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}

View File

@@ -13,7 +13,7 @@ from starlette.middleware.trustedhost import TrustedHostMiddleware
from .core import db
from .core.auth import audit, client_ip
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage
from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_videos, uploads, users
from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, uploads, users
@asynccontextmanager
@@ -45,5 +45,5 @@ async def safe_headers(request, call_next):
# Order is not significant: no two routers declare the same path.
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, reviews, machine_log):
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, site_admin, reviews, machine_log):
app.include_router(module.router)

63
app/catalog.py Normal file
View File

@@ -0,0 +1,63 @@
"""What the Site sells and at what price, edited in the Kanban's Site tab.
Dropstar, 2026-11-05 (Fase 2, front 8): the products and their prices leave the
code and live in the database, with a start date and a history. `PRICES` in
app/core/pricing.py stays as the seed and the fallback for the four modes;
`treatment_cents()` stays as the fallback for `tratamento`. A price row is never
changed or deleted once its start date has passed (the table is the history),
and an approved quote keeps the price it was approved with.
`tratamento` is the designer's treatment (front 5), a fixed amount per order:
it counts as offered only when it is switched on and priced above zero.
"""
from fastapi import HTTPException
from .core import pricing
# The four modes sold by the metre, and the treatment sold per order.
MODES = ('file', 'avulsa', 'uvfile', 'uv')
PRODUCTS = (*MODES, 'tratamento')
TITLES = {
'file': 'Têxtil folha pronta',
'avulsa': 'Têxtil artes avulsas',
'uvfile': 'UV folha pronta',
'uv': 'UV artes avulsas',
'tratamento': 'Tratamento pelo designer',
}
UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro',
'tratamento': 'pedido'}
def fallback_cents(product: str) -> int:
"""The price in the code, used until a row in the database takes over."""
return pricing.treatment_cents() if product == 'tratamento' else pricing.PRICES[product]
def current(c) -> dict:
"""{'file': {'enabled': bool, 'unit_cents': int}, ...}: what is sold now."""
enabled = {row['id']: row['enabled'] for row in
c.execute('SELECT id, enabled FROM dtf_local.products').fetchall()}
prices = {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()}
return {product: {'enabled': bool(enabled.get(product, True)),
'unit_cents': prices.get(product, fallback_cents(product))}
for product in PRODUCTS}
def unit_cents(c, product: str) -> int:
"""The current price of one product, or the fallback."""
row = c.execute('''SELECT unit_cents FROM dtf_local.product_prices
WHERE product=%s AND starts_at <= now()
ORDER BY starts_at DESC, id DESC LIMIT 1''', (product,)).fetchone()
return row['unit_cents'] if row else fallback_cents(product)
def require_enabled(c, product: str) -> None:
"""Refuse a product someone switched off in the Kanban's Site tab."""
row = c.execute('SELECT enabled FROM dtf_local.products WHERE id=%s', (product,)).fetchone()
if row and not row['enabled']:
raise HTTPException(422, 'Este produto não está à venda agora.')

View File

@@ -1,5 +1,5 @@
import re
from datetime import date
from datetime import date, datetime
from decimal import Decimal
from typing import Literal
from uuid import UUID
@@ -352,6 +352,17 @@ class MachineSheet(StrictModel):
minimums: dict[str, Decimal | None] = Field(default_factory=dict)
class SiteProductToggle(StrictModel):
"""Ligar ou desligar um produto na aba Site (Fase 2, front 8)."""
enabled: bool
class SitePriceNew(StrictModel):
"""Um novo preço e a data em que começa; sem data, começa agora."""
unit_cents: int = Field(ge=0, le=10000000, strict=True)
starts_at: datetime | None = None
class Contraction(StrictModel):
item_index: int = Field(ge=0, le=100)
# None returns the item to the class the browser measured.

View File

