feat: designer treatment as an optional paid line (front 5)
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 4m20s
Build and deploy / Publish images (push) Successful in 1m5s

TREATMENT_CENTS sets a fixed price per order; 0 keeps the option hidden.
The cart shows the designer treatment and adds 24 h; the quote total and
Tiny line carry it, and the card gets the "Tratamento pago" label. The
designer uploads the treated file through the existing card flow.
This commit is contained in:
Cauê Faleiros
2026-11-06 13:07:22 -03:00
parent bdff73b76b
commit c8d03d3b94
18 changed files with 108 additions and 8 deletions

View File

@@ -18,6 +18,8 @@ OPERATOR_EMAIL=operator@example.test
OPERATOR_PASSWORD=local-operator-only
APP_ENV=local
PAYMENT_ADAPTER=fake
# Designer treatment, fixed per order in cents; 0 hides the option.
TREATMENT_CENTS=0
FREIGHT_ADAPTER=fake
TINY_ADAPTER=fake
# Sandbox only (see docs/LOCAL_SETUP.md, "Provider sandboxes"):

View File

@@ -9,7 +9,7 @@ from ..core import db
from .. import 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
from ..core.pricing import manual_extra_cents, treatment_cents
from ..core.models import FreightAsk, FreightEstimate
from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, delivery_services, freight, payment,
require_delivery_available, storage)
@@ -43,6 +43,7 @@ def session(request: Request, response: Response):
'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(),
# 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

@@ -264,6 +264,8 @@ class QuoteRequest(StrictModel):
destination: Destination | None = None
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
proof: bool = False
# "Quero o tratamento pelo designer": a fixed service line, when priced (front 5).
treatment: bool = False
# What the browser measured while the customer built the cart (item 0.12).
timings: ClientTimings | None = None

View File

@@ -24,6 +24,18 @@ def manual_extra_cents() -> int:
return value
def treatment_cents() -> int:
"""The designer's treatment, a fixed amount per order (front 5).
Zero keeps the option hidden: the price is the client's decision, and the
server and the Site read the same `TREATMENT_CENTS`.
"""
value = int(os.environ.get('TREATMENT_CENTS', '0') or 0)
if not 0 <= value <= 1000000:
raise ValueError('TREATMENT_CENTS must be between 0 and 1000000')
return value
def is_manual(item, names) -> bool:
"""Whether a finished-sheet item has a file someone must open by hand: one
the customer measured, or one in a format the Site cannot read."""

View File

@@ -22,7 +22,7 @@ from psycopg.types.json import Jsonb
from . import 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
from .core.pricing import bill_splits, is_manual, manual_extra_cents, price, treatment_cents
from .runtime import freight, upload_row
from .scanning import require_clean
@@ -96,13 +96,16 @@ 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
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 {}),
# Browser timings are kept for Números, never for the price (0.12).
**({'timings': draft['timings']} if draft.get('timings') else {}),
'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents']}
'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents'] + treatment}
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
(Jsonb(approved), reviewer, row['id']))
# Approved and payable now: the files wait for the payment, not for ever.

View File

@@ -33,6 +33,7 @@ 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()])
@@ -134,9 +135,12 @@ def quote_view(c, row, order=None, attempt=None, known=False):
attempt = {**attempt, 'message': rejection(attempt['status_detail'])}
expired = row['approved_at'] and row['approved_at'] < datetime.now(timezone.utc)-timedelta(hours=24)
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}
return {'id': row['id'], 'created_at': row['created_at'],
'draft': row['draft'], 'approved': row['approved'],
'prumo': prumo.customer_summary(items),
'prumo': prumo.customer_summary(items), 'treatment': treatment,
'status': 'paid' if order else 'discarded' if row.get('discarded_at') else 'expired' if expired
else 'approved' if row['approved'] else 'pending_review',
'auto_approved': row.get('reviewed_by') == 'auto',

View File

@@ -489,6 +489,14 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
'quantidade': float(Decimal(item['billed_metres'])),
'valorUnitario': money(item['unit_cents']),
'infoAdicional': note})
treatment = order.get('treatment') or {}
if treatment.get('cents'):
setting = os.environ.get('TINY_PRODUCT_TREATMENT', '')
if not setting.isdigit():
raise TinyError('TINY_PRODUCT_TREATMENT must be the Tiny product id')
items.append({'produto': {'id': int(setting)}, 'quantidade': 1,
'valorUnitario': money(treatment['cents']),
'infoAdicional': 'Tratamento da arte pelo designer · +24 h'})
freight = order['freight']
service = freight.get('service')
pickup = service == 'pickup'
@@ -506,7 +514,8 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
# The carrier's time already counts production; a pickup is ready after it.
days = freight.get('days') if not pickup else int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0)
if days is not None:
pedido['dataPrevista'] = business_days_after(day, int(days)).isoformat()
days = int(days) + (1 if treatment.get('cents') else 0)
pedido['dataPrevista'] = business_days_after(day, days).isoformat()
# Paid at once, in full, as the store's orders: one parcel on the day.
pedido['pagamento'] = {'categoria': {'id': CATEGORIES.get(payload.get('origin'), CATEGORY)}}
received = RECEIPT_METHODS.get((payload.get('payment') or {}).get('method'))

