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

@@ -23,6 +23,7 @@ jobs:
deploy.test_production_preflight \
tests.test_pricing \
tests.test_coupons \
tests.test_grade_rules \
tests.test_secrets -v
sh -n infra/lock_dependencies.sh
@@ -74,7 +75,7 @@ jobs:
# one a developer exercises on localhost.
- name: API and workflow regressions
run: |
for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test; do
for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test grade_rules_test; do
echo "--- $suite"
$COMPOSE exec -T \
-e SITE_BASE_URL=http://site \

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()
);

83
tests/grade_rules_test.py Normal file
View File

@@ -0,0 +1,83 @@
"""The art grade rules: the designer warning and the required treatment (8.5).
Run against the local stack: SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost
python -m tests.grade_rules_test
"""
import secrets
from uuid import uuid4
from app.core import db
from tests.print_file_test import artwork
from tests.smoke_test import Client, item_spec, upload_bytes
def quote_body(item, treatment, mail):
body = {'request_key': str(uuid4()),
'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail},
'items': [item], 'freight': {'service': 'pickup'}}
if treatment:
body['treatment'] = True
return body
def run():
tag = secrets.token_hex(4)
mail = f'grade-{tag}@example.test'
client = Client()
client.call('/session')
manager = Client()
manager.call('/session')
manager.call('/operator/me', operator=True)
manager = manager.operator_client
price_id = quote_id = upload_id = None
rules_set = False
treatment_enabled = True
try:
products = {row['id']: row for row in manager.call('/operator/site/products')['products']}
treatment_enabled = products['tratamento']['enabled']
manager.call('/operator/site/products/tratamento', {'enabled': True})
price_id = manager.call('/operator/site/products/tratamento/prices', {'unit_cents': 1000})['id']
manager.call('/operator/site/grade-rules', {'aviso': 100, 'tratamento': 100})
rules_set = True
rules = manager.call('/operator/site/grade-rules')
assert rules['aviso'] == 100 and rules['tratamento'] == 100, rules
assert rules['treatment_offered'] is True, rules
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-GRADE-{tag}.png')
item = {**item_spec('uv', '1', 50, upload_id),
'quality_status': 'warning', 'quality_acknowledged': True}
refused = client.call('/quotes', quote_body(item, False, mail), expected=422)
assert refused['detail'] == ('Sua arte tem nota 50: para imprimir com qualidade, '
'o tratamento pelo designer é obrigatório neste pedido.'), refused
made = client.call('/quotes', quote_body(item, True, mail))
quote_id = made['id']
assert made['status'] == 'approved', made
approved = client.call('/quotes/' + quote_id)['approved']
assert approved['grade_flags'] == {'aviso': 50, 'tratamento': 50}, approved
assert approved['treatment']['cents'] == 1000, approved
assert approved['total_cents'] == 9990, approved
print('PASS: the grade rule requires the designer treatment and flags the order'
' with the worst grade')
finally:
if rules_set:
try:
manager.call('/operator/site/grade-rules', {'aviso': None, 'tratamento': None})
except Exception:
pass
with db.connect() as c:
if quote_id:
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote_id,))
if price_id:
c.execute('DELETE FROM dtf_local.product_prices WHERE id=%s', (price_id,))
if upload_id:
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s', (upload_id,))
try:
manager.call('/operator/site/products/tratamento', {'enabled': treatment_enabled})
except Exception:
pass
if __name__ == '__main__':
run()

42
tests/test_grade_rules.py Normal file
View File

