From c8d03d3b9414334f06cddeb2b07463811358088f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Fri, 6 Nov 2026 13:07:22 -0300 Subject: [PATCH] feat: designer treatment as an optional paid line (front 5) 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. --- .env.example | 2 ++ app/api/health.py | 3 ++- app/core/models.py | 2 ++ app/core/pricing.py | 12 ++++++++++++ app/quote_review.py | 7 +++++-- app/runtime.py | 6 +++++- app/tiny.py | 11 ++++++++++- compose.local.yaml | 3 +++ deploy/portainer.env.example | 2 ++ docker-compose.yml | 3 +++ tests/browser_test.mjs | 5 +++++ tests/test_pricing.py | 13 ++++++++++++- tests/test_tiny.py | 13 +++++++++++++ web/checkout.js | 16 +++++++++++++++- web/index.html | 8 ++++++++ web/kanban.js | 1 + web/site-cart.js | 7 ++++++- web/site-config.js | 2 ++ 18 files changed, 108 insertions(+), 8 deletions(-) diff --git a/.env.example b/.env.example index ab1d905..605610e 100644 --- a/.env.example +++ b/.env.example @@ -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"): diff --git a/app/api/health.py b/app/api/health.py index d86acd9..103f685 100644 --- a/app/api/health.py +++ b/app/api/health.py @@ -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. diff --git a/app/core/models.py b/app/core/models.py index 4729909..24e9e81 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -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 diff --git a/app/core/pricing.py b/app/core/pricing.py index 07ef1fc..0c31965 100644 --- a/app/core/pricing.py +++ b/app/core/pricing.py @@ -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.""" diff --git a/app/quote_review.py b/app/quote_review.py index bbf7072..ca8bc24 100644 --- a/app/quote_review.py +++ b/app/quote_review.py @@ -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. diff --git a/app/runtime.py b/app/runtime.py index 207dcb5..e4e4547 100644 --- a/app/runtime.py +++ b/app/runtime.py @@ -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', diff --git a/app/tiny.py b/app/tiny.py index 68d9e54..4ceb847 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -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')) diff --git a/compose.local.yaml b/compose.local.yaml index 3a12c29..ca7b8ce 100644 --- a/compose.local.yaml +++ b/compose.local.yaml @@ -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:-} diff --git a/deploy/portainer.env.example b/deploy/portainer.env.example index d52dc40..8a13afd 100644 --- a/deploy/portainer.env.example +++ b/deploy/portainer.env.example @@ -37,10 +37,12 @@ TINY_ADAPTER=TBD # redirect URL registered there must equal TINY_REDIRECT_URI. TINY_CLIENT_ID=TBD TINY_REDIRECT_URI=https:///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 diff --git a/docker-compose.yml b/docker-compose.yml index 7020511..cb57a23 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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:-} diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index 0a6c957..e59c9f4 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -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})`), diff --git a/tests/test_pricing.py b/tests/test_pricing.py index c9d8c9f..9ba6c9d 100644 --- a/tests/test_pricing.py +++ b/tests/test_pricing.py @@ -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) diff --git a/tests/test_tiny.py b/tests/test_tiny.py index a4efb9e..198313c 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -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) diff --git a/web/checkout.js b/web/checkout.js index b458ef3..c9ad0f3 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -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={}; diff --git a/web/index.html b/web/index.html index 1e41557..a01db80 100644 --- a/web/index.html +++ b/web/index.html @@ -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. + +