87 lines
2.6 KiB
Go
Raw Permalink Normal View History

package repository
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/muyuqingfeng/iloom/purchaser-service/internal/model"
)
type WashingPlanRepo struct {
db *sql.DB
}
func NewWashingPlanRepo(db *sql.DB) *WashingPlanRepo {
return &WashingPlanRepo{db: db}
}
func (r *WashingPlanRepo) Create(ctx context.Context, wp *model.WashingPlan) error {
query := `INSERT INTO ilm_washing_plan
(id, plan_code, company_id, product_id, washing_factory_id,
planned_meters, washing_price, estimated_shrinkage_rate,
estimated_washed_meters, estimated_total_cost,
status, notes, created_by, created_at, updated_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`
_, err := r.db.ExecContext(ctx, query,
wp.ID, wp.PlanCode, wp.CompanyID, wp.ProductID, wp.WashingFactoryID,
wp.PlannedMeters, wp.WashingPrice, wp.EstimatedShrinkageRate,
wp.EstimatedWashedMeters, wp.EstimatedTotalCost,
wp.Status, wp.Notes, wp.CreatedBy, wp.CreatedAt, wp.UpdatedAt,
)
if err != nil {
return fmt.Errorf("insert washing plan: %w", err)
}
return nil
}
func (r *WashingPlanRepo) List(ctx context.Context, companyID string) ([]model.WashingPlan, error) {
query := `SELECT id, plan_code, company_id, product_id, washing_factory_id,
planned_meters, washing_price, estimated_shrinkage_rate,
estimated_washed_meters, estimated_total_cost,
actual_shrinkage_rate, actual_washed_meters, actual_total_cost,
washing_date, status, notes, created_by, created_at, updated_at
FROM ilm_washing_plan WHERE company_id = ?
ORDER BY created_at DESC`
rows, err := r.db.QueryContext(ctx, query, companyID)
if err != nil {
return nil, fmt.Errorf("list washing plans: %w", err)
}
defer rows.Close()
var plans []model.WashingPlan
for rows.Next() {
var wp model.WashingPlan
if err := rows.Scan(
&wp.ID, &wp.PlanCode, &wp.CompanyID, &wp.ProductID, &wp.WashingFactoryID,
&wp.PlannedMeters, &wp.WashingPrice, &wp.EstimatedShrinkageRate,
&wp.EstimatedWashedMeters, &wp.EstimatedTotalCost,
&wp.ActualShrinkageRate, &wp.ActualWashedMeters, &wp.ActualTotalCost,
&wp.WashingDate, &wp.Status, &wp.Notes, &wp.CreatedBy,
&wp.CreatedAt, &wp.UpdatedAt,
); err != nil {
return nil, fmt.Errorf("scan washing plan: %w", err)
}
plans = append(plans, wp)
}
return plans, nil
}
func (r *WashingPlanRepo) GeneratePlanCode(ctx context.Context) (string, error) {
today := time.Now().Format("20060102")
prefix := "WP" + today
var count int
err := r.db.QueryRowContext(ctx,
`SELECT COUNT(*) FROM ilm_washing_plan WHERE plan_code LIKE ?`,
prefix+"%",
).Scan(&count)
if err != nil {
return "", fmt.Errorf("generate plan code: %w", err)
}
return fmt.Sprintf("%s%03d", prefix, count+1), nil
}