@@ -0,0 +1,42 @@
"""Run from repository root: python3 -m unittest tests.test_grade_rules -v."""
import unittest
from app.grade_rules import triggered, treatment_message
def item(grade):
return {'grade': grade}
class GradeRulesTest(unittest.TestCase):
def test_nothing_changes_without_rules(self):
self.assertEqual(triggered({}, [item(10)], True), {})
self.assertEqual(triggered({}, [item(10)], False), {})
self.assertEqual(triggered({'aviso': 70}, [], True), {})
def test_aviso_only_and_the_worst_item(self):
self.assertEqual(triggered({'aviso': 70}, [item(69), item(90)], True), {'aviso': 69})
self.assertEqual(triggered({'aviso': 70}, [item(90)], True), {})
def test_both_rules_and_treatment_not_offered(self):
both = {'aviso': 70, 'tratamento': 50}
self.assertEqual(triggered(both, [item(45)], True), {'aviso': 45, 'tratamento': 45})
self.assertEqual(triggered(both, [item(62)], True), {'aviso': 62})
# The rule has no effect while the treatment is not offered.
self.assertEqual(triggered(both, [item(45)], False), {'aviso': 45})
self.assertEqual(triggered({'tratamento': 50}, [item(45)], False), {})
def test_the_boundary_is_exclusive(self):
self.assertEqual(triggered({'aviso': 70}, [item(70)], True), {})
self.assertEqual(triggered({'tratamento': 50}, [item(50)], True), {})
self.assertEqual(triggered({'aviso': 70}, [item(69)], True), {'aviso': 69})
def test_treatment_message(self):
self.assertEqual(
treatment_message(45),
'Sua arte tem nota 45: para imprimir com qualidade, o tratamento pelo designer '
'é obrigatório neste pedido.')
if __name__ == '__main__':
unittest.main()

View File

@@ -77,6 +77,9 @@
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho();
}
// The art grade rules (front 8.5): the Site uses only the treatment rule,
// forcing the checkbox when the cart's worst grade is below it.
window.dtfGradeRules=session.grade_rules||{};
// Treatment by the designer (front 5): only offered when TREATMENT_CENTS
// is set; the server adds the same amount and the 24 h to the quote.
TAXA_TRATAMENTO=(session.treatment_cents||0)/100;

View File

