71 lines
2.2 KiB
Go
71 lines
2.2 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"git.sundynix.cn/Blizzard/Veyra/internal/apperror"
|
|
"git.sundynix.cn/Blizzard/Veyra/internal/model"
|
|
)
|
|
|
|
type AccountRepository interface {
|
|
Create(context.Context, model.Account, *model.CashEntry) (model.AccountSummary, error)
|
|
List(context.Context, string) ([]model.AccountSummary, error)
|
|
Get(context.Context, string, string) (model.AccountSummary, error)
|
|
}
|
|
|
|
type AccountService struct{ repo AccountRepository }
|
|
|
|
func NewAccountService(repo AccountRepository) *AccountService { return &AccountService{repo: repo} }
|
|
|
|
func (s *AccountService) Create(ctx context.Context, userID, mode, name string, initialCash *string) (model.AccountSummary, error) {
|
|
if s.repo == nil {
|
|
return model.AccountSummary{}, apperror.ErrUnavailable
|
|
}
|
|
name = strings.TrimSpace(name)
|
|
if name == "" || utf8.RuneCountInString(name) > 80 {
|
|
return model.AccountSummary{}, apperror.ErrInvalidInput
|
|
}
|
|
account := model.Account{ID: uuid.NewString(), UserID: userID, Mode: mode, Name: name, Currency: "CNY", LedgerStatus: "INCOMPLETE"}
|
|
var entry *model.CashEntry
|
|
switch mode {
|
|
case "simulation":
|
|
if initialCash == nil {
|
|
return model.AccountSummary{}, apperror.ErrInvalidInput
|
|
}
|
|
amount, err := model.ParseMoney(*initialCash)
|
|
if err != nil {
|
|
return model.AccountSummary{}, err
|
|
}
|
|
account.LedgerStatus = "COMPLETE"
|
|
entry = &model.CashEntry{ID: uuid.NewString(), AccountID: account.ID, EntryType: "INITIAL", AmountMinor: amount}
|
|
case "manual_real":
|
|
if initialCash != nil {
|
|
return model.AccountSummary{}, apperror.ErrInvalidInput
|
|
}
|
|
default:
|
|
return model.AccountSummary{}, apperror.ErrInvalidInput
|
|
}
|
|
return s.repo.Create(ctx, account, entry)
|
|
}
|
|
|
|
func (s *AccountService) List(ctx context.Context, userID string) ([]model.AccountSummary, error) {
|
|
if s.repo == nil {
|
|
return nil, apperror.ErrUnavailable
|
|
}
|
|
return s.repo.List(ctx, userID)
|
|
}
|
|
|
|
func (s *AccountService) Get(ctx context.Context, userID, accountID string) (model.AccountSummary, error) {
|
|
if s.repo == nil {
|
|
return model.AccountSummary{}, apperror.ErrUnavailable
|
|
}
|
|
if _, err := uuid.Parse(accountID); err != nil {
|
|
return model.AccountSummary{}, apperror.ErrNotFound
|
|
}
|
|
return s.repo.Get(ctx, userID, accountID)
|
|
}
|