package service import ( "context" "database/sql" "household-book/model" _ "modernc.org/sqlite" "os" "path/filepath" "testing" "time" ) func TestNextPaymentDate(t *testing.T) { if got := nextPaymentDate("2026-01-15", "quarterly"); got != "2026-04-15" { t.Fatalf("got %s", got) } if got := nextPaymentDate("2026-01-15", "single"); got != "" { t.Fatalf("single got %s", got) } } func TestBackupCreateAndStatus(t *testing.T) { dir := t.TempDir() dbPath := filepath.Join(dir, "book.db") db, err := sql.Open("sqlite", dbPath) if err != nil { t.Fatal(err) } defer db.Close() if _, err = db.Exec(`CREATE TABLE sample(id INTEGER); INSERT INTO sample VALUES(1)`); err != nil { t.Fatal(err) } svc := NewBackupService(db, dbPath) svc.now = func() time.Time { return time.Date(2026, 8, 6, 12, 0, 0, 0, time.Local) } status, err := svc.Create(context.Background()) if err != nil { t.Fatal(err) } if status.LastBackup != "2026-08-06.db" { t.Fatalf("status=%+v", status) } if _, err := os.Stat(filepath.Join(dir, "backups", status.LastBackup)); err != nil { t.Fatal(err) } } func TestReconcileCreatesAdjustment(t *testing.T) { db, err := sql.Open("sqlite", ":memory:") if err != nil { t.Fatal(err) } defer db.Close() stmts := []string{ `CREATE TABLE accounts(id INTEGER PRIMARY KEY,name TEXT,type TEXT,balance INTEGER,bank_name TEXT,card_number TEXT,branch_name TEXT,note TEXT,is_active INTEGER,created_at TEXT,updated_at TEXT)`, `CREATE TABLE categories(id INTEGER PRIMARY KEY,name TEXT,type TEXT,parent_id INTEGER,sort_order INTEGER,is_active INTEGER)`, `CREATE TABLE transactions(id INTEGER PRIMARY KEY AUTOINCREMENT,type TEXT,amount INTEGER,category_id INTEGER,account_id INTEGER,to_account_id INTEGER,member_id INTEGER,date TEXT,description TEXT,counterparty TEXT,import_batch_id INTEGER,created_at TEXT DEFAULT '',updated_at TEXT DEFAULT '')`, `CREATE TABLE account_reconciliations(id INTEGER PRIMARY KEY AUTOINCREMENT,account_id INTEGER,system_balance INTEGER,actual_balance INTEGER,difference INTEGER,transaction_id INTEGER,note TEXT,created_at TEXT DEFAULT '')`, `INSERT INTO accounts VALUES(1,'现金','cash',1000,'','','','',1,'','')`, `INSERT INTO categories VALUES(1,'支出','expense',NULL,1,1),(2,'其他','expense',1,1,1),(3,'收入','income',NULL,1,1),(4,'其他','income',3,1,1)`, } for _, s := range stmts { if _, err = db.Exec(s); err != nil { t.Fatal(err) } } v, err := NewAccountService(db).Reconcile(context.Background(), 1, model.ReconcileAccountRequest{ActualBalance: 1500, CreateAdjustment: true}) if err != nil { t.Fatal(err) } if v.Difference != 500 || v.TransactionID == nil { t.Fatalf("result=%+v", v) } a, err := NewAccountService(db).GetByID(context.Background(), 1) if err != nil { t.Fatal(err) } if a.CurrentBalance != 1500 { t.Fatalf("balance=%d", a.CurrentBalance) } }