package repository import ( "context" "database/sql" "errors" "fmt" "strings" "time" ) var ( ErrFreightTemplateNotFound = errors.New("freight template not found") ErrFreightTemplateVersionConflict = errors.New("freight template version conflict") ErrFreightTemplateInUse = errors.New("freight template is referenced by products") ErrFreightTemplateNameExists = errors.New("freight template name already exists") ) // FreightTemplateRecord is product.freight_templates. type FreightTemplateRecord struct { ID string Name string PricingMode int32 DefaultFee *int64 RulesJSON []byte Status int32 Version int32 Scope StoreScope CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time } // FreightTemplateListFilter pages store-scoped templates. type FreightTemplateListFilter struct { Keyword string ExactMatch bool Status *int32 Page, PageSize int32 } // FreightTemplatePatch is an optimistic update. type FreightTemplatePatch struct { ExpectedVersion int32 Name *string PricingMode *int32 DefaultFee *int64 DefaultFeeSet bool RulesJSON *[]byte Status *int32 } func (r *ProductRepository) ensureFreightTemplateSchema(ctx context.Context) error { _, err := r.db.ExecContext(ctx, ` CREATE TABLE IF NOT EXISTS product.freight_templates ( id BIGINT PRIMARY KEY, tenant_id BIGINT NOT NULL, store_id BIGINT NOT NULL, name VARCHAR(64) NOT NULL, pricing_mode SMALLINT NOT NULL DEFAULT 1 CHECK (pricing_mode IN (1, 2)), default_fee BIGINT CHECK (default_fee IS NULL OR default_fee >= 0), rules_json JSONB NOT NULL DEFAULT '{}'::jsonb, status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), deleted_at TIMESTAMPTZ ); CREATE INDEX IF NOT EXISTS idx_freight_templates_store ON product.freight_templates (store_id) WHERE deleted_at IS NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_freight_templates_store_normalized_name_active ON product.freight_templates (store_id, LOWER(BTRIM(name))) WHERE deleted_at IS NULL; `) return err } // CreateFreightTemplate inserts one template. func (r *ProductRepository) CreateFreightTemplate(ctx context.Context, rec FreightTemplateRecord) (*FreightTemplateRecord, error) { if err := requireWriteScope(rec.Scope); err != nil { return nil, err } id, err := parseID(rec.ID, "template_id") if err != nil { return nil, err } rules := rec.RulesJSON if len(rules) == 0 { rules = []byte("{}") } row := r.db.QueryRowContext(ctx, ` INSERT INTO product.freight_templates (id, tenant_id, store_id, name, pricing_mode, default_fee, rules_json, status) VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8) RETURNING id::text, name, pricing_mode, default_fee, rules_json, status, version, created_at, updated_at, deleted_at `, id, rec.Scope.TenantID, rec.Scope.StoreID, rec.Name, rec.PricingMode, nullableInt64(rec.DefaultFee), rules, rec.Status) created, err := scanFreightTemplate(row, rec.Scope) if freightTemplateNameConflictError(err) != nil { return nil, ErrFreightTemplateNameExists } return created, err } // GetFreightTemplate loads one non-deleted template. func (r *ProductRepository) GetFreightTemplate(ctx context.Context, templateID string, scope StoreScope) (*FreightTemplateRecord, error) { if err := requireWriteScope(scope); err != nil { return nil, err } id, err := parseID(templateID, "template_id") if err != nil { return nil, err } row := r.db.QueryRowContext(ctx, ` SELECT id::text, name, pricing_mode, default_fee, rules_json, status, version, created_at, updated_at, deleted_at FROM product.freight_templates WHERE id = $1 AND store_id = $2 AND deleted_at IS NULL `, id, scope.StoreID) rec, err := scanFreightTemplate(row, scope) if errors.Is(err, sql.ErrNoRows) { return nil, ErrFreightTemplateNotFound } return rec, err } // BatchGetActiveFreightTemplates loads the distinct, enabled templates needed // by one storefront page in a single store-scoped query. func (r *ProductRepository) BatchGetActiveFreightTemplates(ctx context.Context, templateIDs []string, scope StoreScope) (map[string]*FreightTemplateRecord, error) { if err := requireWriteScope(scope); err != nil { return nil, err } result := make(map[string]*FreightTemplateRecord) if len(templateIDs) == 0 { return result, nil } placeholders := make([]string, 0, len(templateIDs)) args := make([]any, 0, len(templateIDs)+1) seen := make(map[string]struct{}, len(templateIDs)) for _, templateID := range templateIDs { if _, ok := seen[templateID]; ok { continue } id, err := parseID(templateID, "template_id") if err != nil { return nil, err } seen[templateID] = struct{}{} args = append(args, id) placeholders = append(placeholders, fmt.Sprintf("$%d", len(args))) } args = append(args, scope.StoreID) query := fmt.Sprintf(`SELECT id::text, name, pricing_mode, default_fee, rules_json, status, version, created_at, updated_at, deleted_at FROM product.freight_templates WHERE id IN (%s) AND store_id = $%d AND status = 1 AND deleted_at IS NULL`, strings.Join(placeholders, ","), len(args)) rows, err := r.db.QueryContext(ctx, query, args...) if err != nil { return nil, fmt.Errorf("batch get freight templates: %w", err) } defer rows.Close() for rows.Next() { rec, err := scanFreightTemplate(rows, scope) if err != nil { return nil, fmt.Errorf("scan freight template: %w", err) } result[rec.ID] = rec } if err := rows.Err(); err != nil { return nil, fmt.Errorf("iterate freight templates: %w", err) } return result, nil } // ListFreightTemplates pages templates. func (r *ProductRepository) ListFreightTemplates(ctx context.Context, filter FreightTemplateListFilter, scope StoreScope) ([]FreightTemplateRecord, int64, error) { if err := requireWriteScope(scope); err != nil { return nil, 0, err } page, pageSize := filter.Page, filter.PageSize if page < 1 { page = 1 } if pageSize < 1 { pageSize = 20 } if pageSize > 100 { pageSize = 100 } whereSQL, args := freightTemplateListWhere(filter, scope) var total int64 if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.freight_templates WHERE `+whereSQL, args...).Scan(&total); err != nil { return nil, 0, fmt.Errorf("count freight templates: %w", err) } args = append(args, pageSize, (page-1)*pageSize) rows, err := r.db.QueryContext(ctx, fmt.Sprintf(` SELECT id::text, name, pricing_mode, default_fee, rules_json, status, version, created_at, updated_at, deleted_at FROM product.freight_templates WHERE %s ORDER BY updated_at DESC, id DESC LIMIT $%d OFFSET $%d `, whereSQL, len(args)-1, len(args)), args...) if err != nil { return nil, 0, fmt.Errorf("list freight templates: %w", err) } defer rows.Close() out := make([]FreightTemplateRecord, 0) for rows.Next() { rec, err := scanFreightTemplate(rows, scope) if err != nil { return nil, 0, err } out = append(out, *rec) } return out, total, rows.Err() } // UpdateFreightTemplate applies a patch. func (r *ProductRepository) UpdateFreightTemplate(ctx context.Context, templateID string, patch FreightTemplatePatch, scope StoreScope) (*FreightTemplateRecord, error) { current, err := r.GetFreightTemplate(ctx, templateID, scope) if err != nil { return nil, err } if current.Version != patch.ExpectedVersion { return nil, ErrFreightTemplateVersionConflict } id, err := parseID(templateID, "template_id") if err != nil { return nil, err } name := current.Name if patch.Name != nil { name = strings.TrimSpace(*patch.Name) } mode := current.PricingMode if patch.PricingMode != nil { mode = *patch.PricingMode } fee := current.DefaultFee if patch.DefaultFeeSet { fee = patch.DefaultFee } rules := current.RulesJSON if patch.RulesJSON != nil { rules = *patch.RulesJSON } if len(rules) == 0 { rules = []byte("{}") } st := current.Status if patch.Status != nil { st = *patch.Status } res, err := r.db.ExecContext(ctx, ` UPDATE product.freight_templates SET name = $1, pricing_mode = $2, default_fee = $3, rules_json = $4::jsonb, status = $5, version = version + 1, updated_at = NOW() WHERE id = $6 AND store_id = $7 AND version = $8 AND deleted_at IS NULL `, name, mode, nullableInt64(fee), rules, st, id, scope.StoreID, patch.ExpectedVersion) if err != nil { if freightTemplateNameConflictError(err) != nil { return nil, ErrFreightTemplateNameExists } return nil, fmt.Errorf("update freight template: %w", err) } n, _ := res.RowsAffected() if n == 0 { return nil, ErrFreightTemplateVersionConflict } return r.GetFreightTemplate(ctx, templateID, scope) } func freightTemplateListWhere(filter FreightTemplateListFilter, scope StoreScope) (string, []any) { args := []any{scope.StoreID} where := []string{"store_id = $1", "deleted_at IS NULL"} if kw := strings.TrimSpace(filter.Keyword); kw != "" { args = append(args, kw) if filter.ExactMatch { where = append(where, fmt.Sprintf("LOWER(BTRIM(name)) = LOWER($%d)", len(args))) } else { args[len(args)-1] = "%" + kw + "%" where = append(where, fmt.Sprintf("name ILIKE $%d", len(args))) } } if filter.Status != nil { args = append(args, *filter.Status) where = append(where, fmt.Sprintf("status = $%d", len(args))) } return strings.Join(where, " AND "), args } func freightTemplateNameConflictError(err error) error { if isPostgresConstraintError(err, "23505", "uq_freight_templates_store_normalized_name_active") { return ErrFreightTemplateNameExists } return nil } // DeleteFreightTemplate soft-deletes when unused. func (r *ProductRepository) DeleteFreightTemplate(ctx context.Context, templateID string, expectedVersion int32, scope StoreScope) (*FreightTemplateRecord, error) { current, err := r.GetFreightTemplate(ctx, templateID, scope) if err != nil { return nil, err } if current.Version != expectedVersion { return nil, ErrFreightTemplateVersionConflict } id, err := parseID(templateID, "template_id") if err != nil { return nil, err } var used bool if err := r.db.QueryRowContext(ctx, ` SELECT EXISTS( SELECT 1 FROM product.products WHERE store_id = $1 AND freight_template_id = $2 AND deleted_at IS NULL )`, scope.StoreID, id).Scan(&used); err != nil { return nil, fmt.Errorf("check freight template usage: %w", err) } if used { return nil, ErrFreightTemplateInUse } res, err := r.db.ExecContext(ctx, ` UPDATE product.freight_templates SET deleted_at = NOW(), updated_at = NOW(), version = version + 1 WHERE id = $1 AND store_id = $2 AND version = $3 AND deleted_at IS NULL `, id, scope.StoreID, expectedVersion) if err != nil { return nil, fmt.Errorf("delete freight template: %w", err) } n, _ := res.RowsAffected() if n == 0 { return nil, ErrFreightTemplateVersionConflict } now := time.Now().UTC() current.DeletedAt = &now current.Version++ return current, nil } // FreightTemplateExists reports whether an enabled/non-deleted template exists in the store. func (r *ProductRepository) FreightTemplateExists(ctx context.Context, templateID string, scope StoreScope) error { if err := requireWriteScope(scope); err != nil { return err } id, err := parseID(templateID, "freight_template_id") if err != nil { return err } var ok bool if err := r.db.QueryRowContext(ctx, ` SELECT EXISTS( SELECT 1 FROM product.freight_templates WHERE id = $1 AND store_id = $2 AND deleted_at IS NULL AND status = 1 )`, id, scope.StoreID).Scan(&ok); err != nil { return fmt.Errorf("validate freight template: %w", err) } if !ok { return ErrFreightTemplateNotFound } return nil } type freightScanner interface { Scan(dest ...any) error } func scanFreightTemplate(row freightScanner, scope StoreScope) (*FreightTemplateRecord, error) { var rec FreightTemplateRecord var fee sql.NullInt64 var deleted sql.NullTime var rules []byte if err := row.Scan(&rec.ID, &rec.Name, &rec.PricingMode, &fee, &rules, &rec.Status, &rec.Version, &rec.CreatedAt, &rec.UpdatedAt, &deleted); err != nil { return nil, err } if fee.Valid { v := fee.Int64 rec.DefaultFee = &v } rec.RulesJSON = rules if deleted.Valid { t := deleted.Time rec.DeletedAt = &t } rec.Scope = scope return &rec, nil }