Files

370 lines
12 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package service
import (
"context"
"database/sql"
"fmt"
"log/slog"
"strings"
"time"
"household-book/model"
)
type AssetService struct{ db *sql.DB }
func NewAssetService(db *sql.DB) *AssetService { return &AssetService{db: db} }
func scanAsset(row interface {
Scan(...any) error
}) (model.Asset, error) {
var a model.Asset
var boundBalance int64
if err := row.Scan(&a.ID, &a.Name, &a.Type, &a.Value, &a.AccountID, &a.AccountName, &boundBalance, &a.Note, &a.CreatedAt, &a.UpdatedAt); err != nil {
return a, err
}
if a.AccountID != nil {
a.IsDerived = true
a.Value = boundBalance
}
return a, nil
}
func (s *AssetService) ListAssets(ctx context.Context) ([]model.Asset, error) {
rows, err := s.db.QueryContext(ctx, assetSelectSQL()+" ORDER BY a.type, a.id")
if err != nil {
return nil, fmt.Errorf("query assets: %w", err)
}
defer rows.Close()
var list []model.Asset
for rows.Next() {
a, err := scanAsset(rows)
if err != nil {
return nil, fmt.Errorf("scan asset: %w", err)
}
list = append(list, a)
}
if list == nil {
list = []model.Asset{}
}
return list, rows.Err()
}
func (s *AssetService) CreateAsset(ctx context.Context, req model.CreateAssetRequest) (*model.Asset, error) {
value := req.Value
if req.AccountID != nil {
if err := s.ensureAccountNotBound(ctx, *req.AccountID, 0); err != nil {
return nil, err
}
value = 0 // 绑定账户时实际值由派生计算,存 0 以避免误用
}
result, err := s.db.ExecContext(ctx,
"INSERT INTO assets (name, type, value, account_id, note) VALUES (?, ?, ?, ?, ?)",
req.Name, req.Type, value, req.AccountID, req.Note)
if err != nil {
if isUniqueConstraintError(err) {
return nil, ErrAccountAlreadyBound
}
return nil, fmt.Errorf("insert asset: %w", err)
}
id, _ := result.LastInsertId()
return s.GetAsset(ctx, id)
}
func (s *AssetService) GetAsset(ctx context.Context, id int64) (*model.Asset, error) {
a, err := scanAsset(s.db.QueryRowContext(ctx, assetSelectSQL()+" WHERE a.id = ?", id))
if err == sql.ErrNoRows {
return nil, ErrNotFound
}
if err != nil {
return nil, fmt.Errorf("query asset: %w", err)
}
return &a, nil
}
func (s *AssetService) UpdateAsset(ctx context.Context, id int64, req model.UpdateAssetRequest) (*model.Asset, error) {
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.AccountID.Set {
sets = append(sets, "account_id = ?")
if req.AccountID.Valid {
if err := s.ensureAccountNotBound(ctx, req.AccountID.Value, id); err != nil {
return nil, err
}
args = append(args, req.AccountID.Value)
// 绑定账户时清零 value,避免误展示
sets = append(sets, "value = 0")
} else {
args = append(args, nil)
}
}
if req.Value != nil {
// 仅在未绑定时才允许更新 value(如果同时传了 AccountID 绑定,上面已经清零)
if !(req.AccountID.Set && req.AccountID.Valid) {
sets = append(sets, "value = ?")
args = append(args, *req.Value)
}
}
if req.Note != nil {
sets = append(sets, "note = ?")
args = append(args, *req.Note)
}
if len(sets) == 0 {
return s.GetAsset(ctx, id)
}
sets = append(sets, "updated_at = datetime('now')")
args = append(args, id)
result, err := s.db.ExecContext(ctx, "UPDATE assets SET "+strings.Join(sets, ", ")+" WHERE id = ?", args...)
if err != nil {
if isUniqueConstraintError(err) {
return nil, ErrAccountAlreadyBound
}
return nil, fmt.Errorf("update asset: %w", err)
}
if affected, err := result.RowsAffected(); err != nil {
return nil, err
} else if affected == 0 {
return nil, ErrNotFound
}
return s.GetAsset(ctx, id)
}
func (s *AssetService) DeleteAsset(ctx context.Context, id int64) error {
result, err := s.db.ExecContext(ctx, "DELETE FROM assets WHERE id = ?", id)
if err != nil {
return err
}
if affected, err := result.RowsAffected(); err != nil {
return err
} else if affected == 0 {
return ErrNotFound
}
return nil
}
func (s *AssetService) ListLiabilities(ctx context.Context) ([]model.Liability, error) {
rows, err := s.db.QueryContext(ctx, "SELECT id, name, type, principal, interest_rate, monthly_payment, remaining_terms, note, created_at, updated_at FROM liabilities ORDER BY type, id")
if err != nil {
return nil, fmt.Errorf("query liabilities: %w", err)
}
defer rows.Close()
var list []model.Liability
for rows.Next() {
var l model.Liability
if err := rows.Scan(&l.ID, &l.Name, &l.Type, &l.Principal, &l.InterestRate, &l.MonthlyPayment, &l.RemainingTerms, &l.Note, &l.CreatedAt, &l.UpdatedAt); err != nil {
return nil, fmt.Errorf("scan liability: %w", err)
}
list = append(list, l)
}
if list == nil {
list = []model.Liability{}
}
return list, rows.Err()
}
func (s *AssetService) CreateLiability(ctx context.Context, req model.CreateLiabilityRequest) (*model.Liability, error) {
result, err := s.db.ExecContext(ctx, `INSERT INTO liabilities (name, type, principal, interest_rate, monthly_payment, remaining_terms, note)
VALUES (?, ?, ?, ?, ?, ?, ?)`, req.Name, req.Type, req.Principal, req.InterestRate, req.MonthlyPayment, req.RemainingTerms, req.Note)
if err != nil {
return nil, fmt.Errorf("insert liability: %w", err)
}
id, _ := result.LastInsertId()
return s.GetLiability(ctx, id)
}
func (s *AssetService) GetLiability(ctx context.Context, id int64) (*model.Liability, error) {
var l model.Liability
err := s.db.QueryRowContext(ctx, "SELECT id, name, type, principal, interest_rate, monthly_payment, remaining_terms, note, created_at, updated_at FROM liabilities WHERE id = ?", id).
Scan(&l.ID, &l.Name, &l.Type, &l.Principal, &l.InterestRate, &l.MonthlyPayment, &l.RemainingTerms, &l.Note, &l.CreatedAt, &l.UpdatedAt)
if err == sql.ErrNoRows {
return nil, ErrNotFound
}
if err != nil {
return nil, fmt.Errorf("query liability: %w", err)
}
return &l, nil
}
func (s *AssetService) UpdateLiability(ctx context.Context, id int64, req model.UpdateLiabilityRequest) (*model.Liability, error) {
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.Principal != nil {
sets = append(sets, "principal = ?")
args = append(args, *req.Principal)
}
if req.InterestRate != nil {
sets = append(sets, "interest_rate = ?")
args = append(args, *req.InterestRate)
}
if req.MonthlyPayment != nil {
sets = append(sets, "monthly_payment = ?")
args = append(args, *req.MonthlyPayment)
}
if req.RemainingTerms != nil {
sets = append(sets, "remaining_terms = ?")
args = append(args, *req.RemainingTerms)
}
if req.Note != nil {
sets = append(sets, "note = ?")
args = append(args, *req.Note)
}
if len(sets) == 0 {
return s.GetLiability(ctx, id)
}
sets = append(sets, "updated_at = datetime('now')")
args = append(args, id)
result, err := s.db.ExecContext(ctx, "UPDATE liabilities SET "+strings.Join(sets, ", ")+" WHERE id = ?", args...)
if err != nil {
return nil, fmt.Errorf("update liability: %w", err)
}
if affected, err := result.RowsAffected(); err != nil {
return nil, err
} else if affected == 0 {
return nil, ErrNotFound
}
return s.GetLiability(ctx, id)
}
func (s *AssetService) DeleteLiability(ctx context.Context, id int64) error {
result, err := s.db.ExecContext(ctx, "DELETE FROM liabilities WHERE id = ?", id)
if err != nil {
return err
}
if affected, err := result.RowsAffected(); err != nil {
return err
} else if affected == 0 {
return ErrNotFound
}
return nil
}
func (s *AssetService) NetWorth(ctx context.Context) (*model.NetWorthSummary, error) {
summary, err := s.computeNetWorth(ctx)
if err != nil {
return nil, err
}
return summary, nil
}
// ListSnapshots 返回按日期升序的所有净值快照。
func (s *AssetService) ListSnapshots(ctx context.Context) ([]model.AssetSnapshot, error) {
rows, err := s.db.QueryContext(ctx,
"SELECT id, date, total_asset, total_debt, net_worth, created_at FROM asset_snapshots ORDER BY date ASC, id ASC")
if err != nil {
return nil, fmt.Errorf("query asset snapshots: %w", err)
}
defer rows.Close()
list := []model.AssetSnapshot{}
for rows.Next() {
var snap model.AssetSnapshot
if err := rows.Scan(&snap.ID, &snap.Date, &snap.TotalAsset, &snap.TotalDebt, &snap.NetWorth, &snap.CreatedAt); err != nil {
return nil, fmt.Errorf("scan snapshot: %w", err)
}
list = append(list, snap)
}
return list, rows.Err()
}
// EnsureMonthlySnapshot 保存当月最新净值。date 是月份键(每月 1 日),
// 当月重复运行会更新数值,进入下月后旧月份自然冻结。
func (s *AssetService) EnsureMonthlySnapshot(ctx context.Context, now time.Time) error {
monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
date := monthStart.Format("2006-01-02")
summary, err := s.computeNetWorth(ctx)
if err != nil {
return err
}
totalAsset := summary.TotalAssets + summary.LiquidAssets
totalDebt := summary.TotalDebt + summary.LiquidDebt
if _, err := s.db.ExecContext(ctx,
`INSERT INTO asset_snapshots (date, total_asset, total_debt, net_worth)
VALUES (?, ?, ?, ?)
ON CONFLICT(date) DO UPDATE SET
total_asset = excluded.total_asset,
total_debt = excluded.total_debt,
net_worth = excluded.net_worth,
created_at = datetime('now')`,
date, totalAsset, totalDebt, summary.NetWorth,
); err != nil {
return fmt.Errorf("insert snapshot: %w", err)
}
slog.Info("monthly net worth snapshot refreshed", "month", date[:7], "net_worth", summary.NetWorth)
return nil
}
// RunSnapshotScheduler 启动后台任务:进程启动时立刻补一条当月快照,
// 之后每 6 小时检查一次(覆盖跨月场景)。ctx 取消时退出。
func (s *AssetService) RunSnapshotScheduler(ctx context.Context) {
if err := s.EnsureMonthlySnapshot(ctx, time.Now()); err != nil {
slog.Error("initial snapshot failed", "error", err)
}
ticker := time.NewTicker(6 * time.Hour)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case t := <-ticker.C:
if err := s.EnsureMonthlySnapshot(ctx, t); err != nil {
slog.Error("scheduled snapshot failed", "error", err)
}
}
}
}
// computeNetWorth 共用给 NetWorth 端点和后台快照任务。
//
// - TotalAssets:assets 表总和。绑定到账户的资产 value 列存 0,但派生值已通过 List 计算;
// 这里要把所有 assets 的派生 value 加起来,所以用一段 CTE 把账户余额映射回 assets。
// - LiquidAssets:账户当前余额(非信用卡,正向),且 NOT IN (assets.account_id),避免与上面重复。
// - LiquidDebt:信用卡账户当前余额为负的绝对值。
func (s *AssetService) computeNetWorth(ctx context.Context) (*model.NetWorthSummary, error) {
var summary model.NetWorthSummary
if err := s.db.QueryRowContext(ctx, netWorthSQL()).Scan(
&summary.TotalAssets,
&summary.TotalDebt,
&summary.LiquidAssets,
&summary.LiquidDebt,
); err != nil {
return nil, fmt.Errorf("query net worth: %w", err)
}
summary.NetWorth = summary.TotalAssets + summary.LiquidAssets - summary.TotalDebt - summary.LiquidDebt
return &summary, nil
}
func (s *AssetService) ensureAccountNotBound(ctx context.Context, accountID, excludeAssetID int64) error {
query := "SELECT id FROM assets WHERE account_id = ?"
args := []any{accountID}
if excludeAssetID > 0 {
query += " AND id != ?"
args = append(args, excludeAssetID)
}
var existing int64
err := s.db.QueryRowContext(ctx, query, args...).Scan(&existing)
if err == sql.ErrNoRows {
return nil
}
if err != nil {
return fmt.Errorf("check bound account: %w", err)
}
return ErrAccountAlreadyBound
}