View File

@@ -58,6 +58,8 @@ x-app: &app
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-0}
# Fixed price of the designer's treatment per order; 0 hides the option.
TREATMENT_CENTS: ${TREATMENT_CENTS:-0}
TINY_ADAPTER: ${TINY_ADAPTER:-fake}
TINY_CLIENT_ID: ${TINY_CLIENT_ID:-}
TINY_CLIENT_SECRET: ${TINY_CLIENT_SECRET:-}
@@ -66,6 +68,7 @@ x-app: &app
TINY_PRODUCT_TEXTIL_AVULSA: ${TINY_PRODUCT_TEXTIL_AVULSA:-}
TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-}
TINY_PRODUCT_UV_AVULSA: ${TINY_PRODUCT_UV_AVULSA:-}
TINY_PRODUCT_TREATMENT: ${TINY_PRODUCT_TREATMENT:-}
TINY_SKU_TEXTIL_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-}
TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-}
TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-}

View File

@@ -37,10 +37,12 @@ TINY_ADAPTER=TBD
# redirect URL registered there must equal TINY_REDIRECT_URI.
TINY_CLIENT_ID=TBD
TINY_REDIRECT_URI=https://<KANBAN_DOMAIN>/api/operator/tiny/callback
TREATMENT_CENTS=0
TINY_PRODUCT_TEXTIL_FOLHA=TBD
TINY_PRODUCT_TEXTIL_AVULSA=TBD
TINY_PRODUCT_UV_FOLHA=TBD
TINY_PRODUCT_UV_AVULSA=TBD
TINY_PRODUCT_TREATMENT=TBD
TINY_FORMA_ENVIO_RETIRADA=TBD
# true only at go-live, after the n8n DTFIMP designer branch is removed.
TINY_STATUS_UPDATES=false

View File

@@ -75,6 +75,8 @@ x-app-environment: &app-environment
# (CDR, AI, PSD, TIFF, or a length the customer typed). Dropstar set R$ 2,00
# a metro on 2026-10-23; 0 adds nothing. The Site shows it before payment.
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-200}
# Fixed price of the designer's treatment per order, in cents; 0 hides it.
TREATMENT_CENTS: ${TREATMENT_CENTS:-0}
# Print files longer than 5,08 m are written at their real size, which Corel
# reads (2026-10-28). true goes back to PDF's /UserUnit scale, for a RIP that
# refuses pages over 5,08 m.
@@ -96,6 +98,7 @@ x-app-environment: &app-environment
TINY_PRODUCT_TEXTIL_AVULSA: ${TINY_PRODUCT_TEXTIL_AVULSA:-}
TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-}
TINY_PRODUCT_UV_AVULSA: ${TINY_PRODUCT_UV_AVULSA:-}
TINY_PRODUCT_TREATMENT: ${TINY_PRODUCT_TREATMENT:-}
TINY_SKU_TEXTIL_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-}
TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-}
TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-}

View File