@@ -44,10 +44,12 @@ def is_manual(item, names) -> bool:
for source in item['production']['sources'])
def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Decimal = Decimal('1')) -> dict:
def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Decimal = Decimal('1'),
unit_cents: int | None = None) -> dict:
"""The item's charge. The grade is validated and kept with the item; the
price does not depend on it. A split sheet has no minimum of its own: its
group has one (bill_splits)."""
group has one (bill_splits). `unit_cents` is the current price from the
database (app/catalog.py); without it, the table above."""
length = Decimal(str(metres))
if mode not in PRICES or not length.is_finite() or not 0 < length <= 12000:
raise ValueError('Invalid product or length')
@@ -56,7 +58,7 @@ def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Dec
billed = max(minimum, (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10)
if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
raise ValueError('Invalid extra charge')
unit = PRICES[mode] + extra_cents
unit = (PRICES[mode] if unit_cents is None else unit_cents) + extra_cents
priced = {'mode': mode, 'metres': str(length), 'grade': grade,
'billed_metres': str(billed), 'unit_cents': unit,
'total_cents': int(billed * unit)}

View File

@@ -19,10 +19,10 @@ from decimal import Decimal
from fastapi import HTTPException
from psycopg.types.json import Jsonb
from . import payments
from . import catalog, payments
from .proof import PROOF_ABOVE_METRES
from .core.models import PRODUCTION_VERSIONS
from .core.pricing import bill_splits, is_manual, manual_extra_cents, price, treatment_cents
from .core.pricing import bill_splits, is_manual, manual_extra_cents, price
from .runtime import freight, upload_row
from .scanning import require_clean
@@ -71,9 +71,11 @@ def approve(c, row, items, reviewer):
upload = upload_row(c, upload_id, row['owner'])
require_clean(upload)
names[str(upload_id)] = upload['name']
catalog.require_enabled(c, item.mode)
extra = manual_extra_cents() if is_manual(original, names) else 0
priced.append({**price(item.mode, str(item.metres), item.grade, extra,
minimum=Decimal('0') if item.split else Decimal('1')),
minimum=Decimal('0') if item.split else Decimal('1'),
unit_cents=catalog.unit_cents(c, item.mode)),
'uploads': original['uploads'], 'production': original['production'],
'quality_status': original['quality_status'],
'quality_acknowledged': original['quality_acknowledged'],
@@ -96,7 +98,11 @@ def approve(c, row, items, reviewer):
metres, sum(i['total_cents'] for i in priced))
except ValueError as exc:
raise HTTPException(422, str(exc))
treatment = treatment_cents() if draft.get('treatment') else 0
treatment = 0
if draft.get('treatment'):
# The designer's treatment is offered only when switched on and priced.
offer = catalog.current(c)['tratamento']
treatment = offer['unit_cents'] if offer['enabled'] else 0
approved = {'customer': draft['customer'], 'items': priced, 'freight': quoted_freight,
'destination': draft.get('destination'),
# The customer's proof only above 10 m (Dropstar, 2026-10-28).

View File

@@ -12,6 +12,7 @@ from uuid import uuid5, NAMESPACE_URL
from fastapi import HTTPException
from psycopg.types.json import Jsonb
from . import catalog
from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime
from .freight import FreightOptions
from .core.secrets import load as load_secret_files
@@ -33,7 +34,6 @@ if os.environ.get('FREIGHT_ADAPTER') == 'jadlog':
_carriers.append(JadlogFreight())
from . import correios as _correios
from . import prumo
from .core.pricing import treatment_cents
if _correios.configured():
_carriers.append(_correios.CorreiosFreight())
freight = FreightOptions(_carriers or [FakeFreight()])
@@ -141,8 +141,10 @@ def quote_view(c, row, order=None, attempt=None, known=False):
datetime.now(timezone.utc)-timedelta(hours=QUOTE_VALID_HOURS)))
items = (row['approved'] or row['draft']).get('items') or []
treatment = (row['approved'] or {}).get('treatment')
if not treatment and (row['draft'] or {}).get('treatment') and treatment_cents():
treatment = {'cents': treatment_cents(), 'hours': 24}
if not treatment and (row['draft'] or {}).get('treatment'):
offer = catalog.current(c)['tratamento']
if offer['enabled'] and offer['unit_cents'] > 0:
treatment = {'cents': offer['unit_cents'], 'hours': 24}
return {'id': row['id'], 'created_at': row['created_at'],
'draft': row['draft'], 'approved': row['approved'],
'expires_at': expires_at.isoformat() if expires_at else None,

View File

@@ -581,3 +581,22 @@ CREATE TABLE IF NOT EXISTS dtf_local.machine_snoozes (
snoozed_by text NOT NULL, snoozed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(machine_id, alert, cycle_from)
);
-- Front 8: what the Site sells and at what price, edited in the Kanban's Site tab.
CREATE TABLE IF NOT EXISTS dtf_local.products (
id text PRIMARY KEY CHECK (id IN ('file','avulsa','uvfile','uv','tratamento')),
enabled boolean NOT NULL DEFAULT true,
updated_by text NOT NULL DEFAULT 'sistema',
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO dtf_local.products(id) VALUES ('file'),('avulsa'),('uvfile'),('uv'),('tratamento')
ON CONFLICT (id) DO NOTHING;
CREATE TABLE IF NOT EXISTS dtf_local.product_prices (
id bigserial PRIMARY KEY,
product text NOT NULL REFERENCES dtf_local.products(id),
unit_cents integer NOT NULL CHECK (unit_cents >= 0 AND unit_cents <= 10000000),
starts_at timestamptz NOT NULL,
created_by text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS product_prices_current ON dtf_local.product_prices(product, starts_at DESC);

View File

@@ -51,7 +51,8 @@ from urllib.parse import urlencode
import httpx
from .core.pricing import treatment_cents
from . import catalog
from .core import db
API = 'https://api.tiny.com.br/public-api/v3'
AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect'
@@ -172,7 +173,9 @@ def required_settings():
setting for mode, setting in PRODUCT_SETTINGS.items() if not (sku_prefix(mode) or step_sku(mode))]
# A paid treatment is a line of its own: missing, every treated order would
# fail at the Tiny, so ask for it with the rest of the settings.
if treatment_cents() > 0:
with db.connect() as c:
treatment = catalog.current(c)['tratamento']
if treatment['enabled'] and treatment['unit_cents'] > 0:
required.append('TINY_PRODUCT_TREATMENT')
return required