Files
dtf-system/app/api/site_admin.py
Cauê Faleiros c88d81588e 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>
2026-11-09 13:50:45 -03:00

102 lines
4.8 KiB
Python

"""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}