@@ -65,6 +65,11 @@ try{
// The check above can still pass on the page being replaced; wait for the new one's cards.
await waitFor(()=>site.eval(`!!document.querySelector('[data-modo="file"]') && document.readyState==='complete'`),'product cards after reload');
await site.click('[data-modo="file"]');
const treatmentCents = await site.eval('(async()=> (await dtfSessionReady).treatment_cents)()');
if (treatmentCents > 0) {
assert.equal(await site.eval(`!$('tratamentoBox').hidden`), true);
assert.equal(await site.eval(`$('tratamentoPreco').textContent`), 'R$ '+(treatmentCents/100).toFixed(2).replace('.',','));
}
// Each product has its own page; the home's parts are not on it.
assert.deepEqual(await site.eval(`({path:location.pathname,page:document.documentElement.dataset.rota,
cards:getComputedStyle($('cards')).display,cart:getComputedStyle($('carr')).display})`),

View File

@@ -1,9 +1,11 @@
"""Run from repository root: python3 -m unittest tests.test_pricing -v."""
import json
import os
from pathlib import Path
from unittest.mock import patch
import subprocess
import unittest
from app.core.pricing import is_manual, price, PRICES
from app.core.pricing import is_manual, price, PRICES, treatment_cents
class PricingTests(unittest.TestCase):
def test_every_length_against_actual_site_javascript(self):
@@ -63,6 +65,15 @@ class PricingTests(unittest.TestCase):
# Loose artwork is assembled by the Site; it never pays this.
self.assertFalse(is_manual(item('artwork', 'customer'), {'u1': 'arte.cdr'}))
def test_treatment_is_optional_and_configured_by_the_environment(self):
with patch.dict(os.environ, {'TREATMENT_CENTS': '990'}):
self.assertEqual(treatment_cents(), 990)
with patch.dict(os.environ, {'TREATMENT_CENTS': '0'}):
self.assertEqual(treatment_cents(), 0)
with patch.dict(os.environ, {'TREATMENT_CENTS': '-1'}):
with self.assertRaises(ValueError):
treatment_cents()
def test_invalid_inputs(self):
for value in ('0','-1','NaN','Infinity','12001'):
with self.assertRaises(ValueError):price('file',value,90)

View File

@@ -149,6 +149,19 @@ class TinyTests(FakeTinyCase):
self.assertNotIn('enderecoEntrega', pickup)
self.assertIn('retirada', pickup['observacoes'])
def test_treatment_is_a_line_and_one_more_day(self):
base = {**PAID['order'],
'freight': {'service': 'mock-standard', 'total_cents': 1500, 'days': 3}}
plain = {'order': base, **{k: v for k, v in PAID.items() if k != 'order'}}
treatment = {'order': {**base, 'treatment': {'cents': 990, 'hours': 24},
'total_cents': base['total_cents'] + 990},
**{k: v for k, v in PAID.items() if k != 'order'}}
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
pedido = order_payload(treatment, 777, date(2026, 9, 24))
self.assertIn({'produto': {'id': 105}, 'quantidade': 1, 'valorUnitario': 9.9,
'infoAdicional': 'Tratamento da arte pelo designer · +24 h'}, pedido['itens'])
self.assertNotEqual(pedido['dataPrevista'], order_payload(plain, 777, date(2026, 9, 24))['dataPrevista'])
def test_second_delivery_finds_the_first_order(self):
first = self.tiny.deliver('k1', PAID)
second = self.tiny.deliver('k1', PAID)

View File

@@ -24,7 +24,7 @@
stroke:item.strokeClass||null,strokeChoice:item.strokeChoice||null,
sheets:(item.partes||[]).map(part=>part.production),
files:(item.localFiles||[]).map(file=>({name:file.name,size:file.size,lastModified:file.lastModified}))
}))});
})),treatment:!!$('fTratamento')?.checked});
}
// The quote this browser is paying, forgotten. clearDraft also empties the
// payment area; forgetDraft leaves on screen what is there (a confirmation).
@@ -74,6 +74,17 @@
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho();
}
// 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;
const tratamentoBox=document.getElementById('tratamentoBox');
if(tratamentoBox){
tratamentoBox.hidden=!(TAXA_TRATAMENTO>0);
const preco=document.getElementById('tratamentoPreco');
if(preco)preco.textContent=TAXA_TRATAMENTO>0?rs(TAXA_TRATAMENTO):'';
if(!(TAXA_TRATAMENTO>0)&&document.getElementById('fTratamento'))document.getElementById('fTratamento').checked=false;
}
if(typeof pintaPedido==='function')pintaPedido();
}).catch(()=>{});
window.dtfSessionReady=ready;
window.dtfApi=api;
@@ -122,6 +133,8 @@
const prazo = approved.freight.days ? ' · até '+approved.freight.days+' dias úteis' : '';
rows.push(linha(pickup ? 'Retirada em Franca' : (approved.freight.description || 'Frete')+prazo,
approved.freight.total_cents ? rs(approved.freight.total_cents/100) : 'Grátis'));
if(quote.treatment?.cents)
rows.push(linha('Tratamento da arte pelo designer · +24 h', rs(quote.treatment.cents/100)));
rows.push(linha('Total', rs(approved.total_cents/100), 'tot'));
const prumoBox=node('div',null,'prumoResumo');
if(quote.prumo?.length){
@@ -377,6 +390,7 @@
if (destination) content.destination = destination;
// "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
if ($('fProva')?.checked) content.proof = true;
if ($('fTratamento')?.checked) content.treatment = true;
if (cartSnapshot()!==initialCart) throw new Error('O carrinho mudou durante o envio. Confira os itens e envie de novo.');
// Browser timings for Números (item 0.12); they never affect the price.
const T=window.dtfTimings, timings={};

View File

@@ -1096,6 +1096,14 @@ h2 em{font-style:normal;color:var(--laranja)}
Imprimimos até 30 cm da sua folha e mandamos a foto pelo WhatsApp. O resto só é impresso
depois do seu ok, então o pedido espera a sua resposta. Até 3 provas por pedido, sem custo.</span></label>
</div>
<div class="cxE" id="tratamentoBox" hidden>
<h4>Tratamento da arte</h4>
<label class="provaOp"><input type="checkbox" id="fTratamento">
<span><b>Quero o tratamento pelo designer — <span id="tratamentoPreco"></span></b>
O designer ajusta a arte para DTF, com fundo transparente e 300 DPI, e sobe o arquivo
pelo card. O prazo do pedido aumenta em 24 h.</span></label>
</div>
</div>
<aside class="resumo">

View File

@@ -1019,6 +1019,7 @@ function cardFlags(order){
if(redo.length)out.push(['bad','Retrabalho',redo.map(r=>'Retrabalho · '+REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join(' · ')]);
if(live&&s.items.some(mirroredItem))out.push(['warn','Espelhada',MIRROR_NOTE]);
if(waitingContact(order))out.push(['warn','Contato','Aguardando contato: '+order.contact_note+' · '+contactWho(order)]);
if(order.snapshot.treatment)out.push(['warn','Tratamento pago','O designer trata a arte antes de imprimir; prazo +24 h']);
if(order.proof_parent)out.push(['warn','Prova do #'+order.proof_parent.number,'Card da prova do pedido #'+order.proof_parent.number]);
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]);

View File

@@ -55,7 +55,8 @@ function pintaPedido(){
const aPagar = itensAPagar();
const itens = aPagar.reduce((t,it)=>t+it.total,0);
const frete = entrega.tipo==='frete' && entrega.cotado ? entrega.valor : 0;
const soma = itens + frete;
const tratamento=$('fTratamento')?.checked&&TAXA_TRATAMENTO>0?TAXA_TRATAMENTO:0;
const soma = itens + frete + tratamento;
const n = aPagar.length, noCarrinho = pedido.length + (itemAtual?1:0);
$('resLin').innerHTML =
'<div class="l"><span>'+n+(n===1?' item':' itens')+'</span><b>'+rs(itens)+'</b></div>'+
@@ -64,6 +65,7 @@ function pintaPedido(){
'</span><b>'+
(entrega.tipo==='retira' ? '<span style="color:var(--verde-ml)">Grátis</span>'
: entrega.cotado ? rs(frete) : 'a cotar')+'</b></div>'+
(tratamento?'<div class="l"><span>Tratamento da arte · +24 h</span><b>'+rs(tratamento)+'</b></div>':'')+
'<div class="l"><span>Revisão e reencaixe</span>'+
'<b><span style="color:var(--verde-ml)">Grátis</span></b></div>';
$('carrTot').textContent=rs(soma);
@@ -73,6 +75,8 @@ 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;
@@ -158,6 +162,7 @@ function avisaDesfazer(texto,acao){
function fechaDesfazer(){ clearTimeout(desfazerTimer); desfazerAcao=null; $('desfazer').hidden=true; }
addEventListener('dtf-page-changed',fechaDesfazer);
$('desfazerBtn').addEventListener('click',()=>{ const acao=desfazerAcao; fechaDesfazer(); if(acao) acao(); });
$('fTratamento')?.addEventListener('change',()=>pintaPedido());
$('bEsvaziar').addEventListener('click',()=>{
const antes=pedido.slice();
pedido=[]; invalidaItemAtual(); pintaPedido();

View File

@@ -60,6 +60,8 @@ const PRECO={file:19.90, avulsa:21.90, uvfile:79.90, uv:89.90};
// Folha que alguém abre na mão (CDR, AI, PSD, TIFF): R$ a mais por metro.
// Vem do servidor (/api/session), que cobra o mesmo; zero não soma nada.
let TAXA_MANUAL=0;
// Fixed price of the designer treatment, set by the server (TREATMENT_CENTS).
let TAXA_TRATAMENTO=0;
const folhaManual=()=>ehFolha() && folhas.some(x=>!x.med);
const ehFolha=m=>!!MODOS[m||modo].folha;
const precoMetro=m=>PRECO[m||modo];