TIMESTAMPTZ + INTERVAL is STABLE (depends on timezone), not IMMUTABLE, so PostgreSQL rejects it in GENERATED ALWAYS AS STORED columns. Fix: remove generated column and compute expires_at inline in each query as (added_at + storage_days * INTERVAL '1 day'). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
192 lines
5.4 KiB
Go
192 lines
5.4 KiB
Go
package product
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// ErrNotFound is returned when a product is not found or does not belong to the user.
|
|
var ErrNotFound = errors.New("product not found")
|
|
|
|
// Repository handles product persistence.
|
|
type Repository struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
// NewRepository creates a new Repository.
|
|
func NewRepository(pool *pgxpool.Pool) *Repository {
|
|
return &Repository{pool: pool}
|
|
}
|
|
|
|
// expires_at is computed in SQL because TIMESTAMPTZ + INTERVAL is STABLE (not IMMUTABLE),
|
|
// which prevents it from being used as a stored generated column.
|
|
const selectCols = `id, user_id, mapping_id, name, quantity, unit, category, storage_days, added_at,
|
|
(added_at + storage_days * INTERVAL '1 day') AS expires_at`
|
|
|
|
// List returns all products for a user, sorted by expires_at ASC.
|
|
func (r *Repository) List(ctx context.Context, userID string) ([]*Product, error) {
|
|
rows, err := r.pool.Query(ctx, `
|
|
SELECT `+selectCols+`
|
|
FROM products
|
|
WHERE user_id = $1
|
|
ORDER BY expires_at ASC`, userID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list products: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
return collectProducts(rows)
|
|
}
|
|
|
|
// Create inserts a new product and returns the created record.
|
|
func (r *Repository) Create(ctx context.Context, userID string, req CreateRequest) (*Product, error) {
|
|
storageDays := req.StorageDays
|
|
if storageDays <= 0 {
|
|
storageDays = 7
|
|
}
|
|
unit := req.Unit
|
|
if unit == "" {
|
|
unit = "pcs"
|
|
}
|
|
qty := req.Quantity
|
|
if qty <= 0 {
|
|
qty = 1
|
|
}
|
|
|
|
row := r.pool.QueryRow(ctx, `
|
|
INSERT INTO products (user_id, mapping_id, name, quantity, unit, category, storage_days)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
|
RETURNING `+selectCols,
|
|
userID, req.MappingID, req.Name, qty, unit, req.Category, storageDays,
|
|
)
|
|
return scanProduct(row)
|
|
}
|
|
|
|
// BatchCreate inserts multiple products sequentially and returns all created records.
|
|
func (r *Repository) BatchCreate(ctx context.Context, userID string, items []CreateRequest) ([]*Product, error) {
|
|
var result []*Product
|
|
for _, req := range items {
|
|
p, err := r.Create(ctx, userID, req)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("batch create product %q: %w", req.Name, err)
|
|
}
|
|
result = append(result, p)
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// Update modifies an existing product. Only non-nil fields are changed.
|
|
// Returns ErrNotFound if the product does not exist or belongs to a different user.
|
|
func (r *Repository) Update(ctx context.Context, id, userID string, req UpdateRequest) (*Product, error) {
|
|
row := r.pool.QueryRow(ctx, `
|
|
UPDATE products SET
|
|
name = COALESCE($3, name),
|
|
quantity = COALESCE($4, quantity),
|
|
unit = COALESCE($5, unit),
|
|
category = COALESCE($6, category),
|
|
storage_days = COALESCE($7, storage_days)
|
|
WHERE id = $1 AND user_id = $2
|
|
RETURNING `+selectCols,
|
|
id, userID, req.Name, req.Quantity, req.Unit, req.Category, req.StorageDays,
|
|
)
|
|
p, err := scanProduct(row)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return p, err
|
|
}
|
|
|
|
// Delete removes a product. Returns ErrNotFound if it does not exist or belongs to a different user.
|
|
func (r *Repository) Delete(ctx context.Context, id, userID string) error {
|
|
tag, err := r.pool.Exec(ctx,
|
|
`DELETE FROM products WHERE id = $1 AND user_id = $2`, id, userID)
|
|
if err != nil {
|
|
return fmt.Errorf("delete product: %w", err)
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ListForPrompt returns a human-readable list of user's products for the AI prompt.
|
|
// Expiring soon items are marked with ⚠.
|
|
func (r *Repository) ListForPrompt(ctx context.Context, userID string) ([]string, error) {
|
|
rows, err := r.pool.Query(ctx, `
|
|
SELECT name, quantity, unit, expires_at
|
|
FROM products
|
|
WHERE user_id = $1
|
|
ORDER BY expires_at ASC`, userID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list products for prompt: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
var lines []string
|
|
now := time.Now()
|
|
for rows.Next() {
|
|
var name, unit string
|
|
var qty float64
|
|
var expiresAt time.Time
|
|
if err := rows.Scan(&name, &qty, &unit, &expiresAt); err != nil {
|
|
return nil, fmt.Errorf("scan product for prompt: %w", err)
|
|
}
|
|
daysLeft := int(expiresAt.Sub(now).Hours() / 24)
|
|
line := fmt.Sprintf("- %s %.0f %s", name, qty, unit)
|
|
switch {
|
|
case daysLeft <= 0:
|
|
line += " (истекает сегодня ⚠)"
|
|
case daysLeft == 1:
|
|
line += " (истекает завтра ⚠)"
|
|
case daysLeft <= 3:
|
|
line += fmt.Sprintf(" (истекает через %d дня ⚠)", daysLeft)
|
|
}
|
|
lines = append(lines, line)
|
|
}
|
|
return lines, rows.Err()
|
|
}
|
|
|
|
// --- helpers ---
|
|
|
|
func scanProduct(row pgx.Row) (*Product, error) {
|
|
var p Product
|
|
err := row.Scan(
|
|
&p.ID, &p.UserID, &p.MappingID, &p.Name, &p.Quantity, &p.Unit,
|
|
&p.Category, &p.StorageDays, &p.AddedAt, &p.ExpiresAt,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
computeDaysLeft(&p)
|
|
return &p, nil
|
|
}
|
|
|
|
func collectProducts(rows pgx.Rows) ([]*Product, error) {
|
|
var result []*Product
|
|
for rows.Next() {
|
|
var p Product
|
|
if err := rows.Scan(
|
|
&p.ID, &p.UserID, &p.MappingID, &p.Name, &p.Quantity, &p.Unit,
|
|
&p.Category, &p.StorageDays, &p.AddedAt, &p.ExpiresAt,
|
|
); err != nil {
|
|
return nil, fmt.Errorf("scan product: %w", err)
|
|
}
|
|
computeDaysLeft(&p)
|
|
result = append(result, &p)
|
|
}
|
|
return result, rows.Err()
|
|
}
|
|
|
|
func computeDaysLeft(p *Product) {
|
|
d := int(time.Until(p.ExpiresAt).Hours() / 24)
|
|
if d < 0 {
|
|
d = 0
|
|
}
|
|
p.DaysLeft = d
|
|
p.ExpiringSoon = d <= 3
|
|
}
|