@@ -148,6 +148,66 @@ function sitePriceBlock(product){
return block;
}
// ── Nota da arte (front 8.5) ────────────────────────────────────────────────
function ensureGradePanel(){
let panel=$('site-grade-panel');
if(panel)return panel;
panel=node('section',undefined,'panel clip');panel.id='site-grade-panel';
const head=node('div',undefined,'phead');head.append(node('h2','Nota da arte'));
panel.append(head,node('p','A menor nota dos itens do pedido decide. Sem regra, a nota não muda nada.','phint'));
const body=node('div',undefined,'siteGradeBody');body.id='site-grade-body';panel.append(body);
const coupons=$('site-coupons-panel');
if(coupons)coupons.before(panel);
else{
const videos=$('site-videos-panel');
if(videos)videos.before(panel);else $('tab-site').append(panel);
}
return panel;
}
function gradeRuleRow(label, value){
const row=node('div',undefined,'siteGradeRow');
const on=node('input');on.type='checkbox';on.checked=value!=null;
const word=node('span',on.checked?'Ligado':'Desligado');
const toggle=node('label',undefined,'siteSwitch');toggle.append(on,word);
const num=node('input');num.type='number';num.min='1';num.max='100';num.step='1';
num.className='siteGradeNumber';num.value=value!=null?String(value):'';num.disabled=!on.checked;
on.onchange=()=>{
word.textContent=on.checked?'Ligado':'Desligado';
num.disabled=!on.checked;
if(on.checked)num.focus();
};
const fieldLabel=node('label',undefined,'siteGradeField');
fieldLabel.append(node('span',label),num);
row.append(toggle,fieldLabel);
return {row,on,num};
}
async function loadGradeRules(){
if(!may('manage'))return;
ensureGradePanel();
const data=await api('/site/grade-rules');
const aviso=gradeRuleRow('Avisar o designer abaixo de',data.aviso);
const tratamento=gradeRuleRow('Exigir o tratamento abaixo de',data.tratamento);
const save=button('Salvar',async()=>{
const avisoValue=aviso.on.checked?Number(aviso.num.value):null;
const tratamentoValue=tratamento.on.checked?Number(tratamento.num.value):null;
for(const value of [avisoValue,tratamentoValue])
if(value!==null&&(!Number.isInteger(value)||value<1||value>100))
throw new Error('A nota vai de 1 a 100.');
if(avisoValue!==null&&tratamentoValue!==null&&tratamentoValue>avisoValue)
throw new Error('A regra do tratamento precisa ser menor ou igual à do aviso.');
await api('/site/grade-rules',{aviso:avisoValue,tratamento:tratamentoValue});
say('Regras da nota da arte salvas.');
await loadGradeRules();
},'btn pri');
const children=[aviso.row,tratamento.row];
if(!data.treatment_offered)
children.push(node('p','Ative e dê preço ao Tratamento pelo designer para esta regra valer.','siteGradeWarn'));
const foot=node('div',undefined,'siteGradeSave');foot.append(save);children.push(foot);
$('site-grade-body').replaceChildren(...children);
}
// ── Cupons (front 8.3) ──────────────────────────────────────────────────────
// A "ficha" of the date in the browser's timezone, for datetime-local inputs.
function couponDate(iso){
@@ -298,6 +358,7 @@ async function loadSiteAdmin(){
$('site-products').replaceChildren(...data.products.map(siteProductRow));
$('site-prices').replaceChildren(...data.products.map(sitePriceBlock));
await loadSiteCoupons();
await loadGradeRules();
await loadSiteVideos();
}

View File

@@ -672,6 +672,12 @@ label.fopt{cursor:pointer;user-select:none}
#tab-site .siteCouponActions{display:flex;gap:8px;flex-wrap:wrap}
#tab-site .siteCouponActions .btn{height:32px;padding:0 10px;font-size:12.5px}
#tab-site .siteCouponNote{margin:0;font-size:13px;color:var(--tx2)}
#tab-site .siteGradeBody{display:flex;flex-direction:column;gap:14px;padding:16px 18px}
#tab-site .siteGradeRow{display:flex;align-items:center;gap:16px;flex-wrap:wrap}
#tab-site .siteGradeField{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--tx2)}
#tab-site .siteGradeNumber{width:80px;height:38px;padding:0 10px;border-radius:8px;border:1px solid var(--ln2);background:var(--sf);color:var(--tx);font-size:14px;font-family:inherit}
#tab-site .siteGradeWarn{margin:0;font-size:12.5px;font-weight:600;color:var(--warn)}
#tab-site .siteGradeSave{display:flex;gap:8px}
#tab-site .siteHistory .table{font-size:13px}
#tab-site .siteHistory .table th,#tab-site .siteHistory .table td{padding:8px 12px}
.page>*{flex-shrink:0}

View File

@@ -1057,6 +1057,10 @@ function cardFlags(order){
if(live&&waitingProof(order)&&order.state!=='tra')out.push(['warn','Aguardando prova','Entra na fila com Prova OK no card #'+order.proof_card.number]);
if(live&&proofRejected(order))out.push(['bad','Prova reprovada',order.proof_card.proof_reason+' · '+order.proof_card.proof_decided_by]);
if(live&&proofPending(order)&&!order.proof_card)out.push(['warn','Prova',order.snapshot.proof?'O cliente pediu uma prova antes de imprimir':'Pedido acima de 10 m: prova antes do resto']);
// The grade rule set in the Site tab flagged this order for the designer.
if(!order.proof_parent&&s.grade_flags?.aviso!=null)
out.push(['warn','Nota '+s.grade_flags.aviso+': conferir a arte',
'A nota da arte ficou abaixo do limite configurado: confira antes de imprimir']);
if(live&&s.items.some(i=>i.quality_status==='warning'))out.push(['warn','Nota '+(lowestGrade(s.items)??'baixa'),'Nota da arte baixa: o cliente aceitou a ressalva de resolução']);
const dots=s.items.reduce((t,i)=>t+(i.residue_accepted||0),0);
if(live&&dots)out.push(['warn','Resíduo','O cliente aceitou imprimir com '+residueNote({residue_accepted:dots})]);
@@ -1428,6 +1432,9 @@ function renderPanel(order){
sub.append(paid,node('span','Entrou pelo '+(ORIGINS[order.origin]||order.origin)),code,theirs);
if(s.coupon && !order.proof_parent)
sub.append(badge('Cupom '+s.coupon.code,'','Desconto de '+money(s.coupon.discount_cents)));
if(s.grade_flags?.aviso!=null && !order.proof_parent)
sub.append(badge('Nota '+s.grade_flags.aviso+': conferir a arte','warn',
'A nota da arte ficou abaixo do limite configurado: confira antes de imprimir'));
if(isTest(order))sub.append(badge('Teste','','Pedido de teste: sem pagamento, não vai ao Tiny'));
if(stalled(order)&&!order.cancelled_at)sub.append(badge('Parado há '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at)));
const steps=node('ol',undefined,'stepper');steps.setAttribute('aria-label','Etapas');

View File

@@ -30,6 +30,32 @@ function limpaPaineis(){
if(!pedido.length){ $('carr').classList.remove('on'); }
}
// Front 8.5: when the worst grade of the paying items is below the rule and
// the treatment is offered, the designer's treatment is required.
function mostraAvisoTratamento(texto){
const box=$('tratamentoBox'); if(!box)return;
let el=$('tratamentoAviso');
if(!el){el=document.createElement('p');el.id='tratamentoAviso';el.className='avisoF';box.append(el);}
el.textContent=texto;el.hidden=!texto;
}
function aplicaTratamento(aPagar){
const box=$('tratamentoBox'), check=$('fTratamento');
if(!box||!check)return;
const offered=TAXA_TRATAMENTO>0;
const rule=Number(window.dtfGradeRules?.tratamento)||0;
const grades=aPagar.map(it=>Number(it.nota)||0);
const worst=grades.length?Math.min(...grades):null;
const required=offered&&rule>0&&worst!==null&&worst<rule;
box.hidden=!offered;
if(!offered){
check.checked=false;check.disabled=false;mostraAvisoTratamento('');
}else if(required){
check.checked=true;check.disabled=true;
mostraAvisoTratamento('Sua arte tem nota '+worst+': para imprimir com qualidade, o tratamento pelo designer é obrigatório neste pedido.');
}else{
check.disabled=false;mostraAvisoTratamento('');
}
}
// O carrinho junta itens de produtos diferentes e cobra uma vez só.
function pintaPedido(){
const aPagar = itensAPagar();
@@ -51,6 +77,7 @@ function pintaPedido(){
aviso.hidden=false;
}else{aviso.hidden=true;aviso.textContent='';}
}
aplicaTratamento(aPagar);
$('itens').innerHTML = pedido.map((it,i)=>
'<div class="item'+(it.marcado===false?' fora':'')+'">'+
'<label class="marca"><input type="checkbox" data-sel="'+i+'"'+(it.marcado===false?'':' checked')+
@@ -93,8 +120,6 @@ function pintaPedido(){
// The proof is only for orders above 10 m (Dropstar, 2026-10-28): below it the box is gone.
const prova=$('fProva');
if(prova){ const longo=aPagar.reduce((t,it)=>t+(it.cob||0),0)>10; prova.closest('.cxE').hidden=!longo; if(!longo) prova.checked=false; }
const tratamentoBox=$('tratamentoBox');
if(tratamentoBox){tratamentoBox.hidden=!(TAXA_TRATAMENTO>0);if(tratamentoBox.hidden)$('fTratamento').checked=false;}
$('bPagar').disabled = !cartPodeEnviar() || !entrega.cotado || !clienteOk() || !enderecoOk();
if(pedido.length || itemAtual) $('carr').classList.add('on');
if($('cartN')){ $('cartN').textContent=noCarrinho>99?'99+':noCarrinho; $('cartN').hidden=!noCarrinho;