package service import ( "context" "crypto/sha1" "database/sql" "errors" "fmt" "log/slog" "math" "regexp" "strconv" "strings" "time" "household-book/model" sqlite "modernc.org/sqlite" sqlite3 "modernc.org/sqlite/lib" ) type parsedImportTransaction struct { Type string Amount int64 Date string Description string Counterparty string SourceKey string } var ( debitLineStartRe = regexp.MustCompile(`20\d{2}-\d{2}-\d{2}CNY-?\d{1,3}(?:,\d{3})*\.\d{2}\d{1,3}(?:,\d{3})*\.\d{2}`) debitLineRe = regexp.MustCompile(`^(20\d{2}-\d{2}-\d{2})CNY(-?\d{1,3}(?:,\d{3})*\.\d{2})(\d{1,3}(?:,\d{3})*\.\d{2})(.*)$`) cardSegmentRe = regexp.MustCompile(`支付宝|财付通|京东支付|美团支付|CURSOR`) cardTailRe = regexp.MustCompile(`MVSN([A-Z0-9聚]{1,8}(?:\.[A-Z0-9聚]{2,3})?|[A-Z0-9聚]{3,10})(?:ECN|Erp)\)`) cardRawAmountRe = regexp.MustCompile(`(-?\d{1,3}(?:,\d{3})*\.\d{2})0961`) pageMarkerRe = regexp.MustCompile(`\d{1,2}/\d{1,2}`) creditMonthRe = regexp.MustCompile(`(20\d{2})年(\d{1,2})月`) digitRunRe = regexp.MustCompile(`\d+`) accountNumberRes = []*regexp.Regexp{ regexp.MustCompile(`账号[::]\s*([0-9*]{8,})`), regexp.MustCompile(`Account No\s*([0-9*]{8,})`), regexp.MustCompile(`卡号末四位[^0-9A-Za-z]*([0-9]{4})`), } ) const importPreviewSampleLimit = 1000 func (s *TransactionService) Import(ctx context.Context, req model.ImportTransactionsRequest) (*model.ImportTransactionsResult, error) { items, hintKey, err := parseImportItems(req) if err != nil { return nil, err } tx, err := s.db.BeginTx(ctx, nil) if err != nil { return nil, fmt.Errorf("begin tx: %w", err) } defer tx.Rollback() accountID, err := s.ensureImportAccount(ctx, tx, req, hintKey) if err != nil { return nil, err } batchID, err := s.createImportBatch(ctx, tx, req, accountID) if err != nil { return nil, err } importedIDs := make([]int64, 0, len(items)) skipped := 0 for _, item := range items { categoryID, ok := req.CategoryOverrides[item.SourceKey] var err error if !ok { categoryID, err = s.findCategoryID(ctx, tx, item.Type, item.Description) } if err != nil { return nil, err } result, err := tx.ExecContext(ctx, `INSERT INTO transactions (type, amount, category_id, account_id, date, description, counterparty, source_key, import_batch_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, item.Type, item.Amount, categoryID, accountID, item.Date, item.Description, item.Counterparty, item.SourceKey, batchID, ) if err != nil { if isUniqueConstraintError(err) { skipped++ continue } return nil, fmt.Errorf("insert imported transaction: %w", err) } id, _ := result.LastInsertId() importedIDs = append(importedIDs, id) } if err := s.updateImportBatchStats(ctx, tx, batchID, len(importedIDs), skipped); err != nil { return nil, err } if err := tx.Commit(); err != nil { return nil, fmt.Errorf("commit import: %w", err) } importedItems, err := s.listByIDs(ctx, importedIDs) if err != nil { return nil, err } return &model.ImportTransactionsResult{ ImportedCount: len(importedIDs), SkippedCount: skipped, AccountID: accountID, ImportBatchID: batchID, Items: importedItems, }, nil } // PreviewImport 解析账单并返回预览统计,不写入数据库。 func (s *TransactionService) PreviewImport(ctx context.Context, req model.ImportTransactionsRequest) (*model.ImportPreviewResult, error) { items, hintKey, err := parseImportItems(req) if err != nil { return nil, err } accountName, willCreate, err := s.resolveImportAccountPreview(ctx, req, hintKey) if err != nil { return nil, err } preview := &model.ImportPreviewResult{ TotalCount: len(items), AccountName: accountName, WillCreateAccount: willCreate, Items: make([]model.ImportPreviewItem, 0, min(len(items), importPreviewSampleLimit)), } seen := make(map[string]bool, len(items)) for i, item := range items { status := "new" if seen[item.SourceKey] { status = "duplicate_file" preview.DuplicateCount++ } else { seen[item.SourceKey] = true } var exists int if status == "new" { if err := s.db.QueryRowContext(ctx, "SELECT 1 FROM transactions WHERE source_key = ? LIMIT 1", item.SourceKey, ).Scan(&exists); err != nil && !errors.Is(err, sql.ErrNoRows) { return nil, fmt.Errorf("check duplicate source_key: %w", err) } else if err == nil { status = "duplicate_database" preview.DuplicateCount++ } else { preview.NewCount++ } } categoryName := "" categoryReason := "" var categoryID int64 if status == "new" { var catErr error categoryID, categoryReason, catErr = s.findCategoryWithReason(ctx, s.db, item.Type, item.Description) if catErr != nil { return nil, catErr } if err := s.db.QueryRowContext(ctx, "SELECT name FROM categories WHERE id = ?", categoryID).Scan(&categoryName); err != nil { return nil, fmt.Errorf("query category name: %w", err) } } if i < importPreviewSampleLimit { preview.Items = append(preview.Items, model.ImportPreviewItem{ SourceKey: item.SourceKey, Type: item.Type, Amount: item.Amount, Date: item.Date, Description: item.Description, Counterparty: item.Counterparty, CategoryName: categoryName, CategoryID: categoryID, CategoryReason: categoryReason, Status: status, }) } } return preview, nil } func parseImportItems(req model.ImportTransactionsRequest) ([]parsedImportTransaction, string, error) { req.SourceKind = resolveSourceKind(req) switch req.SourceKind { case "cmb_debit": req.BankName = "招商银行" req.CardType = "debit_card" case "cmb_credit": req.BankName = "招商银行" req.CardType = "credit_card" case "alipay": req.BankName = "支付宝" req.CardType = "alipay" case "wechat": req.BankName = "微信" req.CardType = "wechat" default: return nil, "", fmt.Errorf("unsupported import source %q", req.SourceKind) } var ( items []parsedImportTransaction hintKey string ) switch req.SourceKind { case "cmb_debit": text := extractPDFText(req.Content) hintKey = text items = parseDebitStatement(text, req) case "cmb_credit": text := extractPDFText(req.Content) hintKey = text items = parseCreditCardStatement(text, req) items = mergeCreditRawAmounts(items, parseCreditRawAmounts(extractPDFRawText(req.Content), req, text)) case "alipay": parsed, err := parseAlipayCSV(req) if err != nil { return nil, "", err } items = parsed case "wechat": parsed, err := parseWechatCSV(req) if err != nil { return nil, "", err } items = parsed } if len(items) == 0 { return nil, "", ErrNoImportableTransactions } return items, hintKey, nil } func (s *TransactionService) resolveImportAccountPreview(ctx context.Context, req model.ImportTransactionsRequest, text string) (name string, willCreate bool, err error) { if req.AccountID != nil && *req.AccountID > 0 { err = s.db.QueryRowContext(ctx, "SELECT name FROM accounts WHERE id = ?", *req.AccountID).Scan(&name) if errors.Is(err, sql.ErrNoRows) { return "", false, fmt.Errorf("account %d not found", *req.AccountID) } if err != nil { return "", false, err } return name, false, nil } cardNumber := "" if req.CardType == "debit_card" || req.CardType == "credit_card" { cardNumber = extractAccountNumber(text) } var id int64 err = s.db.QueryRowContext(ctx, `SELECT id, name FROM accounts WHERE type = ? AND COALESCE(bank_name,'') = ? AND (? = '' OR card_number = ?) ORDER BY id LIMIT 1`, req.CardType, req.BankName, cardNumber, cardNumber, ).Scan(&id, &name) if err == nil { return name, false, nil } if !errors.Is(err, sql.ErrNoRows) { return "", false, fmt.Errorf("find import account: %w", err) } return importAccountName(req, cardNumber), true, nil } // resolveSourceKind 解析新 SourceKind 字段;为兼容旧调用,仍接受 BankName + CardType。 func resolveSourceKind(req model.ImportTransactionsRequest) string { switch req.SourceKind { case "cmb_debit", "cmb_credit", "alipay", "wechat": return req.SourceKind case "": // fallthrough default: return req.SourceKind } switch normalizeCardType(req.CardType) { case "debit_card": return "cmb_debit" case "credit_card": return "cmb_credit" } return "" } // parseImportTransactions 兼容现有测试,按 CardType 分发到 PDF 解析器。 func parseImportTransactions(text string, req model.ImportTransactionsRequest) []parsedImportTransaction { switch normalizeCardType(req.CardType) { case "debit_card": return parseDebitStatement(text, req) case "credit_card": return parseCreditCardStatement(text, req) default: return nil } } func parseDebitStatement(text string, req model.ImportTransactionsRequest) []parsedImportTransaction { indexes := debitLineStartRe.FindAllStringIndex(text, -1) items := make([]parsedImportTransaction, 0, len(indexes)) for i, idx := range indexes { end := len(text) if i+1 < len(indexes) { end = indexes[i+1][0] } match := debitLineRe.FindStringSubmatch(text[idx[0]:end]) if len(match) != 5 { continue } amount, err := yuanToCents(match[2]) if err != nil || amount == 0 { continue } typ := "income" if amount < 0 { typ = "expense" amount = -amount } desc := cleanDebitDescription(match[4]) if desc == "" { desc = "招商银行交易流水" } counterparty := extractCounterparty(desc) sourceKey := sourceKey(req, match[1], match[2], desc) items = append(items, parsedImportTransaction{ Type: typ, Amount: amount, Date: match[1], Description: desc, Counterparty: counterparty, SourceKey: sourceKey, }) } return items } func parseCreditCardStatement(text string, req model.ImportTransactionsRequest) []parsedImportTransaction { year, month := inferCreditCardMonth(text, req.Filename) date := fmt.Sprintf("%04d-%02d-01", year, month) matches := cardTailRe.FindAllStringSubmatchIndex(text, -1) items := make([]parsedImportTransaction, 0, len(matches)) for _, match := range matches { token := text[match[2]:match[3]] amount, err := encodedCreditAmountToCents(token) if err != nil || amount <= 0 { continue } desc := creditDescriptionBefore(text, match[0]) if desc == "" { desc = "招商银行信用卡消费" } if strings.Contains(desc, "还款") || strings.Contains(desc, "退款") { continue } typ := "expense" items = append(items, parsedImportTransaction{ Type: typ, Amount: amount, Date: date, Description: desc, Counterparty: extractCounterparty(desc), SourceKey: sourceKey(req, date, fmt.Sprintf("%d", amount), desc), }) } return items } func parseCreditRawAmounts(rawText string, req model.ImportTransactionsRequest, mappedText string) []parsedImportTransaction { year, month := inferCreditCardMonth(mappedText, req.Filename) date := fmt.Sprintf("%04d-%02d-01", year, month) matches := cardRawAmountRe.FindAllStringSubmatch(rawText, -1) items := make([]parsedImportTransaction, 0, len(matches)) for i, match := range matches { amount, err := yuanToCents(match[1]) if err != nil || amount <= 0 { continue } desc := fmt.Sprintf("招商银行信用卡账单消费 #%02d", i+1) items = append(items, parsedImportTransaction{ Type: "expense", Amount: amount, Date: date, Description: desc, Counterparty: "", SourceKey: sourceKey(req, date, fmt.Sprintf("%d", amount), desc), }) } return items } // mergeCreditRawAmounts 是信用卡解析的 fallback 策略: // 当带描述的解析(cardTailRe)漏掉条目时,用纯金额解析(cardRawAmountRe)的结果替补。 // 代价是 raw 分支只有 "招商银行信用卡账单消费 #N" 这种占位描述,准确度较低。 func mergeCreditRawAmounts(parsed, raw []parsedImportTransaction) []parsedImportTransaction { if len(raw) > len(parsed) { slog.Warn("credit card parse fallback to raw amounts", "parsed_count", len(parsed), "raw_count", len(raw)) return raw } return parsed } func inferCreditCardMonth(text, filename string) (int, int) { combined := text + filename if m := creditMonthRe.FindStringSubmatch(combined); len(m) == 3 { year, _ := strconv.Atoi(m[1]) month, _ := strconv.Atoi(m[2]) if month >= 1 && month <= 12 { return year, month } } now := time.Now() return now.Year(), int(now.Month()) } func encodedCreditAmountToCents(token string) (int64, error) { token = strings.TrimPrefix(token, "-") if strings.Contains(token, ".") { parts := strings.SplitN(token, ".", 2) intText := decodeCreditDigits(parts[0]) decText := decodeCreditDigits(parts[1]) if len(decText) > 2 { decText = decText[:2] } if intText == "" || len(decText) != 2 { return 0, fmt.Errorf("invalid encoded amount") } yuan, err := strconv.ParseInt(intText, 10, 64) if err != nil { return 0, err } cents, err := strconv.ParseInt(decText, 10, 64) if err != nil { return 0, err } return yuan*100 + cents, nil } text := decodeCreditDigits(token) if len(text) < 3 { return 0, fmt.Errorf("invalid encoded amount") } if strings.HasSuffix(text, "0") { text = strings.TrimSuffix(text, "0") } value, err := strconv.ParseInt(text, 10, 64) if err != nil { return 0, err } return value, nil } func decodeCreditDigits(value string) string { var b strings.Builder for _, r := range value { switch { case r >= '0' && r <= '9': b.WriteRune(r) case r >= 'M' && r <= 'V': b.WriteRune('0' + (r - 'M')) case r == '聚': b.WriteByte('6') } } return b.String() } func creditDescriptionBefore(text string, offset int) string { start := offset - 80 if start < 0 { start = 0 } window := text[start:offset] for _, sep := range []string{"ECN)", "\u00a0", "\n", "Transaction Details"} { if idx := strings.LastIndex(window, sep); idx >= 0 { window = window[idx+len(sep):] } } if loc := cardSegmentRe.FindStringIndex(window); loc != nil { window = window[loc[0]:] } window = strings.TrimSpace(window) window = strings.Trim(window, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz .-()()") return window } func extractCounterparty(desc string) string { desc = strings.TrimSpace(desc) if desc == "" { return "" } for _, sep := range []string{"-", "-", "—"} { if idx := strings.LastIndex(desc, sep); idx >= 0 && idx+len(sep) < len(desc) { return strings.TrimSpace(desc[idx+len(sep):]) } } for _, prefix := range []string{"快捷支付", "银联快捷支付", "行内转账转入", "转账汇款", "汇入汇款", "代发工资", "代发奖金", "信用卡自动还款"} { if strings.HasPrefix(desc, prefix) { return strings.TrimSpace(strings.TrimPrefix(desc, prefix)) } } return "" } func cleanDebitDescription(desc string) string { desc = strings.TrimSpace(desc) for _, marker := range []string{ "————————————————", "温馨提示", "记账日期货币交易金额", "DateCurrencyTransactionAmount", "招商银行交易流水", } { if idx := strings.Index(desc, marker); idx >= 0 { desc = desc[:idx] } } if loc := pageMarkerRe.FindStringIndex(desc); loc != nil { desc = desc[:loc[0]] } return strings.TrimSpace(desc) } func (s *TransactionService) createImportBatch(ctx context.Context, tx *sql.Tx, req model.ImportTransactionsRequest, accountID int64) (int64, error) { result, err := tx.ExecContext(ctx, `INSERT INTO import_batches (filename, bank_name, card_type, account_id) VALUES (?, ?, ?, ?)`, req.Filename, req.BankName, req.CardType, accountID, ) if err != nil { return 0, fmt.Errorf("create import batch: %w", err) } return result.LastInsertId() } func (s *TransactionService) updateImportBatchStats(ctx context.Context, tx *sql.Tx, batchID int64, imported, skipped int) error { _, err := tx.ExecContext(ctx, `UPDATE import_batches SET imported_count = ?, skipped_count = ? WHERE id = ?`, imported, skipped, batchID, ) if err != nil { return fmt.Errorf("update import batch stats: %w", err) } return nil } func (s *TransactionService) ensureImportAccount(ctx context.Context, tx *sql.Tx, req model.ImportTransactionsRequest, text string) (int64, error) { if req.AccountID != nil && *req.AccountID > 0 { return *req.AccountID, nil } // 银行类来源用 PDF 中的卡号末四位辅助匹配;第三方支付不需要卡号。 cardNumber := "" if req.CardType == "debit_card" || req.CardType == "credit_card" { cardNumber = extractAccountNumber(text) } var id int64 err := tx.QueryRowContext(ctx, `SELECT id FROM accounts WHERE type = ? AND COALESCE(bank_name,'') = ? AND (? = '' OR card_number = ?) ORDER BY id LIMIT 1`, req.CardType, req.BankName, cardNumber, cardNumber, ).Scan(&id) if err == nil { return id, nil } if !errors.Is(err, sql.ErrNoRows) { return 0, fmt.Errorf("find import account: %w", err) } name := importAccountName(req, cardNumber) result, err := tx.ExecContext(ctx, `INSERT INTO accounts (name, type, bank_name, card_number, note) VALUES (?, ?, ?, ?, ?)`, name, req.CardType, req.BankName, cardNumber, "由收支导入自动创建", ) if err != nil { return 0, fmt.Errorf("create import account: %w", err) } return result.LastInsertId() } func importAccountName(req model.ImportTransactionsRequest, cardNumber string) string { switch req.CardType { case "credit_card": name := req.BankName + "信用卡" if cardNumber != "" { name += "(" + lastCardDigits(cardNumber) + ")" } return name case "debit_card": name := req.BankName + "储蓄卡" if cardNumber != "" { name += "(" + lastCardDigits(cardNumber) + ")" } return name case "alipay": return "支付宝" case "wechat": return "微信" default: return req.BankName + "账户" } } type sqlQueryer interface { QueryRowContext(context.Context, string, ...any) *sql.Row QueryContext(context.Context, string, ...any) (*sql.Rows, error) } func (s *TransactionService) findCategoryID(ctx context.Context, q sqlQueryer, typ, desc string) (int64, error) { id, _, err := s.findCategoryWithReason(ctx, q, typ, desc) return id, err } func (s *TransactionService) findCategoryWithReason(ctx context.Context, q sqlQueryer, typ, desc string) (int64, string, error) { if id, ok, err := s.findCategoryByConfiguredKeywords(ctx, q, typ, desc); err != nil { return 0, "", err } else if ok { return id, "关键词匹配", nil } var id int64 err := q.QueryRowContext(ctx, `SELECT id FROM categories WHERE type = ? AND parent_id IS NOT NULL AND is_active = 1 ORDER BY CASE WHEN name = '其他' THEN 0 ELSE 1 END, sort_order, id LIMIT 1`, typ, ).Scan(&id) if err != nil { return 0, "", fmt.Errorf("find fallback category: %w", err) } return id, "未命中关键词,归入其他", nil } // findCategoryByConfiguredKeywords 用 categories.keywords 字段(逗号分隔)匹配交易描述。 // 命中后返回 sort_order 最小的那个分类。 func (s *TransactionService) findCategoryByConfiguredKeywords(ctx context.Context, q sqlQueryer, typ, desc string) (int64, bool, error) { rows, err := q.QueryContext(ctx, `SELECT id, COALESCE(keywords,'') FROM categories WHERE type = ? AND parent_id IS NOT NULL AND is_active = 1 AND keywords <> '' ORDER BY sort_order, id`, typ, ) if err != nil { return 0, false, fmt.Errorf("query keyword categories: %w", err) } defer rows.Close() for rows.Next() { var id int64 var keywords string if err := rows.Scan(&id, &keywords); err != nil { return 0, false, fmt.Errorf("scan keyword category: %w", err) } for _, kw := range strings.Split(keywords, ",") { kw = strings.TrimSpace(kw) if kw == "" { continue } if strings.Contains(desc, kw) { return id, true, nil } } } return 0, false, rows.Err() } func (s *TransactionService) listByIDs(ctx context.Context, ids []int64) ([]model.TransactionListItem, error) { if len(ids) == 0 { return []model.TransactionListItem{}, nil } placeholders := make([]string, len(ids)) args := make([]any, len(ids)) for i, id := range ids { placeholders[i] = "?" args[i] = id } query := `SELECT t.id, t.type, t.amount, t.category_id, COALESCE(c.name,''), COALESCE(c.is_active, 1), t.account_id, COALESCE(a.name,''), t.to_account_id, COALESCE(ta.name,''), t.member_id, COALESCE(m.name,''), t.date, t.description, COALESCE(t.counterparty,''), t.import_batch_id, COALESCE(ib.filename,''), t.created_at, t.updated_at FROM transactions t LEFT JOIN categories c ON t.category_id = c.id LEFT JOIN accounts a ON t.account_id = a.id LEFT JOIN accounts ta ON t.to_account_id = ta.id LEFT JOIN members m ON t.member_id = m.id LEFT JOIN import_batches ib ON t.import_batch_id = ib.id WHERE t.id IN (` + strings.Join(placeholders, ",") + `) ORDER BY t.date DESC, t.id DESC` rows, err := s.db.QueryContext(ctx, query, args...) if err != nil { return nil, fmt.Errorf("query imported transactions: %w", err) } defer rows.Close() items := []model.TransactionListItem{} for rows.Next() { var item model.TransactionListItem var categoryIsActive int if err := rows.Scan( &item.ID, &item.Type, &item.Amount, &item.CategoryID, &item.CategoryName, &categoryIsActive, &item.AccountID, &item.AccountName, &item.ToAccountID, &item.ToAccountName, &item.MemberID, &item.MemberName, &item.Date, &item.Description, &item.Counterparty, &item.ImportBatchID, &item.ImportFilename, &item.CreatedAt, &item.UpdatedAt, ); err != nil { return nil, fmt.Errorf("scan imported transaction: %w", err) } item.CategoryIsActive = categoryIsActive == 1 items = append(items, item) } return items, rows.Err() } func yuanToCents(text string) (int64, error) { clean := strings.ReplaceAll(text, ",", "") value, err := strconv.ParseFloat(clean, 64) if err != nil { return 0, err } return int64(math.Round(value * 100)), nil } func sourceKey(req model.ImportTransactionsRequest, parts ...string) string { h := sha1.New() // 交易身份不得依赖整个文件内容,否则同一交易出现在不同日期范围的账单中会失去防重能力。 h.Write([]byte(resolveSourceKind(req) + "|" + req.BankName + "|" + req.CardType + "|")) for _, part := range parts { h.Write([]byte(part)) h.Write([]byte("|")) } return fmt.Sprintf("import:%x", h.Sum(nil)) } func guessBankName(filename string) string { if strings.Contains(filename, "招商") || strings.Contains(strings.ToLower(filename), "cmb") { return "招商银行" } return "银行" } func normalizeCardType(value string) string { switch value { case "bank_card", "debit", "debit_card": return "debit_card" case "credit", "credit_card": return "credit_card" default: return value } } func extractAccountNumber(text string) string { for _, re := range accountNumberRes { if match := re.FindStringSubmatch(text); len(match) == 2 { return strings.TrimSpace(match[1]) } } return "" } func lastCardDigits(value string) string { digits := digitRunRe.FindAllString(value, -1) joined := strings.Join(digits, "") if len(joined) <= 4 { return joined } return joined[len(joined)-4:] } func isUniqueConstraintError(err error) bool { var serr *sqlite.Error if errors.As(err, &serr) { return serr.Code() == sqlite3.SQLITE_CONSTRAINT_UNIQUE || serr.Code() == sqlite3.SQLITE_CONSTRAINT_PRIMARYKEY } return false }