package service import ( "context" "database/sql" "fmt" "time" "github.com/google/uuid" "github.com/muyuqingfeng/iloom/shared/pkg/database" "github.com/muyuqingfeng/iloom/washing-service/internal/model" "github.com/muyuqingfeng/iloom/washing-service/internal/repository" ) type FinishedProductService struct { repo *repository.FinishedProductRepo db *sql.DB } func NewFinishedProductService(repo *repository.FinishedProductRepo, db *sql.DB) *FinishedProductService { return &FinishedProductService{repo: repo, db: db} } func (s *FinishedProductService) List(ctx context.Context, companyID string) ([]model.FinishedProduct, error) { return s.repo.List(ctx, companyID) } func (s *FinishedProductService) Create(ctx context.Context, companyID, userID string, fp *model.FinishedProduct) error { now := time.Now() fp.ID = uuid.New().String() fp.CompanyID = companyID fp.CreatedBy = &userID fp.CreatedAt = now fp.UpdatedAt = now if fp.Status == "" { fp.Status = "in_stock" } fp.StockMeters = fp.WashedMeters fp.StockRolls = 0 if fp.Rolls != nil { fp.StockRolls = *fp.Rolls } return database.WithTx(ctx, s.db, func(tx *sql.Tx) error { return s.repo.Create(ctx, tx, fp) }) } func (s *FinishedProductService) Outbound(ctx context.Context, fpID, companyID, userID string, rolls int, meters float64, notes string) error { return database.WithTx(ctx, s.db, func(tx *sql.Tx) error { if err := s.repo.UpdateStock(ctx, tx, fpID, -meters, -rolls); err != nil { return fmt.Errorf("update stock: %w", err) } var notePtr *string if notes != "" { notePtr = ¬es } rec := &model.FinishedProductInventoryRecord{ ID: uuid.New().String(), FinishedProductID: fpID, CompanyID: companyID, RecordType: "outbound", Rolls: rolls, Meters: meters, Notes: notePtr, OperatorID: &userID, CreatedAt: time.Now(), } return s.repo.CreateInventoryRecord(ctx, tx, rec) }) }