package service import ( "context" "database/sql" "fmt" "strings" "household-book/model" ) type TransactionService struct { db *sql.DB } func NewTransactionService(db *sql.DB) *TransactionService { return &TransactionService{db: db} } func (s *TransactionService) List(ctx context.Context, req model.TransactionListRequest) (*model.TransactionListResponse, error) { var conditions []string var args []any if req.Month != "" { conditions = append(conditions, "t.date LIKE ?") args = append(args, req.Month+"%") } if req.DateFrom != "" { conditions = append(conditions, "t.date >= ?") args = append(args, req.DateFrom) } if req.DateTo != "" { conditions = append(conditions, "t.date <= ?") args = append(args, req.DateTo) } if req.CategoryID != nil { conditions = append(conditions, "t.category_id = ?") args = append(args, *req.CategoryID) } if req.Type != "" { conditions = append(conditions, "t.type = ?") args = append(args, req.Type) } if req.MemberID != nil { conditions = append(conditions, "t.member_id = ?") args = append(args, *req.MemberID) } if req.AccountID != nil { conditions = append(conditions, "(t.account_id = ? OR t.to_account_id = ?)") args = append(args, *req.AccountID, *req.AccountID) } if req.ImportBatchID != nil { conditions = append(conditions, "t.import_batch_id = ?") args = append(args, *req.ImportBatchID) } if req.Keyword != "" { conditions = append(conditions, "(t.description LIKE ? OR t.counterparty LIKE ?)") args = append(args, "%"+req.Keyword+"%", "%"+req.Keyword+"%") } where := "" if len(conditions) > 0 { where = " WHERE " + strings.Join(conditions, " AND ") } // Count total var total int countQuery := "SELECT COUNT(*) FROM transactions t" + where if err := s.db.QueryRowContext(ctx, countQuery, args...).Scan(&total); err != nil { return nil, fmt.Errorf("count transactions: %w", err) } // Pagination if req.Page < 1 { req.Page = 1 } if req.PageSize < 1 { req.PageSize = 20 } offset := (req.Page - 1) * req.PageSize 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 + " ORDER BY t.date DESC, t.id DESC LIMIT ? OFFSET ?" fullArgs := append(args, req.PageSize, offset) rows, err := s.db.QueryContext(ctx, query, fullArgs...) if err != nil { return nil, fmt.Errorf("query transactions: %w", err) } defer rows.Close() var 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 transaction: %w", err) } item.CategoryIsActive = categoryIsActive == 1 items = append(items, item) } if items == nil { items = []model.TransactionListItem{} } return &model.TransactionListResponse{ Items: items, Total: total, Page: req.Page, PageSize: req.PageSize, }, rows.Err() } func (s *TransactionService) GetByID(ctx context.Context, id int64) (*model.Transaction, error) { var t model.Transaction err := s.db.QueryRowContext(ctx, `SELECT id, type, amount, category_id, account_id, to_account_id, member_id, date, description, COALESCE(counterparty,''), import_batch_id, created_at, updated_at FROM transactions WHERE id = ?`, id, ).Scan(&t.ID, &t.Type, &t.Amount, &t.CategoryID, &t.AccountID, &t.ToAccountID, &t.MemberID, &t.Date, &t.Description, &t.Counterparty, &t.ImportBatchID, &t.CreatedAt, &t.UpdatedAt) if err == sql.ErrNoRows { return nil, ErrNotFound } if err != nil { return nil, fmt.Errorf("query transaction: %w", err) } return &t, nil } func (s *TransactionService) Create(ctx context.Context, req model.CreateTransactionRequest) (*model.Transaction, error) { tx, err := s.db.BeginTx(ctx, nil) if err != nil { return nil, fmt.Errorf("begin tx: %w", err) } defer tx.Rollback() result, err := tx.ExecContext(ctx, `INSERT INTO transactions (type, amount, category_id, account_id, to_account_id, member_id, date, description, counterparty) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, req.Type, req.Amount, req.CategoryID, req.AccountID, req.ToAccountID, req.MemberID, req.Date, req.Description, req.Counterparty) if err != nil { return nil, fmt.Errorf("insert transaction: %w", err) } id, _ := result.LastInsertId() if err := tx.Commit(); err != nil { return nil, fmt.Errorf("commit: %w", err) } return s.GetByID(ctx, id) } func (s *TransactionService) Update(ctx context.Context, id int64, req model.UpdateTransactionRequest) (*model.Transaction, error) { current, err := s.GetByID(ctx, id) if err != nil { return nil, err } merged := *current mergeTransactionUpdate(&merged, req) if err := validateTransactionFields(merged.Type, merged.CategoryID, merged.AccountID, merged.ToAccountID); 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() var sets []string var args []any if req.Type != nil { sets = append(sets, "type = ?") args = append(args, *req.Type) } if req.Amount != nil { sets = append(sets, "amount = ?") args = append(args, *req.Amount) } if req.CategoryID.Set { sets = append(sets, "category_id = ?") if req.CategoryID.Valid { args = append(args, req.CategoryID.Value) } else { args = append(args, nil) } } if req.AccountID.Set { sets = append(sets, "account_id = ?") if req.AccountID.Valid { args = append(args, req.AccountID.Value) } else { args = append(args, nil) } } if req.ToAccountID.Set { sets = append(sets, "to_account_id = ?") if req.ToAccountID.Valid { args = append(args, req.ToAccountID.Value) } else { args = append(args, nil) } } if req.MemberID.Set { sets = append(sets, "member_id = ?") if req.MemberID.Valid { args = append(args, req.MemberID.Value) } else { args = append(args, nil) } } if req.Date != nil { sets = append(sets, "date = ?") args = append(args, *req.Date) } if req.Description != nil { sets = append(sets, "description = ?") args = append(args, *req.Description) } if req.Counterparty != nil { sets = append(sets, "counterparty = ?") args = append(args, *req.Counterparty) } if len(sets) == 0 { return s.GetByID(ctx, id) } sets = append(sets, "updated_at = datetime('now')") args = append(args, id) query := "UPDATE transactions SET " + strings.Join(sets, ", ") + " WHERE id = ?" result, err := tx.ExecContext(ctx, query, args...) if err != nil { return nil, fmt.Errorf("update transaction: %w", err) } if affected, err := result.RowsAffected(); err != nil { return nil, fmt.Errorf("check updated transaction: %w", err) } else if affected == 0 { return nil, ErrNotFound } if err := tx.Commit(); err != nil { return nil, fmt.Errorf("commit: %w", err) } return s.GetByID(ctx, id) } func mergeTransactionUpdate(t *model.Transaction, req model.UpdateTransactionRequest) { if req.Type != nil { t.Type = *req.Type } if req.CategoryID.Set { if req.CategoryID.Valid { v := req.CategoryID.Value t.CategoryID = &v } else { t.CategoryID = nil } } if req.AccountID.Set { if req.AccountID.Valid { v := req.AccountID.Value t.AccountID = &v } else { t.AccountID = nil } } if req.ToAccountID.Set { if req.ToAccountID.Valid { v := req.ToAccountID.Value t.ToAccountID = &v } else { t.ToAccountID = nil } } } func validateTransactionFields(typ string, categoryID, accountID, toAccountID *int64) error { if typ == "transfer" { if categoryID != nil || accountID == nil || toAccountID == nil || *accountID == *toAccountID { return ErrInvalidTransaction } return nil } if (typ != "income" && typ != "expense") || categoryID == nil || *categoryID <= 0 || toAccountID != nil { return ErrInvalidTransaction } return nil } func (s *TransactionService) Delete(ctx context.Context, id int64) error { result, err := s.db.ExecContext(ctx, "DELETE FROM transactions WHERE id = ?", id) if err != nil { return err } if affected, err := result.RowsAffected(); err != nil { return fmt.Errorf("check deleted transaction: %w", err) } else if affected == 0 { return ErrNotFound } return nil } func (s *TransactionService) DeleteBatch(ctx context.Context, ids []int64) (int64, error) { if len(ids) == 0 { return 0, nil } placeholders := make([]string, len(ids)) args := make([]any, len(ids)) for i, id := range ids { placeholders[i] = "?" args[i] = id } result, err := s.db.ExecContext(ctx, "DELETE FROM transactions WHERE id IN ("+strings.Join(placeholders, ",")+")", args...) if err != nil { return 0, fmt.Errorf("delete transactions: %w", err) } return result.RowsAffected() } func (s *TransactionService) ListImportBatches(ctx context.Context) ([]model.ImportBatch, error) { rows, err := s.db.QueryContext(ctx, `SELECT ib.id, ib.filename, ib.bank_name, ib.card_type, ib.account_id, COALESCE(a.name,''), ib.imported_count, ib.skipped_count, ib.created_at FROM import_batches ib LEFT JOIN accounts a ON ib.account_id = a.id ORDER BY ib.created_at DESC, ib.id DESC`) if err != nil { return nil, fmt.Errorf("query import batches: %w", err) } defer rows.Close() var batches []model.ImportBatch for rows.Next() { var b model.ImportBatch if err := rows.Scan(&b.ID, &b.Filename, &b.BankName, &b.CardType, &b.AccountID, &b.AccountName, &b.ImportedCount, &b.SkippedCount, &b.CreatedAt); err != nil { return nil, fmt.Errorf("scan import batch: %w", err) } batches = append(batches, b) } if batches == nil { batches = []model.ImportBatch{} } return batches, rows.Err() } func (s *TransactionService) DeleteImportBatch(ctx context.Context, batchID int64) (int64, error) { tx, err := s.db.BeginTx(ctx, nil) if err != nil { return 0, fmt.Errorf("begin tx: %w", err) } defer tx.Rollback() var batchAccountID sql.NullInt64 if err := tx.QueryRowContext(ctx, "SELECT account_id FROM import_batches WHERE id = ?", batchID).Scan(&batchAccountID); err != nil && err != sql.ErrNoRows { return 0, fmt.Errorf("load import batch: %w", err) } result, err := tx.ExecContext(ctx, "DELETE FROM transactions WHERE import_batch_id = ?", batchID) if err != nil { return 0, fmt.Errorf("delete imported transactions: %w", err) } deleted, err := result.RowsAffected() if err != nil { return 0, fmt.Errorf("check deleted imported transactions: %w", err) } if _, err := tx.ExecContext(ctx, "DELETE FROM import_batches WHERE id = ?", batchID); err != nil { return 0, fmt.Errorf("delete import batch: %w", err) } if batchAccountID.Valid { if err := s.cleanupAutoImportAccount(ctx, tx, batchAccountID.Int64); err != nil { return 0, err } } if err := tx.Commit(); err != nil { return 0, fmt.Errorf("commit: %w", err) } return deleted, nil } // cleanupAutoImportAccount 删除"由收支导入自动创建"且不再被任何交易、其他导入批次引用的账户。 // 用 note 字段做标识,避免误删用户手动创建的账户。 func (s *TransactionService) cleanupAutoImportAccount(ctx context.Context, tx *sql.Tx, accountID int64) error { const autoCreatedNote = "由收支导入自动创建" var note string if err := tx.QueryRowContext(ctx, "SELECT COALESCE(note,'') FROM accounts WHERE id = ?", accountID).Scan(¬e); err != nil { if err == sql.ErrNoRows { return nil } return fmt.Errorf("load account note: %w", err) } if note != autoCreatedNote { return nil } refs, err := countAccountReferences(ctx, tx, accountID) if err != nil { return err } if refs > 0 { return nil } if _, err := tx.ExecContext(ctx, "DELETE FROM accounts WHERE id = ?", accountID); err != nil { return fmt.Errorf("delete orphan account: %w", err) } return nil }