feat: implement Iteration 2 — product management
Backend: - migrations/005: add pg_trgm extension + search indexes on ingredient_mappings - migrations/006: products table with computed expires_at column - ingredient: add Search method (aliases + ILIKE + trgm) + HTTP handler - product: full package — model, repository (CRUD + BatchCreate + ListForPrompt), handler - gemini: add AvailableProducts field to RecipeRequest, include in prompt - recommendation: add ProductLister interface, load user products for personalised prompts - server/main: wire ingredient and product handlers with new routes Flutter: - models: Product, IngredientMapping with json_serializable - ProductService: getProducts, createProduct, updateProduct, deleteProduct, searchIngredients - ProductsNotifier: create/update/delete with optimistic delete - ProductsScreen: expiring-soon section, normal section, swipe-to-delete, edit bottom sheet - AddProductScreen: name field with 300ms debounce autocomplete, qty/unit/days fields - app_router: /products/add route + Badge on Products nav tab showing expiring count - MainShell converted to ConsumerWidget for badge reactivity Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
188
backend/internal/product/repository.go
Normal file
188
backend/internal/product/repository.go
Normal file
@@ -0,0 +1,188 @@
|
||||
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}
|
||||
}
|
||||
|
||||
const selectCols = `id, user_id, mapping_id, name, quantity, unit, category, storage_days, added_at, 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
|
||||
}
|
||||
Reference in New Issue
Block a user