255 lines
7.3 KiB
Go
255 lines
7.3 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"household-book/model"
|
|
)
|
|
|
|
type AccountService struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
func (s *AccountService) Reconcile(ctx context.Context, id int64, req model.ReconcileAccountRequest) (*model.AccountReconciliation, error) {
|
|
account, err := s.GetByID(ctx, id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
diff := req.ActualBalance - account.CurrentBalance
|
|
tx, err := s.db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer tx.Rollback()
|
|
var transactionID *int64
|
|
if req.CreateAdjustment && diff != 0 {
|
|
typ := "income"
|
|
amount := diff
|
|
if amount < 0 {
|
|
typ = "expense"
|
|
amount = -amount
|
|
}
|
|
var categoryID int64
|
|
err = tx.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(&categoryID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
r, e := tx.ExecContext(ctx, `INSERT INTO transactions(type,amount,category_id,account_id,date,description,counterparty) VALUES(?,?,?,?,?,?,?)`, typ, amount, categoryID, id, time.Now().Format("2006-01-02"), "账户对账余额调整", "系统对账")
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
tid, _ := r.LastInsertId()
|
|
transactionID = &tid
|
|
}
|
|
r, err := tx.ExecContext(ctx, `INSERT INTO account_reconciliations(account_id,system_balance,actual_balance,difference,transaction_id,note) VALUES(?,?,?,?,?,?)`, id, account.CurrentBalance, req.ActualBalance, diff, transactionID, req.Note)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
rid, _ := r.LastInsertId()
|
|
if err = tx.Commit(); err != nil {
|
|
return nil, err
|
|
}
|
|
return &model.AccountReconciliation{ID: rid, AccountID: id, SystemBalance: account.CurrentBalance, ActualBalance: req.ActualBalance, Difference: diff, TransactionID: transactionID, Note: req.Note}, nil
|
|
}
|
|
|
|
func (s *AccountService) ListReconciliations(ctx context.Context, id int64) ([]model.AccountReconciliation, error) {
|
|
rows, err := s.db.QueryContext(ctx, `SELECT id,account_id,system_balance,actual_balance,difference,transaction_id,note,created_at FROM account_reconciliations WHERE account_id=? ORDER BY id DESC`, id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
items := []model.AccountReconciliation{}
|
|
for rows.Next() {
|
|
var v model.AccountReconciliation
|
|
if err := rows.Scan(&v.ID, &v.AccountID, &v.SystemBalance, &v.ActualBalance, &v.Difference, &v.TransactionID, &v.Note, &v.CreatedAt); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, v)
|
|
}
|
|
return items, rows.Err()
|
|
}
|
|
|
|
func NewAccountService(db *sql.DB) *AccountService {
|
|
return &AccountService{db: db}
|
|
}
|
|
|
|
func (s *AccountService) List(ctx context.Context) ([]model.Account, error) {
|
|
rows, err := s.db.QueryContext(ctx, accountSelectSQL()+" ORDER BY a.id")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("query accounts: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
var list []model.Account
|
|
for rows.Next() {
|
|
var a model.Account
|
|
var isActive int
|
|
if err := rows.Scan(
|
|
&a.ID, &a.Name, &a.Type, &a.Balance, &a.CurrentBalance,
|
|
&a.BankName, &a.CardNumber, &a.BranchName, &a.Note,
|
|
&isActive, &a.CreatedAt, &a.UpdatedAt,
|
|
); err != nil {
|
|
return nil, fmt.Errorf("scan account: %w", err)
|
|
}
|
|
a.IsActive = isActive == 1
|
|
list = append(list, a)
|
|
}
|
|
if list == nil {
|
|
list = []model.Account{}
|
|
}
|
|
return list, rows.Err()
|
|
}
|
|
|
|
func (s *AccountService) GetByID(ctx context.Context, id int64) (*model.Account, error) {
|
|
var a model.Account
|
|
var isActive int
|
|
err := s.db.QueryRowContext(ctx, accountSelectSQL()+" WHERE a.id = ?", id).Scan(
|
|
&a.ID, &a.Name, &a.Type, &a.Balance, &a.CurrentBalance,
|
|
&a.BankName, &a.CardNumber, &a.BranchName, &a.Note,
|
|
&isActive, &a.CreatedAt, &a.UpdatedAt,
|
|
)
|
|
if err == sql.ErrNoRows {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("query account: %w", err)
|
|
}
|
|
a.IsActive = isActive == 1
|
|
return &a, nil
|
|
}
|
|
|
|
func (s *AccountService) Create(ctx context.Context, req model.CreateAccountRequest) (*model.Account, 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 accounts (name, type, balance, bank_name, card_number, branch_name, note)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
req.Name, req.Type, req.Balance, req.BankName, req.CardNumber, req.BranchName, req.Note)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("insert account: %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 *AccountService) Update(ctx context.Context, id int64, req model.UpdateAccountRequest) (*model.Account, error) {
|
|
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.Name != nil {
|
|
sets = append(sets, "name = ?")
|
|
args = append(args, *req.Name)
|
|
}
|
|
if req.Type != nil {
|
|
sets = append(sets, "type = ?")
|
|
args = append(args, *req.Type)
|
|
}
|
|
if req.Balance != nil {
|
|
sets = append(sets, "balance = ?")
|
|
args = append(args, *req.Balance)
|
|
}
|
|
if req.BankName != nil {
|
|
sets = append(sets, "bank_name = ?")
|
|
args = append(args, *req.BankName)
|
|
}
|
|
if req.CardNumber != nil {
|
|
sets = append(sets, "card_number = ?")
|
|
args = append(args, *req.CardNumber)
|
|
}
|
|
if req.BranchName != nil {
|
|
sets = append(sets, "branch_name = ?")
|
|
args = append(args, *req.BranchName)
|
|
}
|
|
if req.Note != nil {
|
|
sets = append(sets, "note = ?")
|
|
args = append(args, *req.Note)
|
|
}
|
|
if req.IsActive != nil {
|
|
isActive := 0
|
|
if *req.IsActive {
|
|
isActive = 1
|
|
}
|
|
sets = append(sets, "is_active = ?")
|
|
args = append(args, isActive)
|
|
}
|
|
|
|
if len(sets) == 0 {
|
|
return s.GetByID(ctx, id)
|
|
}
|
|
|
|
sets = append(sets, "updated_at = datetime('now')")
|
|
args = append(args, id)
|
|
|
|
query := "UPDATE accounts SET " + strings.Join(sets, ", ") + " WHERE id = ?"
|
|
result, err := tx.ExecContext(ctx, query, args...)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("update account: %w", err)
|
|
}
|
|
if affected, err := result.RowsAffected(); err != nil {
|
|
return nil, fmt.Errorf("check updated account: %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 (s *AccountService) Delete(ctx context.Context, id int64) error {
|
|
count, err := countAccountReferences(ctx, s.db, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if count > 0 {
|
|
return ErrHasTransactions
|
|
}
|
|
|
|
result, err := s.db.ExecContext(ctx, "DELETE FROM accounts WHERE id = ?", id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if affected, err := result.RowsAffected(); err != nil {
|
|
return fmt.Errorf("check deleted account: %w", err)
|
|
} else if affected == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func countAccountReferences(ctx context.Context, q sqlQueryer, accountID int64) (int, error) {
|
|
var count int
|
|
if err := q.QueryRowContext(ctx, `
|
|
SELECT
|
|
(SELECT COUNT(*) FROM transactions WHERE account_id = ? OR to_account_id = ?)
|
|
+ (SELECT COUNT(*) FROM assets WHERE account_id = ?)
|
|
+ (SELECT COUNT(*) FROM import_batches WHERE account_id = ?)
|
|
+ (SELECT COUNT(*) FROM account_reconciliations WHERE account_id = ?)`,
|
|
accountID, accountID, accountID, accountID, accountID,
|
|
).Scan(&count); err != nil {
|
|
return 0, fmt.Errorf("check account references: %w", err)
|
|
}
|
|
return count, nil
|
|
}
|