feat: products and prices from the database, edited in the Kanban's Site tab (front 8.1)

Gestão and the administrators switch each product on and off and set its
price from a start date; a price that has started is history and cannot
change, a scheduled one can be cancelled. The Site and the server read
the current price; with no row the code's prices and TREATMENT_CENTS
still apply, so nothing changes until someone sets one. A switched-off
product disappears from the Site and new quotes with it are refused.
Approved quotes and paid orders keep their price.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 13:50:45 -03:00
parent 4219db8215
commit c88d81588e
20 changed files with 550 additions and 35 deletions

View File

@@ -6,10 +6,10 @@ import httpx
from fastapi import APIRouter, HTTPException, Request, Response
from ..core import db
from .. import mail
from .. import catalog, mail
from ..core.auth import client_ip, owner, new_session, rate_limit
from ..core.limits import upload_limit_bytes
from ..core.pricing import manual_extra_cents, treatment_cents
from ..core.pricing import manual_extra_cents
from ..core.models import FreightAsk, FreightEstimate
from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, delivery_services, freight, payment,
require_delivery_available, storage)
@@ -38,12 +38,18 @@ def session(request: Request, response: Response):
rate_limit('guest-sessions', client_ip(request), GUEST_SESSION_LIMIT, 900)
with db.connect() as c:
session_id = new_session(c, response)
with db.connect() as c:
products = catalog.current(c)
treatment = products['tratamento']
return {'environment': ENVIRONMENT, 'cart_scope': str(session_id), 'part_bytes': PART_BYTES,
'max_upload_bytes': upload_limit_bytes(), 'payment_provider': payment.name,
'password_recovery': mail.configured(),
# Per metre on a finished sheet someone opens by hand (app/core/pricing.py).
'manual_extra_cents': manual_extra_cents(),
'treatment_cents': treatment_cents(),
# Zero keeps the designer's treatment hidden, as an off product does.
'treatment_cents': treatment['unit_cents'] if treatment['enabled'] else 0,
# What the Site sells now: a switched-off product is hidden there.
'products': {mode: products[mode] for mode in catalog.MODES},
# Public by design: Mercado Pago's card form needs it in the browser.
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
# The delivery options the cart quotes, or none: pickup only.

View File

@@ -8,7 +8,7 @@ from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException
from psycopg.types.json import Jsonb
from .. import payments
from .. import catalog, payments
from ..core import db
from ..core.auth import owner
from ..core.models import QuoteRequest
@@ -35,15 +35,19 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
if item.get('stroke_choice'):
item['stroke_choice_at'] = accepted_at
reason = quote_review.review_reason(draft)
if reason is not None:
# Waits for review: check the delivery now, priced at approval.
try:
priced = [price(item.mode, str(item.metres), item.grade) for item in body.items]
freight.quote(body.freight.service, body.freight.postal_code,
sum(Decimal(i['billed_metres']) for i in priced), sum(i['total_cents'] for i in priced))
except ValueError as exc:
raise HTTPException(422, str(exc))
with db.connect() as c:
if reason is not None:
# Waits for review: check the delivery now, priced at approval.
try:
priced = []
for item in body.items:
catalog.require_enabled(c, item.mode)
priced.append(price(item.mode, str(item.metres), item.grade,
unit_cents=catalog.unit_cents(c, item.mode)))
freight.quote(body.freight.service, body.freight.postal_code,
sum(Decimal(i['billed_metres']) for i in priced), sum(i['total_cents'] for i in priced))
except ValueError as exc:
raise HTTPException(422, str(exc))
rows = {}
for item in body.items:
for uid in item.uploads:

101
app/api/site_admin.py Normal file
View File

@@ -0,0 +1,101 @@
"""The Site tab: what the Site sells and at what price, edited by Gestão.
A product is switched on or off here. Prices carry a start date and become
history: a row that has started is never changed or deleted, so only a
scheduled (future) price may be cancelled. Approved quotes keep the price they
were approved with (app/quote_review.py); a switched-off product refuses new
quotes and approvals with 422.
"""
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends, HTTPException
from .. import catalog
from ..core import db
from ..core.auth import audit, can
from ..core.models import SitePriceNew, SiteProductToggle
router = APIRouter()
def price_row(row):
return {'id': row['id'], 'unit_cents': row['unit_cents'],
'starts_at': row['starts_at'].isoformat(), 'created_by': row['created_by'],
'created_at': row['created_at'].isoformat()}
@router.get('/api/operator/site/products')
def site_products(user=Depends(can('manage'))):
with db.connect() as c:
state = catalog.current(c)
now = c.execute('SELECT now() AS now').fetchone()['now']
started = {row['product']: row['unit_cents'] for row in c.execute('''
SELECT DISTINCT ON (product) product, unit_cents
FROM dtf_local.product_prices
WHERE starts_at <= now()
ORDER BY product, starts_at DESC, id DESC''').fetchall()}
rows = c.execute('''SELECT id, product, unit_cents, starts_at, created_by, created_at
FROM dtf_local.product_prices ORDER BY product, created_at DESC, id DESC''').fetchall()
products = []
for product in catalog.PRODUCTS:
prices = [row for row in rows if row['product'] == product]
future = sorted((row for row in prices if row['starts_at'] > now),
key=lambda row: (row['starts_at'], row['id']))
products.append({
'id': product, 'title': catalog.TITLES[product], 'unit': catalog.UNITS[product],
'enabled': state[product]['enabled'],
'unit_cents': state[product]['unit_cents'],
'fallback': product not in started,
'scheduled': [price_row(row) for row in future],
'history': [price_row(row) for row in prices[:20]],
})
return {'products': products}
@router.post('/api/operator/site/products/{product}')
def toggle_product(product: str, body: SiteProductToggle, user=Depends(can('manage'))):
if product not in catalog.PRODUCTS:
raise HTTPException(404, 'Produto não encontrado.')
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.products(id, enabled, updated_by, updated_at)
VALUES(%s,%s,%s,now())
ON CONFLICT (id) DO UPDATE SET enabled=EXCLUDED.enabled,
updated_by=EXCLUDED.updated_by, updated_at=now()''',
(product, body.enabled, user))
audit('site_product_changed', product=product, enabled=body.enabled, operator=user)
return {'ok': True}
@router.post('/api/operator/site/products/{product}/prices')
def schedule_price(product: str, body: SitePriceNew, user=Depends(can('manage'))):
if product not in catalog.PRODUCTS:
raise HTTPException(404, 'Produto não encontrado.')
if product != 'tratamento' and body.unit_cents <= 0:
raise HTTPException(422, 'O preço precisa ser maior que zero.')
now = datetime.now(timezone.utc)
starts_at = body.starts_at or now
if starts_at.tzinfo is None:
starts_at = starts_at.replace(tzinfo=timezone.utc)
if starts_at < now - timedelta(minutes=1):
raise HTTPException(422, 'A data de início não pode estar no passado.')
with db.connect() as c:
row = c.execute('''INSERT INTO dtf_local.product_prices(product, unit_cents, starts_at, created_by)
VALUES(%s,%s,%s,%s) RETURNING id''',
(product, body.unit_cents, starts_at, user)).fetchone()
audit('site_price_changed', product=product, unit_cents=body.unit_cents,
starts_at=starts_at.isoformat(), operator=user)
return {'id': row['id']}
@router.post('/api/operator/site/prices/{price_id}/cancel')
def cancel_price(price_id: int, user=Depends(can('manage'))):
with db.connect() as c:
row = c.execute('''SELECT id, product, unit_cents, starts_at
FROM dtf_local.product_prices WHERE id=%s FOR UPDATE''', (price_id,)).fetchone()
if not row:
raise HTTPException(404, 'Preço não encontrado.')
if row['starts_at'] <= datetime.now(timezone.utc):
raise HTTPException(409, 'Este preço já começou: o histórico não pode ser apagado.')
c.execute('DELETE FROM dtf_local.product_prices WHERE id=%s', (price_id,))
audit('site_price_cancelled', price=price_id, product=row['product'], operator=user)
return {'ok': True}