feat: the art grade becomes configurable, off by default (front 8.5)

Gestão sets in the Site tab below which grade the designer is warned and
below which the designer treatment is required (only while it is offered).
The decision is stored with the approved quote, so a later change never
rewrites old orders; the card shows 'Nota N: conferir a arte', the Site
forces the treatment box with the reason. With no rule nothing changes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 16:13:30 -03:00
parent 1d0353fe54
commit 272755d2bc
16 changed files with 338 additions and 13 deletions

View File

@@ -6,7 +6,7 @@ import httpx
from fastapi import APIRouter, HTTPException, Request, Response
from ..core import db
from .. import catalog, mail
from .. import catalog, grade_rules, 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
@@ -40,6 +40,7 @@ def session(request: Request, response: Response):
session_id = new_session(c, response)
with db.connect() as c:
products = catalog.current(c)
rules = grade_rules.current_rules(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,
@@ -48,6 +49,9 @@ def session(request: Request, response: Response):
'manual_extra_cents': manual_extra_cents(),
# Zero keeps the designer's treatment hidden, as an off product does.
'treatment_cents': treatment['unit_cents'] if treatment['enabled'] else 0,
# The grade rules the Site needs for the treatment requirement
# (front 8.5): {} when nothing is configured.
'grade_rules': rules,
# What the Site sells now: a switched-off product is hidden there.
# Bands travel with the price; the Site reads them as numbers.
'products': {mode: {**products[mode],

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 catalog, coupons, payments
from .. import catalog, coupons, grade_rules, payments
from ..core import db
from ..core.auth import owner
from ..core.models import QuoteRequest
@@ -40,6 +40,12 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
item['stroke_choice_at'] = accepted_at
reason = quote_review.review_reason(draft)
with db.connect() as c:
# The art grade rules (front 8.5): the treatment may be required. With
# no rule this is empty and nothing below changes.
flags = grade_rules.triggered(grade_rules.current_rules(c), draft['items'],
catalog.treatment_offered(c))
if 'tratamento' in flags and not draft.get('treatment'):
raise HTTPException(422, grade_rules.treatment_message(flags['tratamento']))
if reason is not None or code:
# Waits for review: check the delivery now, priced at approval. A
# coupon is checked on the same priced items (front 8.3).

View File

@@ -14,10 +14,10 @@ from fastapi import APIRouter, Depends, HTTPException
from psycopg.errors import UniqueViolation
from psycopg.types.json import Jsonb
from .. import catalog
from .. import catalog, grade_rules
from ..core import db
from ..core.auth import audit, can
from ..core.models import CouponNew, CouponUpdate, SitePriceNew, SiteProductToggle
from ..core.models import CouponNew, CouponUpdate, GradeRules, SitePriceNew, SiteProductToggle
router = APIRouter()
@@ -233,3 +233,30 @@ def delete_coupon(coupon_id: UUID, user=Depends(can('manage'))):
raise HTTPException(404, 'Cupom não encontrado.')
audit('site_coupon_deleted', coupon=str(coupon_id), code=row['code'], operator=user)
return {'ok': True}
@router.get('/api/operator/site/grade-rules')
def site_grade_rules(user=Depends(can('manage'))):
with db.connect() as c:
rules = grade_rules.current_rules(c)
offered = catalog.treatment_offered(c)
return {'aviso': rules.get('aviso'), 'tratamento': rules.get('tratamento'),
'treatment_offered': offered}
@router.post('/api/operator/site/grade-rules')
def save_grade_rules(body: GradeRules, user=Depends(can('manage'))):
if body.aviso is not None and body.tratamento is not None and body.tratamento > body.aviso:
raise HTTPException(422, 'A regra do tratamento precisa ser menor ou igual à do aviso.')
with db.connect() as c:
for action, below in (('aviso', body.aviso), ('tratamento', body.tratamento)):
if below is None:
c.execute('DELETE FROM dtf_local.grade_rules WHERE action=%s', (action,))
else:
c.execute('''INSERT INTO dtf_local.grade_rules(action,below,updated_by,updated_at)
VALUES(%s,%s,%s,now())
ON CONFLICT (action) DO UPDATE SET below=EXCLUDED.below,
updated_by=EXCLUDED.updated_by, updated_at=now()''',
(action, below, user))
audit('site_grade_rules_changed', aviso=body.aviso, tratamento=body.tratamento, operator=user)
return {'ok': True}

View File

@@ -86,6 +86,12 @@ def unit_cents_for(c, product: str, metres: Decimal) -> int:
return band_price(row['unit_cents'], row['bands'], metres)
def treatment_offered(c) -> bool:
"""Whether the designer's treatment is on the Site: enabled and priced."""
offer = current(c)['tratamento']
return bool(offer['enabled'] and offer['unit_cents'] > 0)
def require_enabled(c, product: str) -> None:
"""Refuse a product someone switched off in the Kanban's Site tab."""
# Imported here so the pure helpers above load without the web framework

View File

@@ -401,6 +401,12 @@ class CouponUpdate(StrictModel):
paused: bool | None = None
class GradeRules(StrictModel):
"""As regras da nota da arte: um limite por ação, ou nada (null)."""
aviso: int | None = Field(ge=1, le=100, strict=True)
tratamento: int | None = Field(ge=1, le=100, strict=True)
class Contraction(StrictModel):
item_index: int = Field(ge=0, le=100)
# None returns the item to the class the browser measured.

34
app/grade_rules.py Normal file
View File

@@ -0,0 +1,34 @@
"""What the art grade decides, set in the Kanban's Site tab (Fase 2, front 8.5).
With no rule nothing changes anywhere. An item triggers a rule when its grade
is below the rule's `below`; the order's worst item decides. `aviso` flags the
order for the designer; `tratamento` makes the designer's treatment required,
but only while it is offered (enabled and priced above zero).
"""
def current_rules(c) -> dict:
"""{'aviso': 70, 'tratamento': 50} for the rows that exist."""
return {row['action']: row['below'] for row in
c.execute('SELECT action, below FROM dtf_local.grade_rules').fetchall()}
def triggered(rules: dict, items, treatment_offered: bool) -> dict:
"""The rules the order's worst item triggers: {'aviso': N}, maybe with
'tratamento': N. N is the worst grade; empty when no rule applies."""
grades = [item.get('grade') for item in items if item.get('grade') is not None]
if not grades:
return {}
worst = min(grades)
flags = {}
if 'aviso' in rules and worst < rules['aviso']:
flags['aviso'] = worst
if treatment_offered and 'tratamento' in rules and worst < rules['tratamento']:
flags['tratamento'] = worst
return flags
def treatment_message(grade: int) -> str:
"""The refusal the customer sees when the treatment is required."""
return (f'Sua arte tem nota {grade}: para imprimir com qualidade, o tratamento '
'pelo designer é obrigatório neste pedido.')

View File

@@ -19,7 +19,7 @@ from decimal import Decimal
from fastapi import HTTPException
from psycopg.types.json import Jsonb
from . import catalog, coupons, payments
from . import catalog, coupons, grade_rules, payments
from .proof import PROOF_ABOVE_METRES
from .core.models import PRODUCTION_VERSIONS
from .core.pricing import apply_bands, bill_splits, is_manual, manual_extra_cents, price
@@ -103,6 +103,13 @@ def approve(c, row, items, reviewer):
if price_for_total != catalog.unit_cents(c, mode):
banded[mode] = price_for_total
apply_bands(priced, banded)
# The art grade rules (front 8.5): the worst item may require the designer's
# treatment and/or flag the order for the designer, stored with the approval.
offer = catalog.current(c)['tratamento']
offered = bool(offer['enabled'] and offer['unit_cents'] > 0)
flags = grade_rules.triggered(grade_rules.current_rules(c), priced, offered)
if 'tratamento' in flags and not draft.get('treatment'):
raise HTTPException(422, grade_rules.treatment_message(flags['tratamento']))
items_total = sum(i['total_cents'] for i in priced)
# The coupon discounts the items, after their bands, never freight or the
# treatment (front 8.3). It is checked again here: a quote that waited may
@@ -117,17 +124,16 @@ def approve(c, row, items, reviewer):
metres, items_total)
except ValueError as exc:
raise HTTPException(422, str(exc))
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
# The designer's treatment is offered only when switched on and priced.
treatment = offer['unit_cents'] if draft.get('treatment') and 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).
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
# Designer treatment is one fixed service line (front 5).
**({'treatment': {'cents': treatment, 'hours': 24}} if treatment else {}),
# The art grade decision stored with the quote (front 8.5).
**({'grade_flags': flags} if flags else {}),
# The coupon used, for the order card, Números and Tiny (front 8.3).
**({'coupon': coupon} if coupon else {}),
# Browser timings are kept for Números, never for the price (0.12).

View File

@@ -644,3 +644,11 @@ CREATE TABLE IF NOT EXISTS dtf_local.coupons (
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX IF NOT EXISTS coupons_live_code ON dtf_local.coupons(code) WHERE deleted_at IS NULL;
-- Front 8.5: what the art grade decides, set in the Kanban's Site tab. No row
-- means no rule, and nothing changes; each action has at most one threshold.
CREATE TABLE IF NOT EXISTS dtf_local.grade_rules (
action text PRIMARY KEY CHECK (action IN ('aviso','tratamento')),
below integer NOT NULL CHECK (below BETWEEN 1 AND 100),
updated_by text NOT NULL, updated_at timestamptz NOT NULL DEFAULT now()
);