diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 4991f95..18b8566 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -26,7 +26,10 @@ jobs: tests.test_db_pool \ tests.test_coupons \ tests.test_grade_rules \ + tests.test_hotfolder \ tests.test_migrate \ + tests.test_label \ + tests.test_observability \ tests.test_secrets -v sh -n infra/lock_dependencies.sh @@ -84,7 +87,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 stamps_test grade_rules_test; do + for suite in smoke_test workflow_test security_test upload_limits_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test label_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 stamps_test grade_rules_test; do echo "--- $suite" $COMPOSE exec -T \ -e SITE_BASE_URL=http://site \ @@ -97,7 +100,7 @@ jobs: # the generator's geometry. The provider suites use a fake transport: they # prove the documented contract, not the integration. - name: Print-file geometry and provider adapters - run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_worker_drain -v + run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain -v - name: Runtime and retention regressions run: | diff --git a/app/adapters.py b/app/adapters.py index 3b5dbcd..f8ea3e7 100644 --- a/app/adapters.py +++ b/app/adapters.py @@ -190,10 +190,22 @@ class EventAdapter(Protocol): def deliver(self, event_key: str, payload: dict) -> dict: ... class FakeTiny: + # The montador's Venda customer search (front 7a.3) has somewhere to look + # on the local stack and in CI. Two fixed contacts, always. + CONTACTS = [ + {'id': 1001, 'name': 'Nexstar Marketplace Ltda', 'document': '11.222.333/0001-81', + 'email': 'financeiro@nexstar.example', 'phone': '1633334444'}, + {'id': 1002, 'name': 'Maria Souza', 'document': '123.456.789-09', + 'email': 'maria.souza@example.test', 'phone': '16988887777'}, + ] + def deliver(self, event_key: str, payload: dict) -> dict: return {'provider': 'fake-tiny', 'reference': f"LOCAL-{payload['number']}", 'event_key': event_key, 'status': 'recorded-locally'} + def search_contacts(self, query: str) -> list: + return [dict(contact) for contact in self.CONTACTS] + class ObjectStorage(Protocol): def begin(self, key: str) -> str: ... def parts(self, key: str, upload_id: str) -> list: ... diff --git a/app/api/health.py b/app/api/health.py index 7125a99..3ef97bc 100644 --- a/app/api/health.py +++ b/app/api/health.py @@ -47,8 +47,12 @@ 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(), - # Zero keeps the designer's treatment hidden, as an off product does. + # Zero keeps Ajuste Fino hidden, as an off product does. Its bands + # are counted in arts, not metres. 'treatment_cents': treatment['unit_cents'] if treatment['enabled'] else 0, + 'treatment_bands': [{'from_metres': float(band['from_metres']), + 'unit_cents': band['unit_cents']} + for band in treatment['bands']] if treatment['enabled'] else [], # The grade rules the Site needs for the treatment requirement # (front 8.5): {} when nothing is configured. 'grade_rules': rules, @@ -59,6 +63,10 @@ def session(request: Request, response: Response): 'unit_cents': band['unit_cents']} for band in products[mode]['bands']]} for mode in catalog.MODES}, + # Public by design: the browser initialises Sentry with these; empty is off. + 'sentry_dsn_web': os.environ.get('SENTRY_DSN_WEB', '').strip(), + 'sentry_environment': os.environ.get('SENTRY_ENVIRONMENT') or ENVIRONMENT, + 'sentry_release': os.environ.get('IMAGE_TAG', ''), # 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/api/machine_log.py b/app/api/machine_log.py index 7f18399..3bad147 100644 --- a/app/api/machine_log.py +++ b/app/api/machine_log.py @@ -53,6 +53,8 @@ def sheet(mid: UUID, user=Depends(can('view'))): 'counters': machine_log.counters(c, mid), 'supplies': machine_log.supply_estimates(c, mid), 'minimums': minimums, + # The values the sheet shows when Gestão has not typed one. + 'default_minimums': machine_log.DEFAULT_MINIMUMS, 'alerts': machine_log.alerts(c, mid), 'entries': [{**row, 'label': entry_label(row)} for row in entries], 'catalog': {'supplies': machine_log.SUPPLIES, 'parts': machine_log.PARTS, diff --git a/app/api/operator/__init__.py b/app/api/operator/__init__.py index 4fa08be..63e41fd 100644 --- a/app/api/operator/__init__.py +++ b/app/api/operator/__init__.py @@ -5,7 +5,7 @@ includes and the names other modules imported from the old single file. """ from fastapi import APIRouter -from . import board, common, files, integrations, orders, quotes, rework, session, stats +from . import board, common, files, integrations, labels, orders, quotes, rework, session, stats from .integrations import tiny_callback from .stats import speed_figures @@ -13,5 +13,5 @@ router = APIRouter() # The order the routes first appeared in the old file. Static paths that could # meet a parameterised one stay ahead of it: /orders/finished before any # /orders/{uid} GET. -for module in (common, session, integrations, board, quotes, rework, orders, stats, files): +for module in (common, session, integrations, board, quotes, rework, orders, labels, stats, files): router.include_router(module.router) diff --git a/app/api/operator/common.py b/app/api/operator/common.py index 3ff55e0..4fa00f5 100644 --- a/app/api/operator/common.py +++ b/app/api/operator/common.py @@ -65,8 +65,8 @@ def cursor_pair(first, second): return first is not None -MODES = {'textil': {'file', 'avulsa'}, 'uv': {'uvfile', 'uv'}, - 'folha': {'file', 'uvfile'}, 'avulsa': {'avulsa', 'uv'}} +MODES = {'textil': {'file', 'avulsa', 'premium'}, 'uv': {'uvfile', 'uv'}, + 'folha': {'file', 'uvfile', 'premium'}, 'avulsa': {'avulsa', 'uv'}} def like(text): diff --git a/app/api/operator/integrations.py b/app/api/operator/integrations.py index 36a0e36..0b3d217 100644 --- a/app/api/operator/integrations.py +++ b/app/api/operator/integrations.py @@ -133,6 +133,22 @@ def tiny_status(c=None): return {'configured': True, 'orders_enabled': os.environ.get('TINY_ADAPTER') == 'tiny', **tiny.TinyAuth().status(c)} +@router.get('/api/operator/tiny/contacts') +def tiny_contacts(q: str = Query(min_length=1, max_length=120), user=Depends(can('assemble'))): + """The Tiny contacts a Venda customer is picked from (Fase 2, front + 7a.3): by name, or by CPF/CNPJ when only digits were typed. The fake + adapter answers with two fixed contacts on the local stack and in CI.""" + if os.environ.get('TINY_ADAPTER') != 'tiny': + from ...adapters import FakeTiny + return FakeTiny().search_contacts(q) + if not tiny.configured(): + raise HTTPException(409, 'O Tiny não está conectado.') + try: + return tiny.search_contacts(tiny.TinyOrders(), q) + except tiny.TinyNotConnected: + raise HTTPException(409, 'O Tiny não está conectado.') + + @router.post('/api/operator/tiny/connect') def tiny_connect(user=Depends(can('integrations'))): """Start the one-time authorisation of this system in the client's Tiny.""" diff --git a/app/api/operator/labels.py b/app/api/operator/labels.py new file mode 100644 index 0000000..99c1fb2 --- /dev/null +++ b/app/api/operator/labels.py @@ -0,0 +1,81 @@ +"""The 10x15 thermal label at Finalizado (Fase 2, front 10; Marcus, 2026-11-10). + +The label page is rendered by the server; one computer prints it automatically +(the first claim), and the Expedição profile or the Revisor may reprint it. +""" +from uuid import UUID + +from fastapi import APIRouter, Depends, HTTPException, Response + +from ... import label +from ...core import db +from ...core.auth import audit, can + +router = APIRouter() + + +def _order(c, uid, columns='number,state,cancelled_at'): + order = c.execute(f'SELECT {columns} FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() + if not order: + raise HTTPException(404, 'Pedido não encontrado.') + return order + + +def _tiny_number(c, uid): + """The Tiny order number from the sale event's receipt, or None.""" + row = c.execute("SELECT receipt->>'tiny_number' AS tiny_number FROM dtf_local.outbox WHERE event_key=%s", + (f'{uid}:paid:tiny',)).fetchone() + return row['tiny_number'] if row else None + + +def _finished(c, uid): + """When the card reached Finalizado and who released it, from the movements.""" + row = c.execute('''SELECT m.created_at, + COALESCE(NULLIF((SELECT o.name FROM dtf_local.operators o WHERE o.email=m.operator), ''), + m.operator) AS revisor + FROM dtf_local.movements m + WHERE m.order_id=%s AND m.to_state='fin' AND NOT m.back + ORDER BY m.created_at DESC, m.id DESC LIMIT 1''', (uid,)).fetchone() + return (row['created_at'], row['revisor']) if row else (None, None) + + +@router.get('/api/operator/orders/{uid}/label') +def order_label(uid: UUID, user=Depends(can('label'))): + """The printable label page (text/html), sized 100 x 150 mm.""" + with db.connect() as c: + order = _order(c, uid, 'number,state,cancelled_at,updated_at,snapshot') + if order['cancelled_at'] or order['state'] != 'fin': + raise HTTPException(409, 'A etiqueta é impressa em Finalizado.') + tiny = _tiny_number(c, uid) + finished, revisor = _finished(c, uid) + fields = label.label_fields(order, tiny, finished or order['updated_at'], revisor) + return Response(label.label_html(fields), media_type='text/html; charset=utf-8', + headers={'Cache-Control': 'no-store'}) + + +@router.post('/api/operator/orders/{uid}/label/claim') +def claim_label(uid: UUID, user=Depends(can('label'))): + """The first computer to ask prints the label; the unique partial index on + the 'auto' row decides, so two computers at once cannot both print it.""" + with db.connect() as c: + order = _order(c, uid) + if order['cancelled_at'] or order['state'] != 'fin': + return {'print': False} + row = c.execute('''INSERT INTO dtf_local.label_prints(order_id,reason,printed_by) + VALUES(%s,'auto',%s) ON CONFLICT DO NOTHING RETURNING id''', (uid, user)).fetchone() + if row: + audit('label_printed', order=order['number'], reason='auto', operator=user) + return {'print': bool(row)} + + +@router.post('/api/operator/orders/{uid}/label/reprint') +def reprint_label(uid: UUID, user=Depends(can('label'))): + """A new label for an order in Finalizado, from any computer.""" + with db.connect() as c: + order = _order(c, uid) + if order['cancelled_at'] or order['state'] != 'fin': + raise HTTPException(409, 'A etiqueta é reimpressa em Finalizado.') + c.execute('''INSERT INTO dtf_local.label_prints(order_id,reason,printed_by) + VALUES(%s,'reprint',%s)''', (uid, user)) + audit('label_printed', order=order['number'], reason='reprint', operator=user) + return {'print': True} diff --git a/app/api/operator/orders.py b/app/api/operator/orders.py index 806fcaa..9b07cf1 100644 --- a/app/api/operator/orders.py +++ b/app/api/operator/orders.py @@ -501,7 +501,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)): JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND {FINAL_OK} AND {TREATED}''', (uid,)).fetchall() if {r['item_index'] for r in treated} != set(range(len(row['snapshot']['items']))): - raise HTTPException(409, 'Tratamento pago: envie e aprove a arte tratada de todos os itens antes de entrar na fila.') + raise HTTPException(409, 'Ajuste Fino pago: envie e aprove a arte do Ajuste Fino de todos os itens antes de entrar na fila.') # Two at most per machine in Imprimindo (app/machines.py). if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)): raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.') diff --git a/app/api/operator/stats.py b/app/api/operator/stats.py index 01ed0fd..95eae47 100644 --- a/app/api/operator/stats.py +++ b/app/api/operator/stats.py @@ -4,7 +4,7 @@ from decimal import Decimal from fastapi import APIRouter, Depends, HTTPException, Query -from ... import machines, unpaid +from ... import machines, payments, unpaid from ...core import db from ...core.auth import operator from .common import ORIGINS, REAL_ORDER, TREATED, person @@ -13,6 +13,11 @@ from .rework import CUSTOMER_CAUSE, HOUSE_CAUSES, REWORK_GOAL_PERCENT router = APIRouter() LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date" +# A montador "Interno" or "faturado" order records the table price, not money +# received (Marcus, 2026-11-10): the cash figures leave it out and Números +# shows it in its own block. +NOT_CASH = ('COALESCE(o.payment->>\'method\',\'\') NOT IN ' + f"('{payments.INTERNAL_METHOD}','{payments.INVOICED_METHOD}')") def waited(order, start, end): @@ -57,7 +62,8 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start limit_rows = c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall() limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']} for row in limit_rows} - total = c.execute(f'''SELECT count(*) AS orders, COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents, + total = c.execute(f'''SELECT count(*) AS orders, + COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents, COALESCE(sum({metres}),0) AS metres, count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state='cor' AND NOT m.back)) AS corrected @@ -131,20 +137,29 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start # Each way in apart (D-21): what came from where, and how long it took # from payment to Finalizado, Aguardando contato left out as above. origins = {row['origin']: row for row in c.execute(f'''SELECT o.origin, count(*) AS orders, - COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents, COALESCE(sum({metres}),0) AS metres, + COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents, + COALESCE(sum({metres}),0) AS metres, count(f.at) AS finished, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM f.at - o.created_at) - {waited('o.id', 'o.created_at', 'f.at')}) / 3600 AS median_hours FROM dtf_local.orders o LEFT JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state='fin') f ON true WHERE {REAL_ORDER} AND {within} GROUP BY o.origin''', period).fetchall()} + # The table price of the montador's Interno and Venda orders, counted + # apart from the money received above (front 7a.3). + price_table = {row['method']: row for row in c.execute(f'''SELECT o.payment->>'method' AS method, + count(*) AS orders, COALESCE(sum({metres}),0) AS metres, + COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents + FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within} + AND o.payment->>'method' IN (%s,%s) GROUP BY 1''', + period + (payments.INTERNAL_METHOD, payments.INVOICED_METHOD)).fetchall()} # Coupons used by the period's paid orders (front 8.3): what each code # brought in orders, billed metres, discount and money received. coupons_used = c.execute(f'''SELECT o.snapshot->'coupon'->>'id' AS id, o.snapshot->'coupon'->>'code' AS code, count(*) AS orders, COALESCE(sum({metres}),0) AS metres, COALESCE(sum((o.snapshot->'coupon'->>'discount_cents')::bigint),0) AS discount_cents, - COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents + COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within} AND o.snapshot->'coupon'->>'id' IS NOT NULL GROUP BY 1,2 ORDER BY orders DESC, code''', period).fetchall() @@ -224,6 +239,11 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start 'median_hours': hours(origins[name]['median_hours']) if name in origins else None} for name in ORIGINS], 'unpaid': unpaid_figures, + 'price_table': [{'method': method, + 'orders': price_table[method]['orders'] if method in price_table else 0, + 'metres': float(price_table[method]['metres']) if method in price_table else 0.0, + 'cents': int(price_table[method]['cents']) if method in price_table else 0} + for method in (payments.INVOICED_METHOD, payments.INTERNAL_METHOD)], 'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])}, 'stage_limits': limits, 'late': late, 'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'], diff --git a/app/api/site_admin.py b/app/api/site_admin.py index 70afd32..d9e3bd3 100644 --- a/app/api/site_admin.py +++ b/app/api/site_admin.py @@ -29,21 +29,20 @@ def price_row(row): def checked_bands(product, bands): - """The bands the row will store; 422 in Portuguese for anything invalid.""" - if product == 'tratamento' and bands: - raise HTTPException(422, 'O tratamento é um valor por pedido: não tem faixas.') + """The bands the row will store; 422 in Portuguese for anything invalid. + Ajuste Fino counts its bands in arts; the other products in metres.""" if len(bands) > 5: raise HTTPException(422, 'Um preço pode ter no máximo 5 faixas.') checked, last = [], None for band in bands: if not band.from_metres.is_finite() or band.from_metres <= 0: - raise HTTPException(422, 'A metragem de cada faixa precisa ser maior que zero.') + raise HTTPException(422, 'O início de cada faixa precisa ser maior que zero.') if band.unit_cents <= 0: raise HTTPException(422, 'O preço de cada faixa precisa ser maior que zero.') if band.unit_cents > 10000000: raise HTTPException(422, 'O preço de cada faixa é alto demais.') if last is not None and band.from_metres <= last: - raise HTTPException(422, 'As faixas precisam estar em ordem crescente de metragem.') + raise HTTPException(422, 'As faixas precisam estar em ordem crescente.') last = band.from_metres checked.append({'from_metres': str(band.from_metres), 'unit_cents': band.unit_cents}) return checked @@ -247,7 +246,7 @@ def site_grade_rules(user=Depends(can('manage'))): @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.') + raise HTTPException(422, 'A regra do Ajuste Fino 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: diff --git a/app/api/stamps.py b/app/api/stamps.py index 712ea9c..4b64213 100644 --- a/app/api/stamps.py +++ b/app/api/stamps.py @@ -1,6 +1,8 @@ -"""The montador's stamp sizes and its invoiced orders (Fase 2, front 7).""" +"""The montador's stamp sizes, its brand per stamp, the internal customer and +the Interno and Venda orders a sheet becomes (Fase 2, fronts 7a to 7a.3).""" import hashlib import json +import re from uuid import uuid4 from fastapi import APIRouter, Depends, HTTPException, Request @@ -9,12 +11,22 @@ from psycopg.types.json import Jsonb from .. import payments, quote_review from ..core import db from ..core.auth import audit, can -from ..core.models import Freight, MontadorOrder, QuoteRequest, StampSizeTable, UploadStart +from ..core.models import (Customer, Freight, MontadorOrder, QuoteRequest, StampBrand, + StampSizeTable, UploadStart) from ..runtime import operator_identity from .uploads import begin_upload router = APIRouter() +CODE = re.compile(r'^[A-Za-z0-9_-]{1,40}$') +INTERNAL_MISSING = 'Peça à Gestão para completar o cliente interno.' +# Who chooses which kind of order in the montador (Marcus, 2026-11-10): the +# Expedição only Interno, the Vendedor only Venda; Gestão and the +# administrators both. +MONTADOR_KINDS = {'expedicao': {'interno'}, 'vendedor': {'venda'}, + 'superadmin': {'interno', 'venda'}, 'admin': {'interno', 'venda'}, + 'gestao': {'interno', 'venda'}} + @router.get('/api/operator/stamp-sizes') def stamp_sizes(user=Depends(can('assemble'))): @@ -33,6 +45,63 @@ def save_stamp_sizes(body: StampSizeTable, user=Depends(can('manage'))): return {'ok': True} +@router.get('/api/operator/internal-customer') +def read_internal_customer(user=Depends(can('assemble'))): + """The customer every Interno order belongs to; empty fields mean Gestão + still has to complete it.""" + with db.connect() as c: + row = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone() + return row or {'name': '', 'cnpj': '', 'zap': '', 'mail': ''} + + +@router.post('/api/operator/internal-customer') +def save_internal_customer(body: Customer, user=Depends(can('manage'))): + with db.connect() as c: + c.execute('''INSERT INTO dtf_local.internal_customer(id,name,cnpj,zap,mail,updated_by,updated_at) + VALUES(1,%s,%s,%s,%s,%s,now()) ON CONFLICT(id) DO UPDATE SET name=EXCLUDED.name, + cnpj=EXCLUDED.cnpj, zap=EXCLUDED.zap, mail=EXCLUDED.mail, + updated_by=EXCLUDED.updated_by, updated_at=now()''', + (body.name, body.cnpj, body.zap, body.mail, user)) + audit('internal_customer_changed', operator=user) + return {'ok': True} + + +def internal_customer(c): + """The fixed Interno customer, ready to use, or the reason Gestão must + complete it first.""" + row = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone() + if not row or not all(str(row[key] or '').strip() for key in ('name', 'cnpj', 'zap', 'mail')): + raise HTTPException(409, INTERNAL_MISSING) + try: + return Customer(**row) + except ValueError: + raise HTTPException(409, INTERNAL_MISSING) from None + + +@router.get('/api/operator/stamps/{code}') +def read_stamp(code: str, user=Depends(can('assemble'))): + """The brand recorded for a stamp code; nothing else uses it yet.""" + if not CODE.fullmatch(code): + raise HTTPException(422, 'Código inválido.') + with db.connect() as c: + row = c.execute('SELECT code,brand,public FROM dtf_local.stamps WHERE code=%s', (code,)).fetchone() + return row or {'code': code, 'brand': '', 'public': False} + + +@router.post('/api/operator/stamps/{code}') +def save_stamp(code: str, body: StampBrand, user=Depends(can('manage'))): + if not CODE.fullmatch(code): + raise HTTPException(422, 'Código inválido.') + brand = body.brand.strip() + with db.connect() as c: + c.execute('''INSERT INTO dtf_local.stamps(code,brand,public,updated_by,updated_at) + VALUES(%s,%s,%s,%s,now()) ON CONFLICT(code) DO UPDATE SET brand=EXCLUDED.brand, + public=EXCLUDED.public, updated_by=EXCLUDED.updated_by, updated_at=now()''', + (code, brand, body.public, user)) + audit('stamp_brand_saved', code=code, operator=user, public=body.public) + return {'ok': True} + + @router.post('/api/operator/montador/uploads') def montador_upload(body: UploadStart, user=Depends(can('assemble'))): if not body.name.lower().endswith('.png'): @@ -42,16 +111,30 @@ def montador_upload(body: UploadStart, user=Depends(can('assemble'))): @router.post('/api/operator/montador/orders') def montador_order(body: MontadorOrder, request: Request, user=Depends(can('assemble'))): - """The order a montador sheet becomes, already invoiced (front 7a.2b): - typed customer, pickup, the Site's table price, and held out of Tiny until - Dropstar decides how it is invoiced there.""" - origin = 'dropflow' if request.state.operator['role'] == 'expedicao' else 'atendimento' - draft = QuoteRequest(request_key=body.request_key, customer=body.customer, items=body.items, - freight=Freight(service='pickup')).model_dump(mode='json', exclude={'request_key'}) - draft['montador'] = True - digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest() - owner = operator_identity(user) + """The card a montador sheet becomes (fronts 7a.3 and 7a.4): Interno (the + fixed internal customer, origin dropflow, never Tiny) or Venda (a Tiny + customer, origin atendimento, invoiced and sent to Tiny), at the Site's + table price. A Venda is picked up, travels with a clothing order or ships + with the Site's freight; approve quotes the freight again.""" + role = request.state.operator['role'] + if body.kind not in MONTADOR_KINDS.get(role, set()): + raise HTTPException(403, 'Seu perfil não permite este tipo de pedido.') with db.connect() as c: + if body.kind == 'interno': + customer = internal_customer(c) + origin, method = 'dropflow', payments.INTERNAL_METHOD + else: + customer = body.customer + origin, method = 'atendimento', payments.INVOICED_METHOD + draft = QuoteRequest(request_key=body.request_key, customer=customer, items=body.items, + freight=body.freight or Freight(service='pickup'), + destination=body.destination).model_dump(mode='json', exclude={'request_key'}) + draft['montador'] = True + draft['kind'] = body.kind + if body.with_order: + draft['with_order'] = body.with_order + digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest() + owner = operator_identity(user) c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft) VALUES(%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING''', (uuid4(), owner, body.request_key, digest, Jsonb(draft))) @@ -60,12 +143,18 @@ def montador_order(body: MontadorOrder, request: Request, user=Depends(can('asse if quote['request_hash'] != digest: raise HTTPException(409, 'A montagem mudou durante o envio. Tente de novo.') if not quote['approved']: - quote_review.approve(c, quote, body.items, user) + approved = quote_review.approve(c, quote, body.items, user) + # The order's kind and the clothing order it travels with, on the + # card and in Tiny's internal note. + approved = {**approved, 'kind': body.kind, + **({'with_order': body.with_order} if body.with_order else {})} + c.execute('UPDATE dtf_local.quotes SET approved=%s WHERE id=%s', + (Jsonb(approved), quote['id'])) quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (quote['id'],)).fetchone() - receipt = {'provider': payments.MANUAL_PROVIDER, 'method': payments.INVOICED_METHOD, 'note': '', + receipt = {'provider': payments.MANUAL_PROVIDER, 'method': method, 'note': '', 'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user} order, created = payments.create_order(c, quote, receipt, origin) if not created: raise HTTPException(409, f"Esta montagem já virou o pedido #{order['number']}.") - audit('montador_order_created', order=str(order['id']), origin=origin, operator=user) + audit('montador_order_created', order=str(order['id']), origin=origin, kind=body.kind, operator=user) return order diff --git a/app/api/uploads.py b/app/api/uploads.py index c73b57f..95a9652 100644 --- a/app/api/uploads.py +++ b/app/api/uploads.py @@ -12,7 +12,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request from starlette.concurrency import run_in_threadpool from ..core import db -from ..core.auth import audit, owner, rate_limit +from ..core.auth import audit, client_ip, owner, rate_limit from ..core.limits import upload_limit_bytes from ..core.models import UploadStart from ..payments import UNPAID_HOLD @@ -20,13 +20,25 @@ from ..runtime import PART_BYTES, storage, upload_row router = APIRouter() +# A cart of many files: 66 in Marcus's case (2026-11-11), and adding more or +# retrying must fit. The per-source bucket bounds abuse, not a real order. +UPLOAD_START_LIMIT = 1000 +UPLOAD_START_IP_LIMIT = 3000 + + +def upload_ip_limit(request: Request): + """The public upload route's per-source bucket. The operator upload routes + reuse begin_upload directly and stay bound by their own session bucket.""" + rate_limit('upload-start-ip', client_ip(request), UPLOAD_START_IP_LIMIT, 900) + + @router.post('/api/uploads') -def begin_upload(body: UploadStart, session_id=Depends(owner)): +def begin_upload(body: UploadStart, session_id=Depends(owner), _source=Depends(upload_ip_limit)): if body.size > upload_limit_bytes(): raise HTTPException(413, 'O arquivo passa do tamanho máximo aceito. Escolha um arquivo menor.') uid = uuid4() key = f'originals/{uid}' - rate_limit('upload-start', str(session_id), 60, 900) + rate_limit('upload-start', str(session_id), UPLOAD_START_LIMIT, 900) with db.connect() as c: # Serialize reservations across API processes, including changing guest IDs. c.execute('SELECT pg_advisory_xact_lock(804208)') diff --git a/app/api/users.py b/app/api/users.py index e0c3b93..8a52e42 100644 --- a/app/api/users.py +++ b/app/api/users.py @@ -5,6 +5,7 @@ changes it in "Minha senha". The superadmin is the system's own account, set fro administrators manage everyone else. Nobody can remove, disable or demote themselves, so the last administrator cannot lock the team out by accident. """ +import os import re from decimal import Decimal from typing import Literal @@ -18,7 +19,7 @@ from ..core import db from ..core.auth import (CAPABILITIES, MACHINE_QUESTION, audit, can, may_move, may_reorder, password_hash, password_matches, signed_in) from ..core.models import StrictModel -from ..runtime import BACK, STATES, TRANSITIONS +from ..runtime import BACK, ENVIRONMENT, STATES, TRANSITIONS router = APIRouter() @@ -68,6 +69,10 @@ def me(request: Request): moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(role, a, b)] moves += [[a, b] for a, b in BACK.items() if may_move(role, a, b, back=True)] return {'email': account['email'], 'name': account['name'], 'role': role, + # Public by design: the Kanban browser initialises Sentry with these. + 'sentry_dsn_web': os.environ.get('SENTRY_DSN_WEB', '').strip(), + 'sentry_environment': os.environ.get('SENTRY_ENVIRONMENT') or ENVIRONMENT, + 'sentry_release': os.environ.get('IMAGE_TAG', ''), # The machine this session is on, and whether to ask (item 12). 'machine': account['machine'], 'machine_question': MACHINE_QUESTION.get(role), 'machine_answered': account['machine_answered'], diff --git a/app/app.py b/app/app.py index 31e8b87..93d1c2b 100644 --- a/app/app.py +++ b/app/app.py @@ -10,11 +10,14 @@ from fastapi import FastAPI from fastapi.responses import JSONResponse from starlette.middleware.trustedhost import TrustedHostMiddleware +from . import observability 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_admin, site_videos, stamps, uploads, users +observability.init('api') + @asynccontextmanager async def lifespan(app): diff --git a/app/cart_pricing.py b/app/cart_pricing.py index 96e414b..bd7f985 100644 --- a/app/cart_pricing.py +++ b/app/cart_pricing.py @@ -11,6 +11,38 @@ from . import catalog, coupons, grade_rules from .core import pricing +def art_pairs(items): + """[item_index, source_index] for every art in the cart: one artwork of + loose art, or one sheet file of a ready sheet.""" + return [[index, source] for index, item in enumerate(items) + for source in range(len((item.get('production') or {}).get('sources') or []))] + + +def chosen_arts(items, choice): + """The arts the draft's treatment selects: all of them for True (old carts + and the grade rule), the valid pairs for a list.""" + if choice is True: + return art_pairs(items) + if not isinstance(choice, (list, tuple)): + return [] + valid = {tuple(pair) for pair in art_pairs(items)} + return [list(pair) for pair in choice + if isinstance(pair, (list, tuple)) and len(pair) == 2 and tuple(pair) in valid] + + +def treatment_price(items, choice, offer): + """Ajuste Fino for the chosen arts, with the row's bands counted in arts. + {} when it is not offered or no art is chosen.""" + if not offer or not offer.get('enabled') or offer.get('unit_cents', 0) <= 0: + return {} + arts = chosen_arts(items, choice) + if not arts: + return {} + count = len(arts) + unit = catalog.band_price(offer['unit_cents'], offer.get('bands') or [], count) + return {'cents': unit * count, 'hours': 24, 'arts': count, 'unit_cents': unit} + + def price_items(items, names, catalog_now, manual_extra): """Price the items without a database: price() per item with the product's base price and the manual extra, bill_splits, then the band of each mode's @@ -41,9 +73,9 @@ def price_cart(c, items, names, *, coupon_code=None, customer_document=None, wants_treatment=False, treatment_rule=True): """Price a cart exactly as an order is charged. Returns {'items': [priced item dicts], 'items_total': int, 'coupon': dict|None, - 'treatment_cents': int, 'grade_flags': dict}. - Raises HTTPException(422) for a product switched off, a required treatment - the cart did not ask for, or a refused coupon (the same messages as today). + 'treatment': dict, 'treatment_cents': int, 'grade_flags': dict}. + Raises HTTPException(422) for a product switched off, a required Ajuste + Fino the cart did not ask for, or a refused coupon. `treatment_rule=False` is for the montador, which assembles the sheet.""" from fastapi import HTTPException catalog_now = catalog.current(c) @@ -56,14 +88,15 @@ def price_cart(c, items, names, *, coupon_code=None, customer_document=None, flags = grade_rules.triggered(grade_rules.current_rules(c), priced, offered) if not treatment_rule: flags.pop('tratamento', None) - if 'tratamento' in flags and not wants_treatment: + treatment = treatment_price(items, wants_treatment, offer) + if 'tratamento' in flags and not treatment: raise HTTPException(422, grade_rules.treatment_message(flags['tratamento'])) coupon = None if coupon_code: coupon = coupons.check(c, coupon_code, customer_document, priced) - treatment = offer['unit_cents'] if wants_treatment and offer['enabled'] else 0 return {'items': priced, 'items_total': sum(i['total_cents'] for i in priced), 'coupon': coupon, - 'treatment_cents': treatment, + 'treatment': treatment, + 'treatment_cents': treatment.get('cents', 0), 'grade_flags': flags} diff --git a/app/catalog.py b/app/catalog.py index a4b43cc..94db760 100644 --- a/app/catalog.py +++ b/app/catalog.py @@ -2,25 +2,26 @@ 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; +app/core/pricing.py stays as the seed and the fallback for the five 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. +`tratamento` is Ajuste Fino (front 1a): a price per art, with an optional band +by the order's number of arts (front 8.2). It counts as offered only when it is +switched on and priced above zero. -A price row may carry bands by the order's total metres of that product (front -8.2): below the first band the base price, then the highest band reached wins -and the whole quantity is charged at that one price. The bands travel with the -row, so they start and become history with it. +A price row may carry bands by the order's quantity of that product (metres, or +arts for Ajuste Fino): below the first band the base price, then the highest +band reached wins and the whole quantity is charged at that one price. The +bands travel with the row, so they start and become history with it. """ from decimal import Decimal from .core import pricing -# The four modes sold by the metre, and the treatment sold per order. -MODES = ('file', 'avulsa', 'uvfile', 'uv') +# The modes sold by the metre, and the treatment sold per order. +MODES = ('file', 'avulsa', 'uvfile', 'uv', 'premium') PRODUCTS = (*MODES, 'tratamento') TITLES = { @@ -28,10 +29,11 @@ TITLES = { 'avulsa': 'Têxtil artes avulsas', 'uvfile': 'UV folha pronta', 'uv': 'UV artes avulsas', - 'tratamento': 'Tratamento pelo designer', + 'premium': 'Têxtil Premium · 8 passadas', + 'tratamento': 'Ajuste Fino', } UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro', - 'tratamento': 'pedido'} + 'premium': 'metro', 'tratamento': 'arte'} def fallback_cents(product: str) -> int: @@ -39,15 +41,16 @@ def fallback_cents(product: str) -> int: return pricing.treatment_cents() if product == 'tratamento' else pricing.PRICES[product] -def band_price(base_cents: int, bands: list, metres: Decimal) -> int: - """The per-metre price for this quantity: the base, or the highest band - reached. The whole quantity is charged at one price, not in steps.""" - metres = Decimal(str(metres)) +def band_price(base_cents: int, bands: list, quantity: Decimal) -> int: + """The unit price for this quantity: the base, or the highest band reached. + The quantity is metres for a product and arts for Ajuste Fino; the whole + quantity is charged at one price, not in steps.""" + quantity = Decimal(str(quantity)) price = base_cents best = None for band in bands or []: start = Decimal(str(band['from_metres'])) - if metres >= start and (best is None or start >= best): + if quantity >= start and (best is None or start >= best): best = start price = band['unit_cents'] return price @@ -76,14 +79,14 @@ def unit_cents(c, product: str) -> int: return row['unit_cents'] if row else fallback_cents(product) -def unit_cents_for(c, product: str, metres: Decimal) -> int: +def unit_cents_for(c, product: str, quantity: Decimal) -> int: """The current price of one product for this quantity, bands included.""" row = c.execute('''SELECT unit_cents, bands FROM dtf_local.product_prices WHERE product=%s AND starts_at <= now() ORDER BY starts_at DESC, id DESC LIMIT 1''', (product,)).fetchone() if not row: return fallback_cents(product) - return band_price(row['unit_cents'], row['bands'], metres) + return band_price(row['unit_cents'], row['bands'], quantity) def treatment_offered(c) -> bool: diff --git a/app/core/auth.py b/app/core/auth.py index de0a1ec..de30000 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -164,6 +164,10 @@ CAPABILITIES = { # Montar folha (Fase 2, front 7): the new Expedição profile and the seller, # who gets this one action although otherwise view-only (D-30). 'assemble': {'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'}, + # The 10x15 thermal label at Finalizado (Marcus, 2026-11-10, front 10): the + # Revisor who releases the card, the Expedição profile that ships it, and + # Gestão, which may stand in for either. + 'label': {'superadmin', 'admin', 'gestao', 'revisor', 'expedicao'}, } # Who moves which card (Dropstar's flow, 2026-10-23, and their rules of diff --git a/app/core/models.py b/app/core/models.py index e534eb0..4026a25 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -174,7 +174,7 @@ def check_splits(items): class Item(StrictModel): - mode: Literal['file','avulsa','uvfile','uv'] + mode: Literal['file','avulsa','uvfile','uv','premium'] metres: Decimal = Field(gt=0, le=12000) grade: int = Field(ge=0, le=100, strict=True) uploads: list[UUID] = Field(min_length=1, max_length=20) @@ -205,7 +205,7 @@ class Item(StrictModel): raise ValueError('Only loose artwork is split into sheets') if [source.upload_id for source in self.production.sources] != self.uploads: raise ValueError('Production sources must match uploaded files in order') - is_sheet = self.mode in ('file', 'uvfile') + is_sheet = self.mode in ('file', 'uvfile', 'premium') # UV is 27 cm wide (Dropstar, 2026-10-28; it was 28,5). film_width = Decimal('27') if self.mode in ('uvfile', 'uv') else Decimal('57') if self.production.film_width_cm != film_width: @@ -265,8 +265,9 @@ 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 + # Ajuste Fino (front 1a): true selects every art of the cart (old carts and + # the grade rule), a list selects [item_index, source_index] arts. + treatment: bool | list[tuple[int, int]] = False # A coupon code typed at checkout (front 8.3); the server prices it. coupon: str | None = Field(default=None, max_length=30) # What the browser measured while the customer built the cart (item 0.12). @@ -277,6 +278,19 @@ class QuoteRequest(StrictModel): check_splits(self.items) return self + @model_validator(mode='after') + def treatment_arts_exist(self): + if isinstance(self.treatment, list): + seen = set() + for item_index, source_index in self.treatment: + if (item_index < 0 or source_index < 0 or item_index >= len(self.items) + or source_index >= len(self.items[item_index].production.sources)): + raise ValueError('Ajuste Fino: arte não encontrada no pedido.') + if (item_index, source_index) in seen: + raise ValueError('Ajuste Fino: cada arte aparece uma vez.') + seen.add((item_index, source_index)) + return self + @model_validator(mode='after') def destination_matches_freight(self): if self.freight.service == 'pickup': @@ -289,16 +303,43 @@ class QuoteRequest(StrictModel): return self class MontadorOrder(StrictModel): - """What the montador sends (front 7a.2b): the typed customer, pickup only - and loose artwork only; the server prices and approves it as a quote.""" + """What the montador sends (fronts 7a.3 and 7a.4): Interno or Venda, loose + artwork only; the server prices and approves it as a quote. An Interno + order takes the fixed customer from the database, a Venda one the customer + picked from Tiny. A Venda ships with the Site's freight or travels with the + customer's clothing order; an Interno never ships.""" request_key: UUID - customer: Customer + kind: Literal['interno', 'venda'] + # Empty for an Interno order: the server reads the internal customer. + customer: Customer | None = None items: list[Item] = Field(min_length=1, max_length=30) + # A Venda that travels with the customer's clothing order; pickup freight. + with_order: int | None = Field(default=None, ge=1, le=999999, strict=True) + # A Venda with "Envio": the chosen freight service and the full address. + freight: Freight | None = None + destination: Destination | None = None @model_validator(mode='after') - def loose_art_only(self): + def order_kind(self): if any(item.mode != 'avulsa' for item in self.items): raise ValueError('O montador só monta artes avulsas.') + if self.kind == 'venda' and self.customer is None: + raise ValueError('O pedido de venda precisa do cliente.') + delivery = bool(self.freight and self.freight.service != 'pickup') + if self.kind == 'interno': + if self.with_order is not None: + raise ValueError('O pedido interno não tem envio.') + if delivery or self.destination is not None: + raise ValueError('O pedido interno não tem envio.') + elif delivery: + if self.with_order is not None: + raise ValueError('Escolha retirada, envio ou junto com o pedido de roupa.') + if self.destination is None: + raise ValueError('O envio precisa do endereço completo.') + if self.destination.postal_code != self.freight.postal_code: + raise ValueError('O CEP do frete e o do endereço precisam ser o mesmo.') + elif self.destination is not None: + raise ValueError('Só o pedido com envio tem endereço de entrega.') return self class Review(StrictModel): @@ -396,7 +437,7 @@ class CouponNew(StrictModel): min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1) max_uses: int | None = Field(default=None, gt=0, strict=True) max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True) - product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None + product: Literal['file', 'avulsa', 'uvfile', 'uv', 'premium'] | None = None note: str = Field(default='', max_length=1000) @@ -409,7 +450,7 @@ class CouponUpdate(StrictModel): min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1) max_uses: int | None = Field(default=None, gt=0, strict=True) max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True) - product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None + product: Literal['file', 'avulsa', 'uvfile', 'uv', 'premium'] | None = None note: str | None = Field(default=None, max_length=1000) paused: bool | None = None @@ -528,3 +569,9 @@ class StampSizeTable(StrictModel): if len(letters) != len(set(letters)): raise ValueError('Cada tamanho tem uma letra própria.') return self + + +class StampBrand(StrictModel): + """The brand recorded per stamp code, for the future catalogue (front 7a.3).""" + brand: str = Field(default='', max_length=120) + public: bool = False diff --git a/app/core/pricing.py b/app/core/pricing.py index b2c631b..d0aad0e 100644 --- a/app/core/pricing.py +++ b/app/core/pricing.py @@ -8,7 +8,7 @@ import os import re from decimal import Decimal, ROUND_CEILING -PRICES = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990} +PRICES = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990, 'premium': 3990} # A finished sheet the Site cannot open (CDR, AI, PSD, TIFF) is opened by a # person before printing. It pays this per metre on top of the product's price @@ -25,7 +25,7 @@ def manual_extra_cents() -> int: def treatment_cents() -> int: - """The designer's treatment, a fixed amount per order (front 5). + """Ajuste Fino, a fixed amount per art (front 1a). Zero keeps the option hidden: the price is the client's decision, and the server and the Site read the same `TREATMENT_CENTS`. diff --git a/app/grade_rules.py b/app/grade_rules.py index a104d84..303fb63 100644 --- a/app/grade_rules.py +++ b/app/grade_rules.py @@ -2,8 +2,8 @@ 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). +order for the designer; `tratamento` makes Ajuste Fino required, but only while +it is offered (enabled and priced above zero). """ @@ -29,6 +29,6 @@ def triggered(rules: dict, items, treatment_offered: bool) -> dict: 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.') + """The refusal the customer sees when Ajuste Fino is required.""" + return (f'Sua arte tem nota {grade}: para imprimir com qualidade, o Ajuste Fino ' + 'é obrigatório neste pedido.') diff --git a/app/hotfolder.py b/app/hotfolder.py index 70f399e..bed73c3 100644 --- a/app/hotfolder.py +++ b/app/hotfolder.py @@ -1,8 +1,9 @@ """Each machine's hot folders (Dropstar's third round, item 10, 2026-10-29/30). -FlexiPRINT watches 3. Imprimindo/// and takes a file out -of it when it rips. When the operator pulls a card to Imprimindo, its files -go, as a copy, into its machine's folder for the item's contraction class; +FlexiPRINT watches 3. Imprimindo/// and takes a +file out of it when it rips. When the operator pulls a card to Imprimindo, its +files go, as a copy, into its machine's folder for the item's contraction +class; a premium item always goes to PREMIUM, whichever class it carries; the order's own file stays in its stage folder. A film over 15 m is several parts (item 13): all on the same machine, in order, never more than two in the folder at once. The third is written when Flexi takes the first. @@ -27,6 +28,8 @@ IN_FOLDER = 2 # A computer that claimed a part and never said it was written. CLAIM_TIMEOUT = timedelta(minutes=10) CLASSES = ('C1', 'C2', 'C3') +# The premium product's own folder (Dropstar, 2026-11-10, front 3). +PREMIUM = 'PREMIUM' def contraction(order, index): @@ -41,6 +44,13 @@ def contraction(order, index): return item.get('stroke_class') if item.get('stroke_class') in CLASSES else None +def folder_class(order, index): + """The folder an item's parts go to: PREMIUM for the premium product, + whatever contraction class is recorded, else C1/C2/C3.""" + item = order['snapshot']['items'][index] + return PREMIUM if item.get('mode') == 'premium' else contraction(order, index) + + def start(c, order_id): """The order entered Imprimindo: its approved finals queue for its machine's folder, item by item, part by part.""" @@ -83,7 +93,7 @@ def claim(c, user): machine, order = row['machine_id'], row['order_id'] if row['state'] != 'queued' or order in blocked: continue - cls = contraction(row, row['item_index']) + cls = folder_class(row, row['item_index']) # A part without its class waits, and the parts after it with it. if busy.get(machine, 0) >= IN_FOLDER or not cls: blocked.add(order) diff --git a/app/label.py b/app/label.py new file mode 100644 index 0000000..ea547b5 --- /dev/null +++ b/app/label.py @@ -0,0 +1,129 @@ +"""The 10x15 cm thermal label printed at Finalizado (Fase 2, front 10). + +Marcus, 2026-11-10: when a card reaches Finalizado the Kanban prints a label on +the Zebra ZD220: the Tiny order number, the customer, what the order is, pickup +or shipping, when it was released and by which Revisor, and a QR with the Tiny +order number only. The server renders the page so its content lives in one +place. The QR is an inline SVG from segno; nothing is loaded from outside. + +`label_fields` is pure, for the tests; `label_html` only adds the markup and the +QR. Without a Tiny receipt the order keeps its own DTF- as the number +and in the QR (an Interno order never reaches Tiny). +""" +import html +from datetime import timezone +from decimal import Decimal +from zoneinfo import ZoneInfo + +LOCAL = ZoneInfo('America/Sao_Paulo') + +SERVICE_NAMES = {'pac': 'Correios PAC', 'sedex': 'Correios SEDEX', 'jadlog': 'Jadlog'} + + +def _escape(value): + return html.escape(str(value if value is not None else ''), quote=True) + + +def _metres(items): + """The order's billed metres with a comma and two decimals, as the card shows.""" + total = sum((Decimal(str(item.get('billed_metres') or item.get('metres') or 0)) + for item in items), Decimal(0)) + return f'{total:.2f}'.replace('.', ',') + + +def _sheets(count): + return f'{count} folha' if count == 1 else f'{count} folhas' + + +def _delivery(snapshot): + """Retirada, Envio with the carrier the card shows, junto com a roupa, or Interno.""" + if snapshot.get('with_order'): + return f"Junto com pedido de roupa nº {snapshot['with_order']}" + if snapshot.get('kind') == 'interno': + return 'Interno' + if snapshot.get('destination'): + freight = snapshot.get('freight') or {} + service = freight.get('service') + return 'Envio · ' + (freight.get('description') or SERVICE_NAMES.get(service) or service or 'Frete') + return 'Retirada' + + +def _customer(snapshot): + customer = snapshot.get('customer') or {} + destination = snapshot.get('destination') or {} + return customer.get('name') or destination.get('recipient') or customer.get('mail') or '—' + + +def _finished_at(value): + if value is None: + return '' + if value.tzinfo is None: + value = value.replace(tzinfo=timezone.utc) + return value.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M') + + +def label_fields(order, tiny_number, finished_at, revisor): + """What the label says, from one order and its Tiny sale receipt.""" + snapshot = order.get('snapshot') or {} + items = snapshot.get('items') or [] + code = str(tiny_number) if tiny_number else f"DTF-{order['number']}" + return {'code': code, 'customer': _customer(snapshot), 'sheets': len(items), + 'metres': _metres(items), 'delivery': _delivery(snapshot), + 'finished_at': _finished_at(finished_at), 'revisor': revisor or '—', + 'qr': code} + + +def qr_svg(text): + """The QR as an inline SVG, dark on the label's white; segno is pure Python. + + `omitsize` keeps a viewBox and drops the fixed width/height, so the CSS can + print it at the label's 30 mm without the modules staying pixel-sized. + """ + import segno + return segno.make_qr(text, error='m').svg_inline(border=1, omitsize=True) + + +def label_html(fields): + """The printable page: 100 x 150 mm, black on white, no external resources.""" + code = _escape(fields['code']) + # The number is as large as its length allows on the 88 mm of usable width. + code_size = 22 if len(str(fields['code'])) <= 7 else 18 if len(str(fields['code'])) <= 9 else 15 + customer = _escape(fields['customer']) + sheets = _escape(_sheets(int(fields['sheets']))) + metres = _escape(fields['metres']) + delivery = _escape(fields['delivery']) + finished = _escape(fields['finished_at']) + revisor = _escape(fields['revisor']) + return f""" + + + +Etiqueta {code} + + + +
+
{code}
+
{customer}
+
DTF · {sheets} · {metres} m
+
{delivery}
+
Finalizado em {finished}
Revisor: {revisor}
+
{qr_svg(fields['qr'])}
+
+ + +""" diff --git a/app/machine_log.py b/app/machine_log.py index 8d8634d..0606ab4 100644 --- a/app/machine_log.py +++ b/app/machine_log.py @@ -16,8 +16,9 @@ once, which lets exactly one more card through. clean CLEAN_EVERY_METRES printed since the last "clean" event. align ALIGN_AFTER_FILM_METRES printed since the last film change (a supply entry of "film") with no "align" event after it. - supply a supply whose estimated stock is at or below the minimum Gestão set - for that machine (no minimum, no alert). + supply a supply whose estimated stock is at or below the machine's minimum: + the one Gestão typed, or Dropstar's default for that supply (1 roll + of film, 1 L of each ink, 5 kg of powder). The supply estimate assumes each entry refills what was used since the one before: the use per metre is the quantity entered over the metres printed in @@ -40,6 +41,11 @@ SUPPLY_INTERVALS = 3 SUPPLIES = {'film': ('Filme', 'rolo'), 'ink_c': ('Tinta ciano', 'L'), 'ink_m': ('Tinta magenta', 'L'), 'ink_y': ('Tinta amarela', 'L'), 'ink_k': ('Tinta preta', 'L'), 'ink_w': ('Tinta branca', 'L'), 'powder': ('Poliamida', 'kg')} +# Dropstar's fixed minimums (2026-11-10): a machine with no minimum typed uses +# these. Units match the supplies: rolls, litres and kilograms. +DEFAULT_MINIMUMS = {'film': Decimal('1'), 'ink_c': Decimal('1'), 'ink_m': Decimal('1'), + 'ink_y': Decimal('1'), 'ink_k': Decimal('1'), 'ink_w': Decimal('1'), + 'powder': Decimal('5')} PARTS = {'cap': 'Cap', 'damper': 'Damper', 'head': 'Cabeça de impressão', 'wiper': 'Wiper', 'other': 'Outra peça'} EVENTS = {'clean': 'Limpeza', 'align': 'Alinhamento da cabeça', 'stop': 'Parada'} @@ -130,8 +136,13 @@ def estimate(entries, metres_between, metres_since_last, minimum=None): 'minimum': minimum} +def minimum_for(minimums, item): + """The minimum typed for the machine, or Dropstar's default for that supply.""" + return minimums.get(item, DEFAULT_MINIMUMS.get(item)) + + def supply_low(value): - """Whether an estimate is at or below the machine's minimum (no minimum, no alert).""" + """Whether an estimate is at or below the machine's minimum (typed or default).""" return bool(value) and value['minimum'] is not None and value['stock'] <= value['minimum'] @@ -151,7 +162,8 @@ def supply_estimates(c, machine_id): continue printed = [printed_since(c, machine_id, row['created_at']) for row in rows] between = [printed[index - 1] - printed[index] for index in range(1, len(printed))] - value = estimate([row['quantity'] for row in rows], between, printed[-1], minimums.get(item)) + value = estimate([row['quantity'] for row in rows], between, printed[-1], + minimum_for(minimums, item)) if value is not None: result[item] = value return result diff --git a/app/mail.py b/app/mail.py index 99b192f..2fdd26e 100644 --- a/app/mail.py +++ b/app/mail.py @@ -93,7 +93,8 @@ def order_paid(c, order, origin): PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas', - 'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'} + 'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas', + 'premium': 'DTF Têxtil Premium · folha montada'} def quote_expired(c, quote, origin): diff --git a/app/migrations/202611111200_montador-interno-stamps.sql b/app/migrations/202611111200_montador-interno-stamps.sql new file mode 100644 index 0000000..f164de0 --- /dev/null +++ b/app/migrations/202611111200_montador-interno-stamps.sql @@ -0,0 +1,24 @@ +-- Front 7a.3: a brand per stamp, for the future catalogue, and the montador's +-- fixed internal customer. The brand is only recorded here for now; nothing +-- else reads it yet (Marcus, 2026-11-10). +CREATE TABLE IF NOT EXISTS dtf_local.stamps ( + code text PRIMARY KEY CHECK (code ~ '^[A-Za-z0-9_-]{1,40}$'), + brand text NOT NULL DEFAULT '', + public boolean NOT NULL DEFAULT false, + updated_by text NOT NULL, + updated_at timestamptz NOT NULL DEFAULT now() +); + +-- The one customer every Interno order belongs to (the marketplace's own +-- sales). Gestão completes it; until then an Interno order is refused. +CREATE TABLE IF NOT EXISTS dtf_local.internal_customer ( + id integer PRIMARY KEY DEFAULT 1 CHECK (id=1), + name text NOT NULL DEFAULT '', + cnpj text NOT NULL DEFAULT '', + zap text NOT NULL DEFAULT '', + mail text NOT NULL DEFAULT '', + updated_by text NOT NULL DEFAULT 'sistema', + updated_at timestamptz NOT NULL DEFAULT now() +); +INSERT INTO dtf_local.internal_customer(id,name) VALUES(1,'Nexstar · Marketplace') +ON CONFLICT (id) DO NOTHING; diff --git a/app/migrations/202611111200_premium-product.sql b/app/migrations/202611111200_premium-product.sql new file mode 100644 index 0000000..2836fb0 --- /dev/null +++ b/app/migrations/202611111200_premium-product.sql @@ -0,0 +1,17 @@ +-- Front 3: the Premium product (Marcus, 2026-11-10), built and switched OFF +-- until Dropstar prints the three test sheets and says "testado". The products +-- CHECK is the inline constraint of dtf_local.products.id, which Postgres +-- named products_id_check; widening a list is a new migration that drops and +-- adds that one constraint (never schema.sql). +ALTER TABLE dtf_local.products DROP CONSTRAINT IF EXISTS products_id_check; +ALTER TABLE dtf_local.products ADD CONSTRAINT products_id_check + CHECK (id IN ('file','avulsa','uvfile','uv','premium','tratamento')); + +INSERT INTO dtf_local.products(id, enabled) VALUES ('premium', false) +ON CONFLICT (id) DO NOTHING; + +-- A coupon may also target the new product (the Site tab lists every mode). +ALTER TABLE dtf_local.coupons DROP CONSTRAINT IF EXISTS coupons_product_check; +ALTER TABLE dtf_local.coupons ADD CONSTRAINT coupons_product_check + CHECK (product IN ('file','avulsa','uvfile','uv','premium')); + diff --git a/app/migrations/202611111530_label-prints.sql b/app/migrations/202611111530_label-prints.sql new file mode 100644 index 0000000..c12dcd9 --- /dev/null +++ b/app/migrations/202611111530_label-prints.sql @@ -0,0 +1,12 @@ +-- Front 10: the 10x15 cm label at Finalizado (Marcus, 2026-11-10). One 'auto' +-- print per order, decided by the unique partial index, so two computers +-- asking at once cannot both print it; a reprint is always another row. +CREATE TABLE IF NOT EXISTS dtf_local.label_prints ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE, + reason text NOT NULL CHECK (reason IN ('auto','reprint')), + printed_by text NOT NULL, + printed_at timestamptz NOT NULL DEFAULT now() +); +CREATE UNIQUE INDEX IF NOT EXISTS label_prints_one_auto + ON dtf_local.label_prints(order_id) WHERE reason='auto'; diff --git a/app/observability.py b/app/observability.py new file mode 100644 index 0000000..bc16dd7 --- /dev/null +++ b/app/observability.py @@ -0,0 +1,139 @@ +"""Sentry for the API and the worker, off until a DSN arrives (note Sentry). + +`init(component)` reads `SENTRY_DSN_API` and returns without importing the SDK +when it is empty, so local and CI runs carry no Sentry dependency or network +cost. When it is set, `scrub` keeps cookies, credentials, request bodies and +Brazilian personal data out of the events (LGPD). +""" +import os +import re +from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit + +EMAIL = re.compile(r'[^\s@]+@[^\s@]+\.[A-Za-z]{2,}') +# CPF (11 digits) or CNPJ (14), with or without punctuation. +DOCUMENT = re.compile(r'(? LARGE_SOURCE_BYTES and not row['name'].lower().endswith(STREAMED) for row in uploads): finish(job, 'manual', {'reason': f'arquivo acima de {LARGE_SOURCE_BYTES // 1048576} MB que não é PNG nem PDF: ' diff --git a/app/quote_review.py b/app/quote_review.py index 20359d4..5540171 100644 --- a/app/quote_review.py +++ b/app/quote_review.py @@ -74,7 +74,7 @@ def approve(c, row, items, reviewer): c, [item.model_dump(mode='json') for item in items], names, coupon_code=draft.get('coupon'), customer_document=(draft.get('customer') or {}).get('cnpj'), - wants_treatment=bool(draft.get('treatment')), + wants_treatment=draft.get('treatment', False), treatment_rule=not draft.get('montador')) # Keep the review snapshot's own fields with each priced item. priced = cart['items'] @@ -99,7 +99,7 @@ def approve(c, row, items, reviewer): coupon = cart['coupon'] discount = coupon['discount_cents'] if coupon else 0 flags = cart['grade_flags'] - treatment = cart['treatment_cents'] + treatment = cart['treatment'] metres = sum(Decimal(i['billed_metres']) for i in priced) try: quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''), @@ -110,15 +110,16 @@ def approve(c, row, items, reviewer): '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 {}), + # Ajuste Fino: per art, with the row's band (front 1a). + **({'treatment': treatment} 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). **({'timings': draft['timings']} if draft.get('timings') else {}), - 'total_cents': items_total - discount + quoted_freight['total_cents'] + treatment} + 'total_cents': items_total - discount + quoted_freight['total_cents'] + + treatment.get('cents', 0)} 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/receipt.py b/app/receipt.py index f146d3c..5b2f966 100644 --- a/app/receipt.py +++ b/app/receipt.py @@ -21,7 +21,8 @@ MARGIN = 4 * MM ROOM = WIDTH - 2 * MARGIN FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'} PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas', - 'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'} + 'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas', + 'premium': 'DTF Têxtil Premium · folha montada'} METHODS = {'pix': 'Pix', 'card': 'Cartão', 'cash': 'Dinheiro', 'credit': 'Crédito do cliente'} # Helvetica's widths for what the tables in printfile.py leave out. EXTRA = {'$': 556, '(': 333, ')': 333, '_': 556, '#': 556, '—': 1000, '@': 1015, '&': 667, '+': 584, "'": 191} diff --git a/app/runtime.py b/app/runtime.py index 1acee11..798d038 100644 --- a/app/runtime.py +++ b/app/runtime.py @@ -142,9 +142,9 @@ def quote_view(c, row, order=None, attempt=None, known=False): items = (row['approved'] or row['draft']).get('items') or [] treatment = (row['approved'] or {}).get('treatment') 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} + from .cart_pricing import treatment_price + treatment = treatment_price(items, (row['draft'] or {}).get('treatment'), + catalog.current(c)['tratamento']) or None 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, diff --git a/app/tiny.py b/app/tiny.py index 2ecb8b1..3c7c916 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -59,29 +59,34 @@ AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect' # Not TINY_PRODUCT_: app/core/secrets.py reads any variable ending in # _FILE as a path to a secret file, and one product mode is called "file". PRODUCT_SETTINGS = {'file': 'TINY_PRODUCT_TEXTIL_FOLHA', 'avulsa': 'TINY_PRODUCT_TEXTIL_AVULSA', - 'uvfile': 'TINY_PRODUCT_UV_FOLHA', 'uv': 'TINY_PRODUCT_UV_AVULSA'} + 'uvfile': 'TINY_PRODUCT_UV_FOLHA', 'uv': 'TINY_PRODUCT_UV_AVULSA', + 'premium': 'TINY_PRODUCT_TEXTIL_PREMIUM'} # The common code prefix of a mode's SKUs ("DTFIMP.TX" for DTFIMP.TX.100CM, # the metre, and DTFIMP.TX.0010CM to DTFIMP.TX.0090CM). When set, it replaces # the mode's product id. SKU_SETTINGS = {'file': 'TINY_SKU_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_TEXTIL_AVULSA', - 'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA'} + 'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA', + 'premium': 'TINY_SKU_TEXTIL_PREMIUM'} # Or a SKU per 10 cm ("DTFIMP.UV.010CM"), alone (2,30 m is 23 of it) or after # a metre SKU ("DTFIMP.UV.1MT"): 2,30 m is 2 metres and 3 of the 10 cm. STEP_SETTINGS = {'file': 'TINY_SKU10_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU10_TEXTIL_AVULSA', - 'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA'} + 'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA', + 'premium': 'TINY_SKU10_TEXTIL_PREMIUM'} METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_METRO_TEXTIL_AVULSA', - 'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA'} + 'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA', + 'premium': 'TINY_SKU_METRO_TEXTIL_PREMIUM'} # Dropstar's own catalogue (checked against its Tiny export, 2026-10-14): Têxtil # as DTFIMP.TX.100CM per metre and DTFIMP.TX.0010CM to 0090CM for the rest, UV # as DTFIMP.UV.1MT per metre and DTFIMP.UV.010CM per 10 cm, the ready sheet and # loose artwork alike. The settings above only override these. -SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX'} +SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX', 'premium': 'DTFIMP.TXP'} STEP_DEFAULTS = {'uvfile': 'DTFIMP.UV.010CM', 'uv': 'DTFIMP.UV.010CM'} METRE_DEFAULTS = {'uvfile': 'DTFIMP.UV.1MT', 'uv': 'DTFIMP.UV.1MT'} PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada', 'avulsa': 'DTF Têxtil 57 cm · artes avulsas', 'uvfile': 'DTF UV 27 cm · folha montada', - 'uv': 'DTF UV 27 cm · artes avulsas'} + 'uv': 'DTF UV 27 cm · artes avulsas', + 'premium': 'DTF Têxtil Premium 57 cm · folha montada'} # How far back to look for an order a previous delivery may already have made. SEARCH_DAYS = 7 # A "ready" event can come after corrections; it normally knows the Tiny id. @@ -103,8 +108,19 @@ OUTSIDE_NOTES = {'pix': 'Pix', 'card': 'cartão', 'cash': 'dinheiro', 'credit': def internal_note(payload): paid = payload.get('payment') or {} - how = f"pago fora do site ({OUTSIDE_NOTES.get(paid.get('method'), paid.get('method'))})" if paid.get('outside') else 'pago' - return f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}" + method = paid.get('method') + if method == 'faturado': + # A montador Venda order is invoiced (front 7a.3): its forma de + # recebimento is "Boleto" when the client's id is configured. + boleto = os.environ.get('TINY_RECEIPT_BOLETO', '').strip() + how = 'faturado (Boleto)' if boleto.isdigit() else 'faturado: forma de recebimento a definir' + else: + how = f"pago fora do site ({OUTSIDE_NOTES.get(method, method)})" if paid.get('outside') else 'pago' + note = f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}" + with_order = (payload.get('order') or {}).get('with_order') + if with_order: + note += f' · junto com o pedido de roupa nº {with_order}' + return note STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES' @@ -119,8 +135,12 @@ PICKUP_EXACT = 'retirar pessoalmente' # looked up: Pix and credit card, as the store's orders are paid, and the # DropStar carrier its pickup orders name. Dinheiro and, for the customer's # credit, Dropstar's own "CORREÇÃO DTF" were sent by Marcus on 2026-10-27, for -# the orders the team registers as paid outside the site (D-35). -RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 977493654} +# the orders the team registers as paid outside the site (D-35). "Boleto" is +# for a montador Venda order (front 7a.3); no id is known yet, and while +# TINY_RECEIPT_BOLETO is empty the order goes without a forma de recebimento. +_BOLETO = os.environ.get('TINY_RECEIPT_BOLETO', '').strip() +RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 977493654, + **({'faturado': int(_BOLETO)} if _BOLETO.isdigit() else {})} PICKUP_CARRIER = 761565838 # Dropstar's answers: the financial category "DTF SITE" (RECEITAS, id sent on # 2026-10-26; it goes in pagamento.categoria, and replaced the store's @@ -438,6 +458,30 @@ def search_forms(document): return list(dict.fromkeys((punctuated(d), d))) +def search_contacts(orders, query, limit=10): + """Up to `limit` contacts matching what was typed (the montador's typeahead, + front 7a.3): by CPF/CNPJ when it is only digits and punctuation, else by + name. Tiny's own search does the matching.""" + text = str(query or '').strip() + digits = ''.join(ch for ch in text if ch.isdigit()) + found = [] + if digits and not any(ch.isalpha() for ch in text): + for form in search_forms(digits): + found += orders.request('GET', '/contatos', params={'cpfCnpj': form, 'limit': limit}).get('itens') or [] + else: + found = orders.request('GET', '/contatos', params={'nome': text, 'limit': limit}).get('itens') or [] + contacts, seen = [], set() + for entry in found: + if entry.get('id') in seen: + continue + seen.add(entry.get('id')) + contacts.append({'id': entry.get('id'), 'name': entry.get('nome') or '', + 'document': entry.get('cpfCnpj') or '', + 'email': entry.get('email') or '', + 'phone': entry.get('telefone') or entry.get('celular') or ''}) + return contacts[:limit] + + def contact_payload(order, company=None): """A new contact, named after the company's razão social when the registry gave it (app/cnpj.py), else the customer's name, else the @@ -506,9 +550,14 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non 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'}) + # Per art (front 1a): the line carries the band unit price and the arts + # as its quantity. An old quote without those keeps one art at its total. + arts = int(treatment.get('arts') or 1) + unit = int(treatment.get('unit_cents') or treatment['cents']) + items.append({'produto': {'id': int(setting)}, 'quantidade': arts, + 'valorUnitario': money(unit), + 'infoAdicional': 'Ajuste Fino · '+str(arts)+ + (' arte' if arts == 1 else ' artes')+' · +24 h'}) freight = order['freight'] service = freight.get('service') pickup = service == 'pickup' diff --git a/app/worker.py b/app/worker.py index d72cbf9..cea0b8a 100644 --- a/app/worker.py +++ b/app/worker.py @@ -6,7 +6,7 @@ import threading import time from http.server import BaseHTTPRequestHandler, HTTPServer from psycopg.types.json import Jsonb -from . import mail, unpaid +from . import mail, observability, unpaid from .adapters import FakeTiny, LocalS3Storage, require_runtime from .core.secrets import load as load_secret_files from .core.db import connect @@ -162,6 +162,7 @@ class Health(BaseHTTPRequestHandler): pass if __name__ == '__main__': + observability.init('worker') scan_thread = threading.Thread(target=scan_loop,args=(storage,),daemon=True) scan_thread.start() render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True) diff --git a/compose.local.yaml b/compose.local.yaml index 4fd89b7..76932e0 100644 --- a/compose.local.yaml +++ b/compose.local.yaml @@ -27,6 +27,10 @@ x-app: &app ALLOWED_HOSTS: ${ALLOWED_HOSTS:-localhost,127.0.0.1} ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-http://localhost:${SITE_PORT:-8080},http://localhost:${KANBAN_PORT:-8081},http://127.0.0.1:${SITE_PORT:-8080},http://127.0.0.1:${KANBAN_PORT:-8081}} COOKIE_SECURE: "false" + # Sentry stays off locally unless real DSNs are set in .env. + SENTRY_DSN_API: ${SENTRY_DSN_API:-} + SENTRY_DSN_WEB: ${SENTRY_DSN_WEB:-} + SENTRY_ENVIRONMENT: ${SENTRY_ENVIRONMENT:-} # Sandbox testing only: set PAYMENT_ADAPTER=mercadopago with the MP_* test # credentials, or TINY_ADAPTER=tiny with a TINY_TOKEN, in .env. Never real # production credentials on a developer machine. @@ -274,6 +278,7 @@ services: # Empty unless testing Mercado Pago's card form; see docs/LOCAL_SETUP.md. PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-} PAYMENT_CHALLENGE_SOURCES: ${PAYMENT_CHALLENGE_SOURCES:-} + SENTRY_CSP_SOURCES: "" ports: # Published ports are host-wide even bound to loopback, so on a shared # machine any of them can collide with something unrelated. CI overrides @@ -299,6 +304,7 @@ services: S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:${STORAGE_PORT:-9000}} PAYMENT_CSP_SOURCES: "" PAYMENT_CHALLENGE_SOURCES: "" + SENTRY_CSP_SOURCES: "" ports: ["127.0.0.1:${KANBAN_PORT:-8081}:80"] networks: [local, edge] depends_on: diff --git a/deploy/nginx.conf.template b/deploy/nginx.conf.template index a1dbc11..301d85e 100644 --- a/deploy/nginx.conf.template +++ b/deploy/nginx.conf.template @@ -27,7 +27,7 @@ server { add_header Referrer-Policy no-referrer always; add_header X-Frame-Options DENY always; add_header Permissions-Policy "camera=(self), microphone=(), geolocation=()" always; - add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always; + add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES} ${SENTRY_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always; location = /health { access_log off; return 200 'ok'; } location /api/ { @@ -49,7 +49,7 @@ server { # Always revalidate HTML/JS/CSS after a deployment. Without this, a browser # can pair a new Kanban page with a cached older script after a rollout. # The Site's product pages and cart are addresses of the same page (web/site-pages.js). - location ~ ^/(arquivo-por-metro|artes-avulsas|uv-arquivo-por-metro|uv-artes-avulsas|carrinho|pagamento|pagamento/pix)/?$ { + location ~ ^/(arquivo-por-metro|artes-avulsas|uv-arquivo-por-metro|uv-artes-avulsas|premium|carrinho|pagamento|pagamento/pix)/?$ { expires -1; try_files /index.html =404; } diff --git a/deploy/portainer.env.example b/deploy/portainer.env.example index 449a17b..00b89f5 100644 --- a/deploy/portainer.env.example +++ b/deploy/portainer.env.example @@ -51,6 +51,8 @@ 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 +# Tiny id of the forma de recebimento "Boleto" (montador Venda orders). +TINY_RECEIPT_BOLETO= # E-mail (password recovery and team alerts). off until the SMTP account exists. MAIL_ADAPTER=off MAIL_FROM=DTF Dropstar @@ -74,6 +76,11 @@ BACKUP_SECRET_ACCESS_KEY=TBD BACKUP_AGE_RECIPIENT=age1... BACKUP_HOUR=3 +# Sentry: empty DSNs keep it off; the environment defaults to production. +SENTRY_DSN_API= +SENTRY_DSN_WEB= +SENTRY_ENVIRONMENT= + # Names of external Portainer/Docker Swarm secrets, never their values. DATABASE_URL_SECRET=TBD DATABASE_ADMIN_URL_SECRET=TBD diff --git a/docker-compose.yml b/docker-compose.yml index 0056228..ddaa617 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -12,6 +12,10 @@ x-app-environment: &app-environment # connection per `with` block, exactly as before (the production default). DB_POOL: ${DB_POOL:-off} DB_POOL_SIZE: ${DB_POOL_SIZE:-20} + # Sentry: empty DSNs leave it off; the environment defaults to production. + SENTRY_DSN_API: ${SENTRY_DSN_API:-} + SENTRY_DSN_WEB: ${SENTRY_DSN_WEB:-} + SENTRY_ENVIRONMENT: ${SENTRY_ENVIRONMENT:-production} S3_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT} S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT} S3_BUCKET: ${R2_BUCKET:?set R2_BUCKET} @@ -120,6 +124,9 @@ x-app-environment: &app-environment # Optional e-commerce channel id for Site orders. Without it the order still # carries DTF- as numeroPedidoEcommerce, with no channel. TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-} + # The Tiny forma de recebimento id of "Boleto", for invoiced montador Venda + # orders (front 7a.3). Empty: the order goes without one and its note says so. + TINY_RECEIPT_BOLETO: ${TINY_RECEIPT_BOLETO:-} # Sets "Aprovada" on paid orders and "Pronto para envio" on finished pickup # orders, which the client's Tiny -> n8n notices send to customers. Turn on # only together with TINY_ADAPTER=tiny and after n8n stops sending the @@ -298,6 +305,8 @@ services: # Mercado Pago's card form loads from these origins; empty keeps the # Site at script-src 'self'. Set together with the Mercado Pago adapter. PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-} + # The Sentry ingest origin(s) for connect-src; empty until the DSN exists. + SENTRY_CSP_SOURCES: ${SENTRY_CSP_SOURCES:-https://o4510863040905216.ingest.us.sentry.io} # The bank's confirmation page for debit and other 3-D Secure cards is # on the issuer's own domain, so it cannot be listed: "https:" lets # frames and form posts reach it (never scripts). Empty turns it off. @@ -326,6 +335,8 @@ services: S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT} PAYMENT_CSP_SOURCES: "" PAYMENT_CHALLENGE_SOURCES: "" + # The Kanban reports to Sentry too; set from the browser DSN host. + SENTRY_CSP_SOURCES: ${SENTRY_CSP_SOURCES:-https://o4510863040905216.ingest.us.sentry.io} networks: [backend] ports: - target: 8080 diff --git a/docs/PORTAINER.md b/docs/PORTAINER.md index c08ae67..9638d5e 100644 --- a/docs/PORTAINER.md +++ b/docs/PORTAINER.md @@ -243,6 +243,19 @@ behaviour). Set it to `on` in the stack's environment and redeploy to keep between 1 and `DB_POOL_SIZE` connections per process (`DB_POOL_SIZE` defaults to 20); set it back to `off` to return to one connection per block. +## 11. Sentry + +Sentry is built into the API, the worker, the Site and the Kanban, and stays +off while the DSNs are empty. Set `SENTRY_DSN_API` and `SENTRY_DSN_WEB` in the +stack's environment, and optionally `SENTRY_ENVIRONMENT` (defaults to +`production`). The API and worker initialise from `SENTRY_DSN_API`; the browser +reads `SENTRY_DSN_WEB` from `/api/session` on the Site and from +`/api/operator/me` on the Kanban. When the DSNs exist, also set +`SENTRY_CSP_SOURCES` to the Sentry ingest origin, such as +`https://o123.ingest.sentry.io` (or `https://*.ingest.sentry.io`), so the CSP +`connect-src` allows the browser to send events. No image change is needed to +switch it on: update the stack variables and redeploy. + ## Current blocker This is the final deployment shape, but it is not authorized for production diff --git a/infra/nginx.conf.template b/infra/nginx.conf.template index c948ebf..eab6a51 100644 --- a/infra/nginx.conf.template +++ b/infra/nginx.conf.template @@ -9,7 +9,7 @@ server { add_header Referrer-Policy no-referrer always; add_header X-Frame-Options DENY always; add_header Permissions-Policy "camera=(self), microphone=(), geolocation=()" always; - add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always; + add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES} ${SENTRY_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always; location = /health { access_log off; return 200 'ok'; } location /api/ { limit_req zone=api_limit burst=100 nodelay; diff --git a/infra/requirements.lock b/infra/requirements.lock index a89136e..887642a 100644 --- a/infra/requirements.lock +++ b/infra/requirements.lock @@ -34,6 +34,7 @@ certifi==2026.10.19 \ # via # httpcore # httpx + # sentry-sdk click==8.5.0 \ --hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \ --hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34 @@ -616,6 +617,14 @@ s3transfer==0.13.1 \ --hash=sha256:a981aa7429be23fe6dfc13e80e4020057cbab622b08c0315288758d67cabc724 \ --hash=sha256:c3fdba22ba1bd367922f27ec8032d6a1cf5f10c934fb5d68cf60fd5a23d936cf # via boto3 +segno==1.6.6 \ + --hash=sha256:28c7d081ed0cf935e0411293a465efd4d500704072cdb039778a2ab8736190c7 \ + --hash=sha256:e60933afc4b52137d323a4434c8340e0ce1e58cec71439e46680d4db188f11b3 + # via -r infra/requirements.txt +sentry-sdk==2.74.0 \ + --hash=sha256:40b205af015649df3ec9986e057ce24ce85956bee3fb75efa72c93aa7036bdff \ + --hash=sha256:dd91d75aacaef636006b579ac3ddb2fdbc9dce35f00f4b353b6b1b110c6b256a + # via -r infra/requirements.txt six==1.17.0 \ --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \ --hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81 @@ -647,7 +656,9 @@ typing-inspection==0.4.4 \ urllib3==2.7.0 \ --hash=sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c \ --hash=sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897 - # via botocore + # via + # botocore + # sentry-sdk uvicorn==0.34.2 \ --hash=sha256:0e929828f6186353a80b58ea719861d2629d766293b6d19baf086ba31d4f3328 \ --hash=sha256:deb49af569084536d269fe0a6d67e3754f104cf03aba7c11c40f01aadf33c403 diff --git a/infra/requirements.txt b/infra/requirements.txt index a528694..ee549c5 100644 --- a/infra/requirements.txt +++ b/infra/requirements.txt @@ -8,3 +8,5 @@ httpx==0.28.1 pillow==13.0.0 pikepdf==10.13.0.post1 pypdfium2==5.14.0 +segno==1.6.6 +sentry-sdk==2.74.0 diff --git a/tests/grade_rules_test.py b/tests/grade_rules_test.py index 8be6828..6a2be79 100644 --- a/tests/grade_rules_test.py +++ b/tests/grade_rules_test.py @@ -49,17 +49,17 @@ def run(): 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 + 'o Ajuste Fino é 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['treatment'] == {'cents': 1000, 'hours': 24, 'arts': 1, + 'unit_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') + print('PASS: the grade rule requires Ajuste Fino and flags the order with the worst grade') finally: if rules_set: try: diff --git a/tests/label_test.py b/tests/label_test.py new file mode 100644 index 0000000..aeb2615 --- /dev/null +++ b/tests/label_test.py @@ -0,0 +1,99 @@ +"""The 10x15 thermal label at Finalizado (Fase 2, front 10). + +Run inside the API container: python -m tests.label_test +""" +from urllib.error import HTTPError +from urllib.request import Request +from uuid import uuid4 + +from psycopg.types.json import Jsonb + +from app.core import db +from tests.smoke_test import BASE, Client, with_host +from tests.users_test import PASSWORD, order_fixture + + +def label_page(client, order_id, expected=200): + """GET the label as the browser does; returns the HTML (or the error body).""" + request = Request(BASE + '/api/operator/orders/' + order_id + '/label', headers=with_host()) + try: + with client.opener.open(request, timeout=30) as response: + assert response.status == expected, (response.status, expected) + assert response.headers.get_content_type() == 'text/html', response.headers + return response.read().decode() + except HTTPError as error: + if error.code != expected: + raise AssertionError((error.code, expected, error.read().decode())) from error + return error.read().decode() + + +def user(superadmin, tag, role, name): + email = f'etiqueta-{tag}-{role}@example.test' + superadmin.call('/operator/users', + {'name': name, 'email': email, 'role': role, 'password': PASSWORD}, operator=True) + client = Client() + client.call('/session') + client.call('/operator/login', {'email': email, 'password': PASSWORD}) + return client + + +def run(): + su = Client() + su.call('/session') + su.call('/operator/me', operator=True) # the default superadmin + tag = uuid4().hex[:6] + revisor_email = f'etiqueta-{tag}-revisor@example.test' + revisor = user(su, tag, 'revisor', 'Revisor Etiqueta') + designer = user(su, tag, 'designer', 'Designer Etiqueta') + expedicao = user(su, tag, 'expedicao', 'Expedição Etiqueta') + + owner = uuid4() + with db.connect() as c: + _, order_id = order_fixture(c, owner, 'file', metres='2.5') + snapshot = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone()['snapshot'] + snapshot['customer']['name'] = 'Cliente Etiqueta' + snapshot['destination'] = {'recipient': 'Loja Etiqueta', 'street': 'Rua A', 'number': '10', + 'complement': '', 'district': 'Centro', 'city': 'Franca', + 'state': 'SP', 'postal_code': '14400000'} + snapshot['freight'] = {'service': 'jadlog', 'description': 'Jadlog .Package', 'total_cents': 1500} + c.execute("UPDATE dtf_local.orders SET snapshot=%s, state='fin' WHERE id=%s", + (Jsonb(snapshot), order_id)) + c.execute("INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) " + "VALUES(%s,'rev','fin',%s,'')", (order_id, revisor_email)) + number = c.execute('SELECT number FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone()['number'] + oid = str(order_id) + + # The first computer claims the automatic print; the second does not. + assert su.call(f'/operator/orders/{oid}/label/claim', {}, operator=True) == {'print': True} + assert su.call(f'/operator/orders/{oid}/label/claim', {}, operator=True) == {'print': False} + # A reprint always prints, on any computer. + assert su.call(f'/operator/orders/{oid}/label/reprint', {}, operator=True) == {'print': True} + + # The page is the server's HTML: customer, what the order is, delivery, QR. + page = label_page(revisor, oid) + assert 'Cliente Etiqueta' in page, page + assert 'DTF · 1 folha · 2,50 m' in page, page + assert 'Envio · Jadlog .Package' in page, page + assert 'Revisor Etiqueta' in page, page + assert ' before[method]['metres'], (method, before[method], after[method]) + assert after_stats['cents'] == before_stats['cents'], (before_stats['cents'], after_stats['cents']) + # The same montagem cannot become a second order. - refused = shipping.call('/operator/montador/orders', body, expected=409) - assert refused['detail'] == f"Esta montagem já virou o pedido #{order['number']}.", refused - # A designer does not use the montador, and only loose art becomes one. + refused = seller.call('/operator/montador/orders', venda_body, expected=409) + assert refused['detail'] == f"Esta montagem já virou o pedido #{order_venda['number']}.", refused + # Each profile makes only its own kind, and only loose art becomes one. + seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno}, expected=403) + shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **venda}, expected=403) designer.call('/operator/montador/uploads', {'name': 'ESTAMPA.png', 'size': 1}, expected=403) - designer.call('/operator/montador/orders', body, expected=403) - shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'customer': customer, + designer.call('/operator/montador/orders', {'request_key': str(uuid4()), **venda}, expected=403) + shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'interno', 'items': [montador_item(stamp, 'file')]}, expected=422) - print('PASS: Expedição reads the sizes, uploads a stamp and gets the invoiced montador card; ' - 'Gestão edits the table; invalid rows, profiles and modes are refused') + + # Venda with Envio: the Site's freight, re-quoted by the server. + destination = {'recipient': 'Maria Souza', 'street': 'Rua das Flores', 'number': '100', + 'complement': 'Sala 2', 'district': 'Centro', 'city': 'Franca', + 'state': 'SP', 'postal_code': '14400000'} + envio_stamp = upload_stamp(seller) + envio = {'kind': 'venda', 'customer': envio_customer, 'items': [montador_item(envio_stamp)], + 'freight': {'service': 'mock-standard', 'postal_code': '14400000'}, + 'destination': destination} + order_envio = seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **envio}) + made_orders.append(UUID(order_envio['id'])) + made_quotes.append(UUID(order_envio['quote_id'])) + snapshot = order_envio['snapshot'] + assert snapshot['destination'] == destination, snapshot.get('destination') + assert snapshot['freight']['service'] == 'mock-standard', snapshot.get('freight') + assert snapshot['freight']['total_cents'] > 0, snapshot.get('freight') + assert snapshot['total_cents'] == (sum(item['total_cents'] for item in snapshot['items']) + + snapshot['freight']['total_cents']), snapshot['total_cents'] + with db.connect() as c: + assert c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s AND provider=%s', + (f"{order_envio['id']}:paid:tiny", 'tiny')).fetchone() + # Envio needs the full address; an Interno order never ships. + sem_destino = {key: value for key, value in envio.items() if key != 'destination'} + seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **sem_destino}, expected=422) + shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'interno', + 'items': [montador_item(stamp)], + 'destination': destination}, expected=422) + print('PASS: Expedição makes Interno and Vendedor makes Venda; the internal customer, the Tiny ' + 'contacts, the stamp brand and the table price in Números work; a Venda with Envio carries ' + 'the destination and the quoted freight; invalid profiles, modes and deliveries are refused') finally: with db.connect() as c: + if made_orders: + c.execute("DELETE FROM dtf_local.outbox WHERE payload->>'order_id' = ANY(%s::text[])", + ([str(oid) for oid in made_orders],)) for oid in made_orders: c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (oid,)) c.execute('DELETE FROM dtf_local.order_files WHERE order_id=%s', (oid,)) @@ -139,8 +245,13 @@ def run(): c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,)) if made_quotes: c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', (made_quotes,)) - c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr=%s', (customer['mail'],)) - c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (identity,)) + c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr IN (%s,%s,%s)', + (internal_customer['mail'], venda_customer['mail'], envio_customer['mail'])) + for identity in identities: + c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (identity,)) + c.execute('DELETE FROM dtf_local.stamps WHERE code=%s', (stamp_code,)) + c.execute('UPDATE dtf_local.internal_customer SET name=%s,cnpj=%s,zap=%s,mail=%s', + (internal['name'], internal['cnpj'], internal['zap'], internal['mail'])) c.execute('DELETE FROM dtf_local.stamp_sizes') c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES(%s,%s)', table) c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',)) diff --git a/tests/test_cart_pricing.py b/tests/test_cart_pricing.py index 95e91d9..62b0df3 100644 --- a/tests/test_cart_pricing.py +++ b/tests/test_cart_pricing.py @@ -9,7 +9,7 @@ import unittest from decimal import Decimal from app import catalog -from app.cart_pricing import price_items +from app.cart_pricing import price_items, treatment_price from app.core import pricing @@ -156,6 +156,21 @@ class CartPricingCharacterizationTest(unittest.TestCase): floating = priced('band-floating-metres')[0] self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.9', 24650)) + def test_ajuste_fino_is_per_art_with_the_band(self): + # Front 1a: 1 to 9 arts at R$ 9,90, from 10 at R$ 6,90, all arts charged + # at the band. `true` keeps meaning every art of the cart. + offer = {'enabled': True, 'unit_cents': 990, + 'bands': [{'from_metres': '10', 'unit_cents': 690}]} + for arts, unit in ((1, 990), (9, 990), (10, 690), (12, 690)): + items = [item('avulsa', '1', uid=f'u{index}') for index in range(arts)] + self.assertEqual(treatment_price(items, True, offer), + {'cents': unit * arts, 'hours': 24, 'arts': arts, 'unit_cents': unit}) + items = [item('file', '1', uid='u1'), item('file', '1', uid='u2')] + self.assertEqual(treatment_price(items, [[1, 0]], offer), + {'cents': 990, 'hours': 24, 'arts': 1, 'unit_cents': 990}) + self.assertEqual(treatment_price(items, [], offer), {}) + self.assertEqual(treatment_price(items, True, {**offer, 'enabled': False}), {}) + if __name__ == '__main__': unittest.main() diff --git a/tests/test_grade_rules.py b/tests/test_grade_rules.py index ceec3ef..cb0889b 100644 --- a/tests/test_grade_rules.py +++ b/tests/test_grade_rules.py @@ -34,7 +34,7 @@ class GradeRulesTest(unittest.TestCase): def test_treatment_message(self): self.assertEqual( treatment_message(45), - 'Sua arte tem nota 45: para imprimir com qualidade, o tratamento pelo designer ' + 'Sua arte tem nota 45: para imprimir com qualidade, o Ajuste Fino ' 'é obrigatório neste pedido.') diff --git a/tests/test_hotfolder.py b/tests/test_hotfolder.py new file mode 100644 index 0000000..85cbba7 --- /dev/null +++ b/tests/test_hotfolder.py @@ -0,0 +1,26 @@ +"""The machine hot folder class (Fase 2, front 3), without a database.""" +import unittest + +from app.hotfolder import PREMIUM, contraction, folder_class + + +def order(mode, stroke_class='C2', chosen=None): + return {'snapshot': {'items': [{'mode': mode, 'stroke_class': stroke_class}]}, + 'contraction': {'0': {'class': chosen}} if chosen else {}} + + +class FolderClassTest(unittest.TestCase): + def test_premium_always_goes_to_its_own_folder(self): + # Marcus, 2026-11-10: every premium item, whatever its contraction class. + self.assertEqual(folder_class(order('premium', 'C3'), 0), PREMIUM) + self.assertEqual(folder_class(order('premium', 'C1', chosen='C2'), 0), PREMIUM) + + def test_a_recorded_contraction_class_still_wins_for_other_products(self): + self.assertEqual(folder_class(order('file', 'C1', chosen='C2'), 0), 'C2') + self.assertEqual(folder_class(order('file'), 0), 'C2') + self.assertIsNone(contraction(order('file', None), 0)) + self.assertIsNone(folder_class(order('file', None), 0)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_label.py b/tests/test_label.py new file mode 100644 index 0000000..a217431 --- /dev/null +++ b/tests/test_label.py @@ -0,0 +1,80 @@ +"""The 10x15 label's fields and page (Fase 2, front 10), without a database.""" +import importlib.util +import unittest +from datetime import datetime, timezone + +from app.label import label_fields, label_html + +HAS_SEGNO = importlib.util.find_spec('segno') is not None + + +def order(**snapshot): + content = {'customer': {'name': 'Cliente Etiqueta', 'mail': 'cliente@example.test'}, + 'items': [{'billed_metres': '1.5'}, {'billed_metres': '1'}], + 'destination': {'recipient': 'Loja Etiqueta'}, + 'freight': {'service': 'jadlog', 'description': 'Jadlog .Package'}} + content.update(snapshot) + return {'number': 42, 'snapshot': content} + + +FINISHED = datetime(2026, 11, 11, 17, 32, tzinfo=timezone.utc) + + +class LabelFieldsTest(unittest.TestCase): + def test_the_order_number_falls_back_to_dtf_when_tiny_did_not_answer(self): + fields = label_fields(order(), None, FINISHED, 'Revisor Etiqueta') + self.assertEqual(fields['code'], 'DTF-42') + self.assertEqual(fields['qr'], 'DTF-42') + fields = label_fields(order(), '98765', FINISHED, 'Revisor Etiqueta') + self.assertEqual(fields['code'], '98765') + self.assertEqual(fields['qr'], '98765') + + def test_customer_sheets_and_billed_metres(self): + fields = label_fields(order(), '98765', FINISHED, 'Revisor Etiqueta') + self.assertEqual(fields['customer'], 'Cliente Etiqueta') + self.assertEqual(fields['sheets'], 2) + self.assertEqual(fields['metres'], '2,50') + self.assertEqual(fields['finished_at'], '11/11/2026 14:32') + self.assertEqual(fields['revisor'], 'Revisor Etiqueta') + + def test_pickup_shipping_interno_and_junto_com_a_roupa(self): + pickup = order(destination=None, freight={'service': 'pickup'}) + self.assertEqual(label_fields(pickup, None, FINISHED, None)['delivery'], 'Retirada') + self.assertEqual(label_fields(order(), None, FINISHED, None)['delivery'], + 'Envio · Jadlog .Package') + self.assertEqual(label_fields(order(kind='interno'), None, FINISHED, None)['delivery'], 'Interno') + self.assertEqual(label_fields(order(with_order='4321'), None, FINISHED, None)['delivery'], + 'Junto com pedido de roupa nº 4321') + # The internal customer's name is the one on the label. + self.assertEqual(label_fields(order(kind='interno', destination=None), None, FINISHED, None)['customer'], + 'Cliente Etiqueta') + + +class LabelHtmlTest(unittest.TestCase): + @unittest.skipUnless(HAS_SEGNO, 'segno is installed with the API image') + def test_the_page_is_sized_for_the_10x15_label(self): + fields = label_fields(order(), '98765', FINISHED, 'Revisor Etiqueta') + page = label_html(fields) + self.assertIn('@page { size: 100mm 150mm; margin: 0 }', page) + self.assertIn('98765', page) + self.assertIn('Cliente Etiqueta', page) + self.assertIn('DTF · 2 folhas · 2,50 m', page) + self.assertIn('Envio · Jadlog .Package', page) + self.assertIn('Finalizado em 11/11/2026 14:32', page) + self.assertIn('Revisor: Revisor Etiqueta', page) + self.assertIn('Loja', 'mail': 'x@example.test'}), + None, FINISHED, None) + page = label_html(fields) + self.assertIn('<b>Loja</b>', page) + self.assertNotIn('Loja', page) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_machine_log.py b/tests/test_machine_log.py index 73ce778..1e43587 100644 --- a/tests/test_machine_log.py +++ b/tests/test_machine_log.py @@ -2,8 +2,8 @@ import unittest from decimal import Decimal -from app.machine_log import (ALIGN_AFTER_FILM_METRES, CLEAN_EVERY_METRES, estimate, - one_decimal, supply_low) +from app.machine_log import (ALIGN_AFTER_FILM_METRES, CLEAN_EVERY_METRES, DEFAULT_MINIMUMS, + estimate, minimum_for, one_decimal, supply_low) class EstimateTest(unittest.TestCase): @@ -38,6 +38,22 @@ class EstimateTest(unittest.TestCase): self.assertEqual(CLEAN_EVERY_METRES, Decimal('10')) self.assertEqual(ALIGN_AFTER_FILM_METRES, Decimal('20')) + def test_a_machine_without_typed_minimums_alerts_at_dropstars_defaults(self): + # Marcus, 2026-11-10: 1 roll of film, 1 L of each ink, 5 kg of powder. + self.assertEqual(DEFAULT_MINIMUMS, {'film': Decimal('1'), 'ink_c': Decimal('1'), + 'ink_m': Decimal('1'), 'ink_y': Decimal('1'), + 'ink_k': Decimal('1'), 'ink_w': Decimal('1'), + 'powder': Decimal('5')}) + for item, default in DEFAULT_MINIMUMS.items(): + with self.subTest(item=item): + minimum = minimum_for({}, item) + self.assertEqual(minimum, default) + value = estimate([Decimal('1'), Decimal('1')], [Decimal('10')], + Decimal('9'), minimum) + self.assertTrue(supply_low(value)) + # A minimum Gestão typed still wins over the default. + self.assertEqual(minimum_for({'film': Decimal('0')}, 'film'), Decimal('0')) + class AlertTextTest(unittest.TestCase): def test_one_decimal_uses_a_comma(self): diff --git a/tests/test_moves.py b/tests/test_moves.py index f2cc637..0d0ecd5 100644 --- a/tests/test_moves.py +++ b/tests/test_moves.py @@ -1,8 +1,9 @@ """Who moves which card on the Kanban: Dropstar's flow of 2026-10-23.""" +import os import unittest from unittest import mock -from app import payments +from app import payments, tiny from app.core import auth from app.core.auth import CAPABILITIES, ROLES, may_move, may_reorder from app.runtime import BACK, STATES, TRANSITIONS @@ -55,6 +56,15 @@ class MovesTest(unittest.TestCase): self.assertEqual(CAPABILITIES['assemble'], {'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'}) + def test_the_label_is_printed_by_these_profiles(self): + # Marcus, 2026-11-10: the Revisor who releases the card, Expedição and + # Gestão; the designer, the operator and the seller do not print it. + self.assertEqual(CAPABILITIES['label'], + {'superadmin', 'admin', 'gestao', 'revisor', 'expedicao'}) + for role in ROLES: + self.assertEqual(role in CAPABILITIES['label'], + role in ('superadmin', 'admin', 'gestao', 'revisor', 'expedicao'), role) + def test_a_column_is_ordered_by_whoever_takes_its_cards_forward(self): self.assertEqual([s for s in STATES if may_reorder('operador', s)], ['tra', 'imp']) self.assertEqual([s for s in STATES if may_reorder('designer', s)], ['rec', 'cor']) @@ -78,14 +88,31 @@ class CanAnyTest(unittest.TestCase): route(None) -class InvoicedOrderTest(unittest.TestCase): - def test_an_invoiced_montador_order_is_held_out_of_tiny(self): +class MontadorPaymentTest(unittest.TestCase): + def test_a_faturado_order_goes_to_tiny_and_an_internal_one_does_not(self): self.assertEqual(payments.INVOICED_METHOD, 'faturado') - # It is not one of the Cotações "registrar" methods. + self.assertEqual(payments.INTERNAL_METHOD, 'interno') + # Neither is one of the Cotações "registrar" methods. self.assertNotIn(payments.INVOICED_METHOD, payments.OUTSIDE_METHODS) - self.assertFalse(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'faturado'}})) + self.assertNotIn(payments.INTERNAL_METHOD, payments.OUTSIDE_METHODS) + self.assertTrue(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'faturado'}})) + self.assertFalse(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'interno'}})) self.assertTrue(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'pix'}})) +class InternalNoteTest(unittest.TestCase): + payload = {'order_id': 'b6f1c0de-0000-4000-8000-000000000001', 'number': 42, + 'origin': 'atendimento', 'payment': {'method': 'faturado', 'outside': True}, + 'order': {'with_order': 4321}} + + def test_an_invoiced_order_says_how_it_is_received(self): + with mock.patch.dict(os.environ, {'TINY_RECEIPT_BOLETO': ''}): + note = tiny.internal_note(self.payload) + self.assertIn('faturado: forma de recebimento a definir', note) + self.assertIn('junto com o pedido de roupa nº 4321', note) + with mock.patch.dict(os.environ, {'TINY_RECEIPT_BOLETO': '123456'}): + self.assertIn('faturado (Boleto)', tiny.internal_note(self.payload)) + + if __name__ == '__main__': unittest.main() diff --git a/tests/test_observability.py b/tests/test_observability.py new file mode 100644 index 0000000..1cfc08d --- /dev/null +++ b/tests/test_observability.py @@ -0,0 +1,83 @@ +"""Sentry's scrubbing rules and its off switch (note Sentry).""" +import os +import unittest +from unittest import mock + +try: + import sentry_sdk +except ImportError: # pragma: no cover - the host may not have the dependency + sentry_sdk = None + +from app import observability + + +@unittest.skipUnless(sentry_sdk, 'sentry-sdk is installed with the API image') +class ScrubTest(unittest.TestCase): + def test_request_credentials_tokens_and_bodies_are_removed(self): + event = {'request': { + 'url': 'https://dtf.example/api/quotes?page=2&token=abc&X-Amz-Signature=def', + 'query_string': 'page=2&token=abc&X-Amz-Signature=def', + 'cookies': {'dtf_session': 'secret'}, + 'data': '{"customer":{"mail":"maria@example.com"}}', + 'headers': {'Cookie': 'dtf_session=secret', 'Authorization': 'Bearer x', + 'X-Auth-Token': 'x', 'X-Amz-Security-Token': 'x', + 'X-Forwarded-For': '1.2.3.4'}, + }} + observability.scrub(event) + request = event['request'] + self.assertNotIn('cookies', request) + self.assertNotIn('data', request) + self.assertEqual(request['headers'], {'X-Forwarded-For': '1.2.3.4'}) + self.assertEqual(request['query_string'], 'page=2') + self.assertEqual(request['url'], 'https://dtf.example/api/quotes?page=2') + + def test_personal_data_in_messages_exceptions_and_breadcrumbs(self): + event = { + 'message': 'Falha para maria@example.com, CPF 123.456.789-01, CNPJ 11.222.333/0001-81', + 'exception': {'values': [{'value': 'e-mail ana@example.com'}]}, + 'breadcrumbs': [ + {'message': 'GET https://x/y?token=abc', + 'data': {'url': 'https://x/y?page=1&token=abc', 'note': 'CPF 12345678901'}}, + {'message': 'CNPJ 11222333000181'}, + ], + } + observability.scrub(event) + self.assertNotIn('maria@example.com', event['message']) + self.assertNotIn('123.456.789-01', event['message']) + self.assertNotIn('11.222.333/0001-81', event['message']) + self.assertEqual(event['message'].count(observability.REDACTED), 3) + self.assertNotIn('ana@example.com', event['exception']['values'][0]['value']) + self.assertNotIn('token=abc', event['breadcrumbs'][0]['message']) + self.assertNotIn('token=abc', event['breadcrumbs'][0]['data']['url']) + self.assertNotIn('12345678901', event['breadcrumbs'][0]['data']['note']) + self.assertNotIn('11222333000181', event['breadcrumbs'][1]['message']) + + +@unittest.skipUnless(sentry_sdk, 'sentry-sdk is installed with the API image') +class InitTest(unittest.TestCase): + def test_no_dsn_does_nothing(self): + with mock.patch.dict(os.environ, {'SENTRY_DSN_API': ''}): + with mock.patch.object(sentry_sdk, 'init') as init: + self.assertFalse(observability.init('api')) + init.assert_not_called() + + def test_a_dsn_initialises_without_pii_and_scrubs(self): + env = {'SENTRY_DSN_API': 'https://key@o1.ingest.sentry.io/1', + 'SENTRY_ENVIRONMENT': 'test', 'IMAGE_TAG': 'abc123', + 'SENTRY_TRACES': '0.2'} + with mock.patch.dict(os.environ, env): + with mock.patch.object(sentry_sdk, 'init') as init, \ + mock.patch.object(sentry_sdk, 'set_tag') as set_tag: + self.assertTrue(observability.init('api')) + options = init.call_args.kwargs + self.assertEqual(options['dsn'], env['SENTRY_DSN_API']) + self.assertEqual(options['environment'], 'test') + self.assertEqual(options['release'], 'abc123') + self.assertIs(options['send_default_pii'], False) + self.assertEqual(options['traces_sample_rate'], 0.2) + self.assertIs(options['before_send'], observability.scrub) + set_tag.assert_called_once_with('component', 'api') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_pricing.py b/tests/test_pricing.py index 0cc5e8e..e74780e 100644 --- a/tests/test_pricing.py +++ b/tests/test_pricing.py @@ -34,8 +34,9 @@ class PricingTests(unittest.TestCase): def test_one_price_per_product(self): # Dropstar, 2026-10-23: textile R$ 19,90 ready sheet and R$ 21,90 loose - # art; UV R$ 79,90 and R$ 89,90. - self.assertEqual(PRICES, {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990}) + # art; UV R$ 79,90 and R$ 89,90. Premium R$ 39,90 (2026-11-10). + self.assertEqual(PRICES, {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990, + 'premium': 3990}) self.assertEqual(price('avulsa', '2.75', 90)['total_cents'], 6132) def test_the_grade_never_changes_the_price(self): @@ -132,6 +133,22 @@ class PricingTests(unittest.TestCase): with self.subTest(metres=metres): self.assertEqual(cents, band_price(PRICES['file'], bands, Decimal(metres))) + def test_ajuste_fino_band_against_actual_site_javascript(self): + # Ajuste Fino counts its band in arts: the Site helper must charge the + # same unit price as catalog.band_price. + source = Path('web/site-config.js').read_text() + body = source.split('function precoAjuste', 1)[1].split('\n}', 1)[0] + bands = [{'from_metres': 10, 'unit_cents': 690}] + js = ('const TAXA_TRATAMENTO=9.9;const FAIXAS=' + json.dumps({'tratamento': bands}) + ';' + 'function precoAjuste' + body + '\n}' + ';const results=[];for(const n of [1,9,10,12])' + 'results.push([n,Math.round(precoAjuste(n)*100)]);' + 'process.stdout.write(JSON.stringify(results));') + cases = json.loads(subprocess.check_output(['node', '-e', js], text=True)) + for arts, cents in cases: + with self.subTest(arts=arts): + self.assertEqual(cents, band_price(990, bands, Decimal(arts))) + def test_which_items_are_opened_by_hand(self): def item(kind, measurement, uid='u1'): return {'production': {'sources': [{'kind': kind, 'measurement': measurement, 'upload_id': uid}]}} diff --git a/tests/test_tiny.py b/tests/test_tiny.py index 962e43f..903f2c7 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -24,7 +24,8 @@ PAID = {'order_id': 'b6f1c0de-0000-4000-8000-000000000001', 'number': 42, 'event 'state': 'SP', 'postal_code': '14400000'}, 'total_cents': 8472}} PRODUCTS = {'TINY_PRODUCT_TEXTIL_FOLHA': '101', 'TINY_PRODUCT_TEXTIL_AVULSA': '102', - 'TINY_PRODUCT_UV_FOLHA': '103', 'TINY_PRODUCT_UV_AVULSA': '104', 'TINY_FORMA_ENVIO_RETIRADA': '77'} + 'TINY_PRODUCT_UV_FOLHA': '103', 'TINY_PRODUCT_UV_AVULSA': '104', + 'TINY_PRODUCT_TEXTIL_PREMIUM': '105', 'TINY_FORMA_ENVIO_RETIRADA': '77'} PICKUP = {**PAID, 'order': {**PAID['order'], 'destination': None, 'freight': {'service': 'pickup', 'total_cents': 0}}} READY = {'order_id': PAID['order_id'], 'number': 42, 'event': 'ready', 'reason': '', 'order': PICKUP['order']} @@ -159,8 +160,17 @@ class TinyTests(FakeTinyCase): 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']) + 'infoAdicional': 'Ajuste Fino · 1 arte · +24 h'}, pedido['itens']) self.assertNotEqual(pedido['dataPrevista'], order_payload(plain, 777, date(2026, 9, 24))['dataPrevista']) + # Per art: the quantity is the number of arts and the unit is the band price. + per_art = {'order': {**base, 'treatment': {'cents': 2070, 'hours': 24, 'arts': 3, + 'unit_cents': 690}, + 'total_cents': base['total_cents'] + 2070}, + **{k: v for k, v in PAID.items() if k != 'order'}} + with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}): + pedido = order_payload(per_art, 777, date(2026, 9, 24)) + self.assertIn({'produto': {'id': 105}, 'quantidade': 3, 'valorUnitario': 6.9, + 'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}, pedido['itens']) def test_second_delivery_finds_the_first_order(self): first = self.tiny.deliver('k1', PAID) @@ -221,7 +231,7 @@ class TinyTests(FakeTinyCase): from app.tiny import check results = check(auth=FakeAuth(), transport=httpx.MockTransport(self.handler)) self.assertEqual(set(results.values()), {'ok'}) - self.assertEqual(len(results), 7) + self.assertEqual(len(results), 8) self.assertTrue(all(method == 'GET' for method, _ in self.calls)) self.products['103']['situacao'] = 'I' with mock.patch.dict(os.environ, {'TINY_PRODUCT_UV_AVULSA': ''}): @@ -794,6 +804,9 @@ class DefaultSkuTests(unittest.TestCase): self.assertEqual(tiny.mode_codes('file'), tiny.sku_codes('DTFIMP.TX')) self.assertEqual(tiny.mode_codes('avulsa'), tiny.sku_codes('DTFIMP.TX')) self.assertEqual(tiny.mode_codes('uv'), ['DTFIMP.UV.1MT', 'DTFIMP.UV.010CM']) + # Premium's own catalogue: DTFIMP.TXP.100CM per metre and DTFIMP.TXP.0010CM to 0090CM (Marcus, 2026-11-11). + self.assertEqual(tiny.mode_codes('premium'), tiny.sku_codes('DTFIMP.TXP')) + self.assertIn('DTFIMP.TXP.0010CM', tiny.mode_codes('premium')) self.assertEqual(tiny.required_settings(), ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI']) with mock.patch.dict(os.environ, {'TINY_SKU10_UV_FOLHA': 'UV.X'}): self.assertEqual(tiny.mode_codes('uvfile'), ['UV.X']) diff --git a/tests/treatment_gate_test.py b/tests/treatment_gate_test.py index 4f34170..d264907 100644 --- a/tests/treatment_gate_test.py +++ b/tests/treatment_gate_test.py @@ -24,14 +24,14 @@ def run(): 'note': 'Gerado pelo Prumo'}, operator=True) blocked = client.call('/operator/orders/' + order['id'] + '/move', {'state': 'tra', 'version': approved['version']}, operator=True, expected=409) - assert 'Tratamento pago' in blocked['detail'], blocked + assert 'Ajuste Fino pago' in blocked['detail'], blocked prepared = upload_bytes(client, artwork(), name='LOCAL-TREATMENT-FINAL.png', order_id=order['id']) approved = client.call('/operator/orders/' + order['id'] + '/final-files', {'version': approved['version'], 'files': [{'item_index': 0, 'upload_id': prepared}], 'note': 'PNG tratado pelo designer'}, operator=True) client.call('/operator/orders/' + order['id'] + '/move', {'state': 'tra', 'version': approved['version']}, operator=True) - print('PASS: generated artwork cannot satisfy paid treatment; designer PNG opens the print queue') + print('PASS: generated artwork cannot satisfy paid Ajuste Fino; designer PNG opens the print queue') if __name__ == '__main__': diff --git a/tests/upload_limits_test.py b/tests/upload_limits_test.py new file mode 100644 index 0000000..b5285ee --- /dev/null +++ b/tests/upload_limits_test.py @@ -0,0 +1,40 @@ +"""The upload start limit: a large cart fits, and the per-source bucket +still refuses above its own limit (Marcus's bugs of 2026-11-11, B1). + +Run against the local stack: python -m tests.upload_limits_test +""" +import secrets + +from fastapi import HTTPException + +from app.api.uploads import UPLOAD_START_IP_LIMIT, UPLOAD_START_LIMIT +from app.core.auth import rate_limit +from tests.smoke_test import Client + + +def run(): + assert (UPLOAD_START_LIMIT, UPLOAD_START_IP_LIMIT) == (1000, 3000) + client = Client() + client.call('/session') + # A 66-file cart, with retries, fits in one session. Each reservation is + # cancelled so the pending-upload quota (unchanged) does not stop the test. + for index in range(70): + uid = client.call('/uploads', {'name': f'LIMIT-{index}.png', 'size': 1})['id'] + client.call(f'/uploads/{uid}', expected=200, method='DELETE') + # The per-source bucket, exercised directly with a small limit: 3000 real + # starts would only slow CI. A unique key keeps other suites out of it. + key = 'upload-start-ip-test-' + secrets.token_hex(8) + for _ in range(3): + rate_limit('upload-start-ip', key, 3, 900) + try: + rate_limit('upload-start-ip', key, 3, 900) + except HTTPException as error: + assert error.status_code == 429, error + assert error.headers.get('Retry-After') == '900', error.headers + else: + raise AssertionError('the per-source upload bucket accepted above its limit') + print('PASS: 70 upload starts in one session; the per-source bucket refuses above its limit') + + +if __name__ == '__main__': + run() diff --git a/tests/users_test.py b/tests/users_test.py index dfc6ed2..a949ac1 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -203,7 +203,7 @@ def run(): 'password': PASSWORD}) reviewer = signed_in(emails['revisor']) me = reviewer.call('/operator/me') - assert me['can'] == ['deliver', 'inspect', 'view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me + assert me['can'] == ['deliver', 'inspect', 'label', 'view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me reviewer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403) assert reviewer.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'], 'reason': ''})['state'] == 'fin' diff --git a/web/checkout.js b/web/checkout.js index 19e271a..0be9814 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -27,7 +27,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,coupon:cupomCode()}); + })),treatment:ajusteSnapshot(),coupon:cupomCode()}); } // The quote this browser is paying, forgotten. clearDraft also empties the // payment area; forgetDraft leaves on screen what is there (a confirmation). @@ -46,7 +46,18 @@ let data; try { data = text ? JSON.parse(text) : {}; } catch (_) { throw new Error(response.ok ? 'Resposta inválida do serviço.' : 'O serviço está indisponível. Tente novamente em instantes.'); } - if (!response.ok) { const error=new Error(problem(data.detail));error.status=response.status;throw error; } + if (!response.ok) { + const text=problem(data.detail); + // A validation the customer cannot read still needs to reach us (Sentry + // picks up console.error later); the customer keeps the generic sentence. + if (response.status===422 && text==='Não foi possível concluir. Confira os dados e tente de novo.') + console.error('Detalhe da validação recusada:',data.detail); + const error=new Error(text);error.status=response.status; + const retry=response.headers.get('Retry-After'); + if(retry!=null)error.retryAfter=retry; + window.dtfObservability?.apiError?.(path,response.status,error.message,data.detail); + throw error; + } return data; }; // A refusal as one sentence: the server's own, or the first field a form @@ -60,6 +71,9 @@ } const ready = api('/session'); ready.then(session=>{ + window.dtfEnvironment=session.sentry_environment||session.environment; + window.dtfRelease=session.sentry_release||undefined; + window.dtfObservability?.start?.(session.sentry_dsn_web,'site'); window.dtfUploadMaxBytes=session.max_upload_bytes; const limit=document.getElementById('zLimite'); if(limit)limit.textContent='Até '+(session.max_upload_bytes/1073741824).toFixed(0)+' GB por arquivo.'; @@ -80,9 +94,11 @@ // 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. + // Ajuste Fino (front 1a): per art, with a band by the order's number of + // arts. 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; + FAIXAS.tratamento=session.treatment_bands||[]; const tratamentoBox=document.getElementById('tratamentoBox'); if(tratamentoBox){ tratamentoBox.hidden=!(TAXA_TRATAMENTO>0); @@ -97,7 +113,8 @@ PRECO[mode]=product.unit_cents/100; FAIXAS[mode]=product.bands||[]; const card=document.querySelector('button.ec[data-modo="'+mode+'"]'); - if(card&&!product.enabled)card.hidden=true; + // Premium starts hidden in the HTML and only appears once enabled. + if(card)card.hidden=!product.enabled; } document.querySelectorAll('[data-preco]').forEach(el=>{ const product=session.products[el.dataset.preco]; @@ -115,6 +132,7 @@ } window.dtfProducts=session.products; if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha(); + if(typeof artes!=='undefined'&&artes.length&&typeof pintaArtes==='function')pintaArtes(); if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho(); if(typeof pintaTipoEnvio==='function')pintaTipoEnvio(); semPedidos=!Object.values(session.products).some(product=>product.enabled); @@ -173,8 +191,11 @@ 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))); + if(quote.treatment?.cents){ + const arts=Number(quote.treatment.arts)||0; + rows.push(linha('Ajuste Fino'+(arts?' · '+arts+(arts===1?' arte':' artes'):'')+' · +24 h', + rs(quote.treatment.cents/100))); + } if(approved.coupon) rows.push(linha('Cupom '+approved.coupon.code, '− '+rs(approved.coupon.discount_cents/100))); rows.push(linha('Total', rs(approved.total_cents/100), 'tot')); @@ -261,10 +282,35 @@ pintaEnvio(); } const arquivosDoCarrinho=()=>[...pedido.filter(it=>it.marcado!==false),...(busy&&itemAtual?[itemAtual]:[])].flatMap(it=>it.localFiles||[]); + // Every file of the paying cart must be sent (and none failed) before the + // quote and before the payment button (bugs B2 and B4, Marcus 2026-11-11). + function faltaEnvio(){ + const files=arquivosDoCarrinho(); + let pending=0,failed=0; + for(const f of files){ + const k=chaveArquivo(f); + if(falhas.has(k)){failed++;continue;} + const e=envios.get(k); + if(!e||!e.done)pending++; + } + return {total:files.length,pending,failed,falta:pending+failed}; + } + window.dtfFaltaEnvio=faltaEnvio; + function faltaEnvioMensagem(){ + const missing=[]; + for(const f of arquivosDoCarrinho()){ + const k=chaveArquivo(f),e=envios.get(k); + if(falhas.has(k)||!e||!e.done)missing.push(f); + } + if(!missing.length) return ''; + return 'Falta enviar '+missing[0].name+ + (missing.length>1?' (e mais '+(missing.length-1)+')':''); + } const gb=n=>(n/1073741824).toLocaleString('pt-BR',{maximumFractionDigits:1})+' GB'; const mb=n=>n>=1073741824 ? gb(n) : Math.round(n/1048576)+' MB'; // Where the uploads stand, and roughly how long is left from the recent speed. const amostras=[]; + let ultimaFalta=null; function estadoEnvio() { const files=arquivosDoCarrinho(); if(!files.length) return null; let total=0, sent=0, pendentes=0; @@ -291,6 +337,13 @@ return 'Enviando seus arquivos · '+restante(e); } function pintaEnvio() { + // The cart button carries the uploads too (B2): repaint it only when the + // number of missing files changes, not on every progress tick. + const falta=faltaEnvio().falta; + if(falta!==ultimaFalta){ + ultimaFalta=falta; + if(typeof pintaPedido==='function')pintaPedido(); + } window.dispatchEvent(new Event('dtf-envio')); const e=estadoEnvio(), texto=textoEnvio(e); const el=document.getElementById('envioArq'); @@ -390,6 +443,8 @@ if (!clienteOk() || !entrega.cotado) return; if (!enderecoOk()) return message('Preencha o endereço de entrega.','error'); if (!cartPodeEnviar()) return message('Revise a qualidade e confirme a ressalva de cada item antes de enviar o pedido.','error'); + const semArquivo=faltaEnvioMensagem(); + if (semArquivo) return message(semArquivo+'.','error'); const cart = itensAPagar(); if (!cart.length) return message('Adicione um item ao pedido.','error'); const initialCart=cartSnapshot(); @@ -434,7 +489,9 @@ 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; + // Ajuste Fino: true for every art, or the [item, source] pairs chosen. + const treatment=tratamentoParaItens(sheets); + if (treatment) content.treatment = treatment; 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 71a0f50..105b43f 100644 --- a/web/index.html +++ b/web/index.html @@ -75,6 +75,7 @@ h1 em{font-style:normal;color:var(--laranja)} .escolha{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-top:24px; align-items:stretch} .escolha .ec{display:flex;flex-direction:column} +.escolha .ec[hidden]{display:none} .escolha .ec .in{flex:1} @media(max-width:1000px){.escolha{grid-template-columns:repeat(2,1fr)}} @media(max-width:600px){.escolha{grid-template-columns:1fr}} @@ -640,6 +641,8 @@ h2 em{font-style:normal;color:var(--laranja)} @media(prefers-reduced-motion:reduce){*{transition:none!important;scroll-behavior:auto}} + + @@ -815,6 +818,15 @@ h2 em{font-style:normal;color:var(--laranja)} Enviar artes de UV + @@ -1111,9 +1123,9 @@ h2 em{font-style:normal;color:var(--laranja)} diff --git a/web/kanban-label.js b/web/kanban-label.js new file mode 100644 index 0000000..08a5ebb --- /dev/null +++ b/web/kanban-label.js @@ -0,0 +1,147 @@ +/* Kanban DTF — the 10x15 cm label at Finalizado (Fase 2, front 10). + + Marcus, 2026-11-10: when a card reaches Finalizado the Kanban prints a Zebra + ZD220 label by itself. The server renders the page (app/label.py), so this + file only decides which computer prints it: the first to claim it prints it + once, and whoever may see labels can reprint. The browser opts in here, in + Integrações, and only orders that reach Finalizado after that moment are + printed automatically, never the whole history. */ + +const LABEL_SINCE = 'label-print-since'; +const LABEL_ASKED = new Set(); // claimed from this browser in this session +const LABEL_BUSY = new Set(); // a claim in flight, so two loads do not repeat it + +function labelSince() { + try { + const value = localStorage.getItem(LABEL_SINCE); + const date = value ? new Date(value) : null; + return date && !Number.isNaN(date.getTime()) ? date : null; + } catch (error) { + return null; + } +} + +function labelSetSince(on) { + try { + if (on) localStorage.setItem(LABEL_SINCE, new Date().toISOString()); + else localStorage.removeItem(LABEL_SINCE); + } catch (error) { + // A browser that cannot store it simply never prints automatically. + } +} + +function labelEnabled() { + return !!labelSince(); +} + +// The label page is rendered by the server; this prints what it returns. +async function labelPrint(orderId) { + const response = await fetch('/api/operator/orders/' + encodeURIComponent(orderId) + '/label', + {credentials: 'same-origin', cache: 'no-store'}); + if (!response.ok) throw new Error('Não foi possível abrir a etiqueta (' + response.status + ').'); + const page = await response.text(); + await new Promise((resolve, reject) => { + const frame = document.createElement('iframe'); + frame.setAttribute('aria-hidden', 'true'); + frame.tabIndex = -1; + frame.style.cssText = 'position:fixed;left:-10000px;top:0;width:100mm;height:150mm;border:0'; + let closed = false; + const done = () => { + if (closed) return; + closed = true; + frame.remove(); + resolve(); + }; + frame.addEventListener('load', () => { + try { + const view = frame.contentWindow; + view.addEventListener('afterprint', done, {once: true}); + // A browser that never fires afterprint still releases the frame. + setTimeout(done, 120000); + view.focus(); + view.print(); + } catch (error) { + done(); + reject(error); + } + }, {once: true}); + // The gateway adds X-Frame-Options: DENY and frame-ancestors 'none' to + // /api responses, so the label URL cannot be framed directly. The page is + // still the server's: it is fetched and written into a srcdoc iframe, + // which is not a framed navigation and inherits this page's policy. + frame.srcdoc = page; + document.body.append(frame); + }); +} + +function labelReprintButton(order, className = 'btn lg') { + if (!may('label') || order.state !== 'fin' || order.cancelled_at) return null; + const print = button('Reimprimir etiqueta', async () => { + try { + await api('/orders/' + order.id + '/label/reprint', {}); + await labelPrint(order.id); + say('Etiqueta do pedido #' + order.number + ' enviada para a impressora.'); + } catch (error) { + say(error.message, true); + } + }, className); + print.prepend(svgIcon(IC.printer, 'i m')); + return print; +} + +// After every board load: claim the labels of the orders that reached +// Finalizado after this browser opted in. Only one computer gets print:true. +async function labelAfterLoad() { + if (!may('label') || !labelEnabled() || !board) return; + const since = labelSince(); + for (const order of board.orders) { + if (order.state !== 'fin' || order.cancelled_at || !order.finished_at) continue; + if (new Date(order.finished_at) <= since) continue; + if (LABEL_ASKED.has(order.id) || LABEL_BUSY.has(order.id)) continue; + LABEL_BUSY.add(order.id); + try { + const answer = await api('/orders/' + order.id + '/label/claim', {}); + LABEL_ASKED.add(order.id); + if (answer.print) { + try { + await labelPrint(order.id); + } catch (error) { + say('Etiqueta do pedido #' + order.number + ': ' + error.message, true); + } + } + } catch (error) { + // The claim did not answer: not marked, so the next board load retries it. + } finally { + LABEL_BUSY.delete(order.id); + } + } +} + +// The Integrações row: the switch that makes this browser the label printer. +function labelIntegrationRow() { + if (!may('label')) return null; + const on = labelEnabled(); + const input = node('input'); + const toggle = checkbox('Esta tela imprime as etiquetas', input); + input.checked = on; + input.onchange = () => { + labelSetSince(input.checked); + say(input.checked + ? 'Etiqueta ligada: os pedidos que chegarem em Finalizado daqui em diante serão impressos.' + : 'Etiqueta desligada nesta tela.'); + renderIntegrations(); + }; + const since = labelSince(); + return integration({ + name: 'Etiqueta 10×15', state: on ? 'Ligada' : 'Desligada', tone: on ? 'ok' : 'off', + summary: on ? 'Esta tela imprime as etiquetas de pedidos que chegam em Finalizado.' + : 'Esta tela não imprime etiquetas.', + actions: [toggle], + details: [ + node('p', 'A etiqueta é impressa uma vez, no primeiro computador que a pegar; os outros não a imprimem de novo. ' + + 'O Revisor e a Expedição também podem reimprimir pelo card do pedido em Finalizado.'), + node('p', 'Para imprimir sem a janela de confirmação, abra o Chrome com --kiosk-printing e deixe a Zebra ZD220 como impressora padrão.'), + ...(since ? [['Ligada desde', when(since.toISOString())]] : []) + ] + }); +} diff --git a/web/kanban-montador.js b/web/kanban-montador.js index 9ab4e73..d6c44c2 100644 --- a/web/kanban-montador.js +++ b/web/kanban-montador.js @@ -1,20 +1,239 @@ /* Kanban DTF: "Montar folha" (Fase 2, front 7). The stamps are the PNG files in Estampas/ inside the folder chosen in Integrações; the sizes are the table Gestão edits. The packing is the Site's own engine (web/packing.js). - Montar, which creates the card, is slice 2b. Uses the globals of kanban.js - and packing.js, loaded first. */ + Montar creates the card: Interno for the Expedição, Venda for a customer + picked from Tiny (front 7a.3). Uses the globals of kanban.js and packing.js, + loaded first. */ const MONTAR_CODE=/^[A-Za-z0-9_-]{1,40}$/; // The Site's ruler (web/site-config.js): the same numbers, copied there too. const MONTAR_DPI_REFUSE=96, MONTAR_DPI_WARN=200; const MONTAR_FILM_CM=57, MONTAR_GAP_CM=0.5; const MONTAR={sizes:[],lines:[],seq:0,preview:null,timer:null,dirty:false,token:0, - layout:null,layoutTimer:null,layoutToken:0,layoutPending:false,creating:false,requestKey:null}; + layout:null,layoutTimer:null,layoutToken:0,layoutPending:false,creating:false,requestKey:null, + kind:null,internal:null,internalDirty:false,brands:new Map(),contactToken:0,contactTimer:null, + freights:null,freight:null,catalog:null}; const montarFolderReady=()=>!!FOLDER.handle&&!!FOLDER.granted; const montarDpi=found=>found.width/(found.widthCm/2.54); const montarHeight=found=>found.widthCm*(found.height/found.width); const montarSelected=()=>MONTAR.sizes.find(size=>size.letter===$('montar-size').value)||null; +// ---- Interno or Venda ------------------------------------------------------ +// Marcus's answers of 2026-11-10 (front 7a.3): the Expedição only makes +// Interno orders, the Vendedor only Venda, and Gestão and the administrators +// both. An Interno order uses the fixed internal customer; a Venda one is +// picked from Tiny. +const montarKindNames=()=>ME?.role==='expedicao'?['interno']:ME?.role==='vendedor'?['venda']:['interno','venda']; +const montarInternalField=key=>String(MONTAR.internal?.[key]||''); +const montarInternalReady=()=>!!MONTAR.internal&&['name','cnpj','zap','mail'].every(key=>montarInternalField(key).trim()); +function montarPaintKind(){ + const kinds=montarKindNames(); + if(!MONTAR.kind||!kinds.includes(MONTAR.kind))MONTAR.kind=kinds.length===1?kinds[0]:'venda'; + if(MONTAR.kind==='interno'&&!montarInternalReady()&&kinds.length>1){ + MONTAR.kind='venda'; + for(const id of ['montar-name','montar-doc','montar-zap','montar-mail'])$(id).value=''; + } + const box=$('montar-kind'); + $('montar-kind-hint').textContent=kinds.length===1 + ?(MONTAR.kind==='interno'?'Interno, para a Expedição.':'Venda, para o Vendedor.') + :'Interno para a Expedição; Venda para um cliente do Tiny.'; + box.hidden=kinds.length<2; + box.replaceChildren(...kinds.map(kind=>{ + const b=node('button',kind==='interno'?'Interno':'Venda',kind===MONTAR.kind?'on':'');b.type='button'; + b.setAttribute('aria-pressed',String(kind===MONTAR.kind)); + b.disabled=kind==='interno'&&!montarInternalReady(); + b.title=b.disabled?'Peça à Gestão para completar o cliente interno.':''; + b.onclick=()=>montarSetKind(kind); + return b; + })); + $('montar-interno-missing').hidden=montarInternalReady(); +} +function montarSetKind(kind){ + if(MONTAR.kind===kind)return; + MONTAR.kind=kind; + montarClearCustomer(); + montarPaintKind();montarPaintCustomer();montarPaintActions(); +} +function montarPaintCustomer(){ + const interno=MONTAR.kind==='interno'; + $('montar-customer-title').textContent=interno?'Cliente interno':'Cliente'; + $('montar-customer-search').hidden=interno; + $('montar-interno-note').hidden=!interno; + $('montar-delivery').hidden=interno; + for(const [id,key] of [['montar-name','name'],['montar-doc','cnpj'],['montar-zap','zap'],['montar-mail','mail']]){ + $(id).disabled=interno; + if(interno)$(id).value=montarInternalField(key); + } +} +const montarDelivery=()=>document.querySelector('input[name="montar-delivery"]:checked')?.value||'pickup'; +function montarPaintDelivery(){ + const delivery=montarDelivery(),withOrder=delivery==='with_order',ship=delivery==='ship'; + $('montar-with-order').disabled=!withOrder; + if(!withOrder)$('montar-with-order').value=''; + $('montar-shipping').hidden=!ship; + if(ship&&!$('montar-ship-recipient').value.trim()) + $('montar-ship-recipient').value=$('montar-name').value.trim(); + montarPaintFreights(); +} +function montarWithOrder(){ + if(MONTAR.kind!=='venda'||montarDelivery()!=='with_order')return null; + const value=Math.round(Number($('montar-with-order').value)); + return Number.isInteger(value)&&value>=1&&value<=999999?value:null; +} +// ---- Envio (front 7a.4): the Site's own freight --------------------------- +// The Site's public routes for the CEP and the carrier quotes (app/api/health.py); +// the Kanban's api() helper only reaches /api/operator. +// The Site's UFS list (web/site-config.js), copied for the address select. +const MONTAR_UFS='AC AL AP AM BA CE DF ES GO MA MT MS MG PA PB PR PE PI RJ RN RS RO RR SC SP SE TO'.split(' '); +const montarCep=()=>$('montar-ship-cep').value.replace(/\D/g,'').slice(0,8); +function montarDestination(){ + const destination={recipient:$('montar-ship-recipient').value.trim(), + street:$('montar-ship-street').value.trim(),number:$('montar-ship-number').value.trim(), + complement:$('montar-ship-complement').value.trim(), + district:$('montar-ship-district').value.trim(),city:$('montar-ship-city').value.trim(), + state:$('montar-ship-state').value.trim().toUpperCase(),postal_code:montarCep()}; + const ok=destination.postal_code.length===8&&destination.recipient.length>=2&& + destination.street.length>=2&&destination.number.length>=1&& + destination.district.length>=2&&destination.city.length>=2&&MONTAR_UFS.includes(destination.state); + return ok?destination:null; +} +const montarShipReady=()=>montarDelivery()==='ship'&&!!montarDestination()&& + !!MONTAR.freight&&MONTAR.freight.postal_code===montarCep(); +function montarResetFreight(){ + MONTAR.freights=null;MONTAR.freight=null; + $('montar-freights').replaceChildren();$('montar-freights').hidden=true; + $('montar-freight-msg').textContent=''; +} +async function montarPublic(path,options={}){ + const response=await fetch('/api'+path,options); + const data=await response.json().catch(()=>({})); + if(!response.ok)throw new Error(typeof data.detail==='string'?data.detail:'Não foi possível agora ('+response.status+').'); + return data; +} +async function montarCepLookup(){ + const msg=$('montar-ship-msg'),cep=montarCep(); + if(cep.length!==8){msg.textContent='Informe um CEP com oito dígitos.';return;} + msg.textContent='Buscando o endereço…'; + try{ + const address=await montarPublic('/cep/'+cep); + $('montar-ship-street').value=address.street||''; + $('montar-ship-district').value=address.district||''; + $('montar-ship-city').value=address.city||''; + if(MONTAR_UFS.includes(address.state))$('montar-ship-state').value=address.state; + if(!$('montar-ship-recipient').value.trim())$('montar-ship-recipient').value=$('montar-name').value.trim(); + msg.textContent='';MONTAR.requestKey=null;montarPaintActions(); + }catch(e){msg.textContent=e.message;} +} +// The item's packed metres and the table value of the items, as the server +// will price them: the band price of the loose-art mode on the billed metres. +function montarQuoteFigures(lines){ + const heights=montarGroups(lines).map(group=>{ + const cargas=[]; + group.sources.forEach((source,sourceIndex)=>{ + for(let copyIndex=0;copyIndexMath.max(1,Math.ceil(metres*10)/10)); + const total=+billed.reduce((sum,metres)=>sum+metres,0).toFixed(2); + let unit=catalog.unit_cents,best=null; + for(const band of catalog.bands||[]){ + const from=Number(band.from_metres); + if(total>=from&&(best===null||from>=best)){best=from;unit=band.unit_cents;} + } + return {metres:+heights.reduce((sum,metres)=>sum+metres,0).toFixed(4), + cents:billed.reduce((sum,metres)=>sum+Math.floor(Number((metres*unit).toFixed(6))),0)}; +} +async function montarCatalog(){ + if(MONTAR.catalog)return MONTAR.catalog; + const session=await montarPublic('/session'); + MONTAR.catalog=session.products||null; + return MONTAR.catalog; +} +async function montarFreightQuote(){ + const msg=$('montar-freight-msg'),cep=montarCep(); + if(cep.length!==8){msg.textContent='Informe o CEP de entrega primeiro.';return;} + if(!MONTAR.lines.length||!MONTAR.layout||MONTAR.layoutPending){ + msg.textContent='Monte a folha antes de cotar o frete.';return; + } + msg.textContent='Cotando o frete…'; + const token=MONTAR.layoutToken; + try{ + await montarCatalog(); + if(token!==MONTAR.layoutToken||montarCep()!==cep)return; + const figures=montarQuoteFigures([...MONTAR.lines]); + const result=await montarPublic('/freight/options',{method:'POST', + headers:{'Content-Type':'application/json'}, + body:JSON.stringify({postal_code:cep,metres:figures.metres,declared_cents:figures.cents})}); + if(token!==MONTAR.layoutToken||montarCep()!==cep)return; + MONTAR.freights=result.options||[]; + MONTAR.freight=MONTAR.freights.length?{...MONTAR.freights[0],postal_code:cep}:null; + MONTAR.requestKey=null; + msg.textContent='';montarPaintFreights();montarPaintActions(); + }catch(e){ + if(token!==MONTAR.layoutToken||montarCep()!==cep)return; + MONTAR.freights=null;MONTAR.freight=null; + $('montar-freights').replaceChildren();$('montar-freights').hidden=true; + msg.textContent=e.message;montarPaintActions(); + } +} +function montarPaintFreights(){ + const box=$('montar-freights'),options=MONTAR.freights||[]; + box.hidden=!options.length; + box.replaceChildren(...options.map(option=>{ + const label=node('label',undefined,'montar-freight'); + const radio=node('input');radio.type='radio';radio.name='montar-freight';radio.value=option.service; + radio.checked=!!MONTAR.freight&&option.service===MONTAR.freight.service; + radio.onchange=()=>{ + MONTAR.freight={...option,postal_code:montarCep()};MONTAR.requestKey=null;montarPaintActions(); + }; + const meta=node('span',undefined,'montar-freight-meta'); + meta.append(node('b',option.description||option.service), + node('span',option.days?'até '+option.days+' dias úteis':'','sub'), + node('em',money(option.total_cents))); + label.append(radio,meta); + return label; + })); +} +// The brand of a stamp, recorded for the future catalogue (Marcus, 10/11): +// only Gestão edits it; everyone who assembles reads it. +async function montarStampBrand(code){ + if(MONTAR.brands.has(code))return MONTAR.brands.get(code); + const stamp=await api('/stamps/'+encodeURIComponent(code)); + MONTAR.brands.set(code,stamp); + return stamp; +} +function montarBrandRow(code,stamp){ + const current=stamp||{brand:'',public:false}; + const row=node('div',undefined,'montar-brand'); + row.append(node('span','Marca','lbl')); + if(!may('manage')){ + row.append(node('b',current.brand||'—'),node('span',current.public?'Pública':'Não pública','lbl')); + return row; + } + const brand=node('input',undefined,'montar-brandinput'); + brand.value=current.brand||'';brand.maxLength=120;brand.autocomplete='off';brand.spellcheck=false; + brand.setAttribute('aria-label','Marca da estampa '+code); + const pub=node('label',undefined,'montar-public'); + const check=node('input');check.type='checkbox';check.checked=!!current.public; + pub.append(check,'Pública'); + const save=node('button','Salvar marca','btn');save.type='button'; + save.onclick=async()=>{ + save.disabled=true; + try{ + await api('/stamps/'+encodeURIComponent(code),{brand:brand.value.trim(),public:check.checked}); + MONTAR.brands.set(code,{code,brand:brand.value.trim(),public:check.checked}); + say('Marca salva.'); + }catch(e){say(e.message,true);}finally{save.disabled=false;} + }; + row.append(brand,pub,save); + return row; +} + // Without the folder there is no Estampas/ to read: only the size table works. function montarPaintFolder(){ const ok=montarFolderReady(); @@ -59,14 +278,16 @@ function montarDropPreview(){ if(MONTAR.preview)URL.revokeObjectURL(MONTAR.preview.url); MONTAR.preview=null; } -function montarPaintPreview(found){ +function montarPaintPreview(found,stamp){ montarDropPreview(); MONTAR.preview=found; const words=node('span',undefined,'montar-stampinfo'); words.append(node('b',found.code), node('span',cm(found.widthCm)+' cm de largura · '+cm(montarHeight(found))+' cm de altura · '+Math.floor(montarDpi(found))+' DPI')); const img=node('img');img.src=found.url;img.alt='Estampa '+found.code; - const wrap=node('div',undefined,'montar-stamp');wrap.append(img,words); + const body=node('div',undefined,'montar-stampbody'); + body.append(words,montarBrandRow(found.code,stamp)); + const wrap=node('div',undefined,'montar-stamp');wrap.append(img,body); $('montar-preview').replaceChildren(wrap); } function montarPaintNotFound(){ @@ -88,7 +309,12 @@ async function montarPreview(){ try{found=await montarRead(code,size);} catch(e){if(token===MONTAR.token&&!montarFolderError(e))say(e.message,true);return;} if(token!==MONTAR.token){if(found)URL.revokeObjectURL(found.url);return;} - if(found)montarPaintPreview(found);else montarPaintNotFound(); + if(found){ + let stamp=null; + try{stamp=await montarStampBrand(code);}catch(e){stamp={code,brand:'',public:false};} + if(token!==MONTAR.token){URL.revokeObjectURL(found.url);return;} + montarPaintPreview(found,stamp); + }else montarPaintNotFound(); } function montarQueuePreview(){ clearTimeout(MONTAR.timer); @@ -129,6 +355,7 @@ function montarChanged(){ MONTAR.layout=null; MONTAR.layoutPending=true; MONTAR.requestKey=null; + montarResetFreight(); montarPaintLines(); if(!MONTAR.lines.length)montarDrawPreview(null); clearTimeout(MONTAR.layoutTimer); @@ -198,15 +425,32 @@ function montarCustomer(){ const montarCustomerFilled=()=>MONTAR_CUSTOMER.every(id=>$(id).value.trim()); function montarClearCustomer(){ for(const id of MONTAR_CUSTOMER)$(id).value=''; + $('montar-customer-q').value=''; + $('montar-customer-hits').hidden=true; + for(const id of ['montar-ship-cep','montar-ship-recipient','montar-ship-street','montar-ship-number', + 'montar-ship-complement','montar-ship-district','montar-ship-city','montar-ship-state']) + $(id).value=''; + $('montar-ship-msg').textContent=''; + montarResetFreight(); + document.querySelector('input[name="montar-delivery"][value="pickup"]').checked=true; + montarPaintDelivery(); MONTAR.requestKey=null; } -// Montar is the real thing now: a sheet, its layout and the customer. +// Montar is the real thing now: a sheet, its layout and the customer, which +// Interno reads from the database and Venda from Tiny. function montarPaintActions(){ const build=$('montar-build'); + const customerReady=MONTAR.kind==='interno'?montarInternalReady():montarCustomerFilled(); + const deliveryReady=MONTAR.kind!=='venda'||montarDelivery()!=='ship'||montarShipReady(); const ready=!!(MONTAR.lines.length&&MONTAR.layout&&!MONTAR.layoutPending&& - montarCustomerFilled()&&!MONTAR.creating); + customerReady&&deliveryReady&&!MONTAR.creating); build.disabled=!ready; - build.title=ready?'':(MONTAR.lines.length?'Aguarde a montagem e preencha o cliente.':'Monte a folha primeiro.'); + build.title=ready?'':(!MONTAR.lines.length?'Monte a folha primeiro.' + :(MONTAR.layoutPending||!MONTAR.layout)?'Aguarde a montagem da folha.' + :MONTAR.kind==='interno'?'Peça à Gestão para completar o cliente interno.' + :!customerReady?'Preencha os dados do cliente.' + :!deliveryReady?(!montarDestination()?'Preencha o endereço de entrega.':'Cote o frete e escolha uma opção.') + :''); } // The Site's grade for loose art (web/site-quality.js): each stamp's DPI over // the ideal 200, from 6 to 100; the item's is the average of its stamps'. @@ -234,13 +478,11 @@ function montarItem(sources){ } // 20 sources and 4000 copies per item; a stamp above 200 copies becomes // several sources of the same upload, 200 each; items in list order. -function montarItems(lines,uploads){ +function montarGroups(lines){ const pool=[]; - for(const line of lines){ - const uploadId=uploads.get(line.id); + for(const line of lines) for(let left=line.qty;left>0;left-=200) - pool.push({line,uploadId,copies:Math.min(200,left)}); - } + pool.push({line,copies:Math.min(200,left)}); const groups=[];let current=null; for(const source of pool){ if(!current||current.sources.length>=20||current.copies+source.copies>4000){ @@ -248,17 +490,41 @@ function montarItems(lines,uploads){ } current.sources.push(source);current.copies+=source.copies; } - return groups.map(group=>montarItem(group.sources)); + return groups; +} +function montarItems(lines,uploads){ + return montarGroups(lines).map(group=>montarItem(group.sources.map(source=> + ({...source,uploadId:uploads.get(source.line.id)})))); } async function montarCreate(){ if(MONTAR.creating)return; - const customer=montarCustomer(); - if(!montarCustomerFilled())return say('Preencha os dados do cliente.',true); + const kind=MONTAR.kind||'venda'; + let customer=null,name=''; + if(kind==='interno'){ + if(!montarInternalReady())return say('Peça à Gestão para completar o cliente interno.',true); + name=montarInternalField('name'); + }else{ + customer=montarCustomer(); + if(!montarCustomerFilled())return say('Preencha os dados do cliente.',true); + name=customer.name; + } + let withOrder=null,deliveryFreight=null,destination=null; + if(kind==='venda'&&montarDelivery()==='with_order'){ + withOrder=montarWithOrder(); + if(!withOrder)return say('Informe o número do pedido de roupa.',true); + } + if(kind==='venda'&&montarDelivery()==='ship'){ + destination=montarDestination(); + if(!destination)return say('Preencha o endereço de entrega.',true); + if(!MONTAR.freight)return say('Cote o frete e escolha uma opção.',true); + if(MONTAR.freight.postal_code!==montarCep())return say('Cote o frete de novo para este CEP.',true); + deliveryFreight={service:MONTAR.freight.service,postal_code:montarCep()}; + } if(!MONTAR.lines.length)return say('Monte a folha primeiro.',true); if(!MONTAR.layout||MONTAR.layoutPending)return say('A montagem ainda está sendo calculada.',true); const lines=[...MONTAR.lines]; if(!await ask('Criar pedido','Criar o pedido com '+plural(lines.reduce((t,line)=>t+line.qty,0),'estampa','estampas')+ - ', '+metres(MONTAR.layout.altura/100)+', para '+customer.name+'?','Criar pedido'))return; + ', '+metres(MONTAR.layout.altura/100)+', para '+name+'?','Criar pedido'))return; MONTAR.creating=true;montarPaintActions(); try{ const uploads=new Map(); @@ -271,11 +537,18 @@ async function montarCreate(){ } say('Criando o pedido…'); if(!MONTAR.requestKey)MONTAR.requestKey=crypto.randomUUID(); - const order=await api('/montador/orders',{request_key:MONTAR.requestKey, - customer,items:montarItems(lines,uploads)}); + const body={request_key:MONTAR.requestKey,kind,items:montarItems(lines,uploads)}; + if(kind==='venda'){ + body.customer=customer; + if(withOrder)body.with_order=withOrder; + if(deliveryFreight)body.freight=deliveryFreight; + if(destination)body.destination=destination; + } + const order=await api('/montador/orders',body); MONTAR.requestKey=null; montarClear(); montarClearCustomer(); + montarPaintCustomer(); say('Pedido #'+order.number+' criado em Arte recebida.',false,10000); load(true).catch(()=>{}); }catch(e){say(e.message,true);} @@ -328,7 +601,9 @@ async function montarAdd(){ try{found=await montarRead(code,size);} catch(e){if(!montarFolderError(e))say(e.message,true);return;} if(!found){montarPaintNotFound();return say('Código não existe em Estampas/.',true);} - montarPaintPreview(found); + let stamp=null; + try{stamp=await montarStampBrand(code);}catch(e){stamp={code,brand:'',public:false};} + montarPaintPreview(found,stamp); if(found.widthCm>56)return say('A estampa tem '+cm(found.widthCm)+' cm de largura: o máximo é 56 cm.',true); const dpi=montarDpi(found); if(dpicustomer[key]))return say('Preencha todos os campos do cliente interno.',true); + await api('/internal-customer',customer); + MONTAR.internalDirty=false; + say('Cliente interno salvo.'); + await montarLoadInternal(true); +} +// The Venda customer comes from Tiny's contacts, by name or CPF/CNPJ. +async function montarSearchContacts(){ + const token=++MONTAR.contactToken,q=$('montar-customer-q').value.trim(),hits=$('montar-customer-hits'); + if(q.length<2){hits.hidden=true;hits.replaceChildren();return;} + let contacts; + try{contacts=await api('/tiny/contacts?q='+encodeURIComponent(q));} + catch(e){ + if(token!==MONTAR.contactToken)return; + hits.replaceChildren(node('p',e.message,'montar-hint'));hits.hidden=false;return; + } + if(token!==MONTAR.contactToken)return; + if(!contacts.length){hits.replaceChildren(node('p','Nenhum contato no Tiny.','montar-hint'));hits.hidden=false;return;} + hits.replaceChildren(...contacts.map(contact=>{ + const hit=node('button',undefined,'montar-hit');hit.type='button';hit.setAttribute('role','option'); + hit.append(node('b',contact.name||contact.document||'Contato'), + node('span',[contact.document,contact.email,contact.phone].filter(Boolean).join(' · '),'sub')); + hit.onclick=()=>montarPickContact(contact); + return hit; + })); + hits.hidden=false; +} +function montarQueueContacts(){ + clearTimeout(MONTAR.contactTimer); + MONTAR.contactTimer=setTimeout(()=>montarSearchContacts().catch(e=>say(e.message,true)),300); +} +function montarPickContact(contact){ + const previous=$('montar-name').value.trim(); + $('montar-name').value=contact.name||''; + $('montar-doc').value=contact.document||''; + $('montar-zap').value=contact.phone||''; + $('montar-mail').value=contact.email||''; + $('montar-customer-q').value=contact.name||contact.document||''; + $('montar-customer-hits').hidden=true; + const recipient=$('montar-ship-recipient').value.trim(); + if(montarDelivery()==='ship'&&(!recipient||recipient===previous)) + $('montar-ship-recipient').value=contact.name||''; + MONTAR.requestKey=null; + montarPaintActions(); + const missing=MONTAR_CUSTOMER.find(id=>!$(id).value.trim()); + if(missing)$(missing).focus(); +} async function loadMontador(){ montarPaintFolder(); - try{await montarLoadSizes(false);} + // Paint the chosen kind and customer before the fetch answers: an Expedição + // never sees an editable customer field, not even for a moment. + montarPaintKind();montarPaintCustomer(); + try{await Promise.all([montarLoadSizes(false),montarLoadInternal(false)]);} catch(e){say(e.message,true);return;} if(montarFolderReady()){ if($('montar-code').value.trim()){if(!MONTAR.preview)montarQueuePreview();} @@ -433,3 +779,45 @@ $('montar-size-save').onclick=async()=>{ $('montar-size-save').disabled=true; try{await montarSaveSizes();}catch(e){say(e.message,true);}finally{$('montar-size-save').disabled=false;} }; +for(const id of ['montar-interno-name','montar-interno-doc','montar-interno-zap','montar-interno-mail']) + $(id).addEventListener('input',()=>{MONTAR.internalDirty=true;}); +$('montar-interno-save').onclick=async()=>{ + $('montar-interno-save').disabled=true; + try{await montarSaveInternal();}catch(e){say(e.message,true);}finally{$('montar-interno-save').disabled=false;} +}; +$('montar-customer-q').addEventListener('input',montarQueueContacts); +$('montar-customer-q').addEventListener('focus',()=>{if($('montar-customer-hits').children.length)$('montar-customer-hits').hidden=false;}); +$('montar-with-order').addEventListener('focus',()=>{ + document.querySelector('input[name="montar-delivery"][value="with_order"]').checked=true; + montarPaintDelivery(); +}); +$('montar-with-order').addEventListener('input',()=>{MONTAR.requestKey=null;}); +for(const radio of document.querySelectorAll('input[name="montar-delivery"]')) + radio.addEventListener('change',()=>{MONTAR.requestKey=null;montarPaintDelivery();montarPaintActions();}); +$('montar-ship-cep').addEventListener('input',()=>{ + const digits=$('montar-ship-cep').value.replace(/\D/g,'').slice(0,8); + $('montar-ship-cep').value=digits.length>5?digits.slice(0,5)+'-'+digits.slice(5):digits; + MONTAR.requestKey=null;montarResetFreight();montarPaintActions(); +}); +$('montar-cep-find').onclick=async()=>{ + $('montar-cep-find').disabled=true; + try{await montarCepLookup();}catch(e){say(e.message,true);} + finally{$('montar-cep-find').disabled=false;} +}; +$('montar-freight-quote').onclick=async()=>{ + $('montar-freight-quote').disabled=true; + try{await montarFreightQuote();}catch(e){say(e.message,true);} + finally{$('montar-freight-quote').disabled=false;} +}; +for(const id of ['montar-ship-recipient','montar-ship-street','montar-ship-number', + 'montar-ship-complement','montar-ship-district','montar-ship-city']) + $(id).addEventListener('input',()=>{MONTAR.requestKey=null;montarPaintActions();}); +$('montar-ship-state').addEventListener('change',()=>{MONTAR.requestKey=null;montarPaintActions();}); +document.addEventListener('click',event=>{ + if(!event.target.closest('.montar-customer-search'))$('montar-customer-hits').hidden=true; +}); +const montarUfPlaceholder=node('option','UF');montarUfPlaceholder.value=''; +$('montar-ship-state').append(montarUfPlaceholder,...MONTAR_UFS.map(uf=>{ + const option=node('option',uf);option.value=uf;return option; +})); +montarPaintDelivery(); diff --git a/web/kanban-numbers.js b/web/kanban-numbers.js index 6964d11..994919c 100644 --- a/web/kanban-numbers.js +++ b/web/kanban-numbers.js @@ -181,14 +181,17 @@ async function loadStats(){ const mk=(label,value,unit)=>{const k=node('div',undefined,'mk');const b=node('b',value);if(unit)b.append(node('small',unit));k.append(node('span',label),b);return k;}; const pct=n=>data.orders?Math.round(100*n/data.orders)+'%':''; const [reais,centavos]=money(data.cents).split(','); + // The ticket is the cash received over the cash orders only: an Interno or + // faturado order records the table price, not money received (front 7a.3). + const cashOrders=Math.max(0,Number(data.orders)-(data.price_table||[]).reduce((sum,row)=>sum+(row.orders||0),0)); const hero=node('div',undefined,'hero'); hero.append(hk('Metros vendidos',metres(data.metres).replace(' m',''),'m',plural(data.orders,'pedido pago','pedidos pagos')), - hk('Recebido, com frete',reais,','+centavos,data.orders?'ticket médio de '+money(Math.round(data.cents/data.orders)):''), + hk('Recebido, com frete',reais,','+centavos,cashOrders?'ticket médio de '+money(Math.round(data.cents/cashOrders)):''), hk('Do pagamento ao Finalizado',duration(data.lead.median_hours),'',data.lead.orders?'mediana de '+plural(data.lead.orders,'pedido','pedidos')+', sem o tempo em Aguardando contato':'nenhum finalizado no período')); const rw=data.rework, share=v=>v==null?'—':String(v).replace('.',',')+'%'; const minis=node('div',undefined,'minis'); minis.append(mk('Pedidos pagos',String(data.orders)), - mk('Ticket médio',data.orders?money(Math.round(data.cents/data.orders)):'—'), + mk('Ticket médio',cashOrders?money(Math.round(data.cents/cashOrders)):'—'), mk('Com correção',String(data.corrected),pct(data.corrected)), mk('Artes tratadas',String(data.treated.orders),pct(data.treated.orders)), mk('Retrabalho da casa',share(rw.house.percent),'meta '+share(rw.house.goal_percent)), @@ -211,6 +214,12 @@ async function loadStats(){ tr.append(node('td',ORIGINS[o.origin]),node('td',String(o.orders),'r'),node('td',metres(o.metres).replace(' m',''),'r'),node('td',money(o.cents),'r'), node('td',o.finished?duration(o.median_hours):'—','r')); if(!o.orders)tr.classList.add('off');return tr;})); + // The montador's table price, apart from the money received (front 7a.3). + const priceNames={faturado:'Faturado',interno:'Interno'}; + $('stats-price-table').replaceChildren(...(data.price_table||[]).map(p=>{const tr=node('tr'); + tr.append(node('td',priceNames[p.method]||p.method),node('td',String(p.orders),'r'), + node('td',metres(p.metres).replace(' m',''),'r'),node('td',money(p.cents),'r')); + if(!p.orders)tr.classList.add('off');return tr;})); // Approved orders never paid: made, paid, expired and the abandonment rate. const unpaid=data.unpaid; const unpaidRows=[['Pedidos feitos',String(unpaid.made)],['Pagos',String(unpaid.paid)], diff --git a/web/kanban-site.js b/web/kanban-site.js index d93955d..fd5e4e4 100644 --- a/web/kanban-site.js +++ b/web/kanban-site.js @@ -3,7 +3,7 @@ which defines api, may, money, when, say, node and button. A price is history: one that has started is never changed or deleted, so only a scheduled (future) price may be cancelled. */ -const SITE_UNIT_LABEL={metro:' /m',pedido:' por pedido'}; +const SITE_UNIT_LABEL={metro:' /m',pedido:' por pedido',arte:' por arte'}; // Reais with a comma, as the Site shows them: "19,90" is 1990 cents. function moneyInputCents(value){ @@ -18,10 +18,11 @@ function moneyInputCents(value){ // A price that already started is refused by the server (409). const cancelScheduledPrice=id=>api('/site/prices/'+id+'/cancel',{}); -// "5" or "5,5": a band's start in metres, as the table reads it. +// "5" or "5,5": a band's start, in metres or arts, as the table reads it. function bandMetres(value){return String(Number(value)).replace('.',',');} -function bandsText(bands){ - return (bands||[]).map(band=>' · '+bandMetres(band.from_metres)+' m: '+money(band.unit_cents)).join(''); +function bandsText(bands,unit='metro'){ + return (bands||[]).map(band=>' · '+bandMetres(band.from_metres)+' '+ + (unit==='arte'?(Number(band.from_metres)===1?'arte':'artes'):'m')+': '+money(band.unit_cents)).join(''); } function siteProductRow(product){ @@ -66,17 +67,18 @@ function sitePriceBlock(product){ starts.setAttribute('aria-label','Quando o novo preço de '+product.title+' começa'); startsLabel.append(starts); // Faixas progressivas (front 8.2): a nova tabela começa vazia; as faixas - // viajam com este preço. O tratamento é um valor por pedido, sem faixas. + // viajam com este preço. Ajuste Fino conta as faixas em artes, os produtos em metros. + const bandUnit=product.unit==='arte'?'artes':'m'; const bandRows=node('div',undefined,'siteBandRows'); const addBand=node('button','Adicionar faixa','btn ghost');addBand.type='button'; const paintAdd=()=>{addBand.disabled=bandRows.children.length>=5;}; const bandRow=()=>{ const row=node('div',undefined,'siteBandRow'); - const fromLabel=node('label');fromLabel.append(node('span','A partir de (m)')); + const fromLabel=node('label');fromLabel.append(node('span','A partir de ('+bandUnit+')')); const from=node('input');from.type='text';from.inputMode='decimal';from.className='siteBandFrom'; - from.setAttribute('aria-label','Metragem da faixa de '+product.title); + from.setAttribute('aria-label','Início da faixa em '+bandUnit+' de '+product.title); fromLabel.append(from); - const priceLabel=node('label');priceLabel.append(node('span','R$ por metro')); + const priceLabel=node('label');priceLabel.append(node('span','R$ por '+(product.unit==='arte'?'arte':'metro'))); const bandPrice=node('input');bandPrice.type='text';bandPrice.inputMode='decimal';bandPrice.className='siteBandPrice'; bandPrice.setAttribute('aria-label','Preço da faixa de '+product.title); priceLabel.append(bandPrice); @@ -93,7 +95,7 @@ function sitePriceBlock(product){ const from=Number(row.querySelector('.siteBandFrom').value.replace(',','.')); const unit=moneyInputCents(row.querySelector('.siteBandPrice').value); if(!Number.isFinite(from)||from<=0||unit===null||unit<=0) - throw new Error('Confira as faixas: metragem e preço maiores que zero.'); + throw new Error('Confira as faixas: início e preço maiores que zero.'); return {from_metres:String(from),unit_cents:unit}; }); const save=button('Salvar',async()=>{ @@ -103,18 +105,17 @@ function sitePriceBlock(product){ if(whenDate&&Number.isNaN(whenDate.getTime()))throw new Error('Data inválida.'); await api('/site/products/'+product.id+'/prices', {unit_cents:cents,starts_at:whenDate?whenDate.toISOString():null, - bands:product.id==='tratamento'?[]:formBands()}); + bands:formBands()}); say(whenDate?'Preço salvo para '+when(whenDate)+'.':'Preço salvo. Vale a partir de agora.'); await loadSiteAdmin(); },'btn pri'); - form.append(priceLabel,startsLabel,save); - if(product.id!=='tratamento')form.append(bands); + form.append(priceLabel,startsLabel,save,bands); const scheduled=node('div',undefined,'siteScheduled'); if(product.scheduled.length){ for(const row of product.scheduled){ const line=node('div',undefined,'siteScheduledRow'); - line.append(node('span',money(row.unit_cents)+SITE_UNIT_LABEL[product.unit]+bandsText(row.bands)+ + line.append(node('span',money(row.unit_cents)+SITE_UNIT_LABEL[product.unit]+bandsText(row.bands,product.unit)+ ' a partir de '+when(row.starts_at))); line.append(button('Cancelar',async()=>{ await cancelScheduledPrice(row.id); @@ -132,7 +133,7 @@ function sitePriceBlock(product){ const body=node('tbody'); for(const row of product.history){ const tr=node('tr'); - tr.append(node('td',money(row.unit_cents)+bandsText(row.bands),'nowrap'),node('td',when(row.starts_at),'nowrap'), + tr.append(node('td',money(row.unit_cents)+bandsText(row.bands,product.unit),'nowrap'),node('td',when(row.starts_at),'nowrap'), node('td',row.created_by),node('td',when(row.created_at),'nowrap')); body.append(tr); } @@ -188,7 +189,7 @@ async function loadGradeRules(){ 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 tratamento=gradeRuleRow('Exigir o Ajuste Fino 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; @@ -196,14 +197,14 @@ async function loadGradeRules(){ 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.'); + throw new Error('A regra do Ajuste Fino 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')); + children.push(node('p','Ative e dê preço ao Ajuste Fino para esta regra valer.','siteGradeWarn')); const foot=node('div',undefined,'siteGradeSave');foot.append(save);children.push(foot); $('site-grade-body').replaceChildren(...children); } diff --git a/web/kanban.css b/web/kanban.css index 468a256..85a0a05 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -1289,6 +1289,48 @@ dialog.viewer::backdrop{background:var(--scrim)} #tab-montar .montar-size-head{font-size:12.5px;color:var(--tx3)} #tab-montar .montar-size-row input{height:36px;padding:0 10px;border-radius:9px;border:1px solid var(--ln2);background:var(--bg);color:var(--tx)} #tab-montar .montar-size-row input:focus{border-color:var(--acc)} +/* The Tiny typeahead opens over the sheet: the panel must not clip it. */ +#tab-montar #montar-sheet{overflow:visible} +#tab-montar .montar-kindbar{display:flex;align-items:center;gap:14px;flex-wrap:wrap;padding:12px 18px} +#tab-montar .montar-kindbar .phint{margin:0} +#tab-montar .montar-customer-search{position:relative;margin-bottom:12px} +#tab-montar .montar-hits{position:absolute;z-index:30;left:0;right:0;top:calc(100% + 4px);max-height:260px;overflow:auto;border:1px solid var(--ln2);border-radius:10px;background:var(--sf);box-shadow:0 12px 32px rgba(0,0,0,.25);padding:4px} +#tab-montar .montar-hit{display:flex;flex-direction:column;gap:2px;width:100%;padding:8px 10px;border:0;border-radius:7px;background:transparent;color:var(--tx);text-align:left;cursor:pointer} +#tab-montar .montar-hit:hover{background:var(--sf3)} +#tab-montar .montar-hit b{font-size:13.5px;font-weight:650} +#tab-montar .montar-hit .sub{font-size:12.5px;color:var(--tx3)} +#tab-montar .montar-delivery{border-top:1px solid var(--ln);padding:14px 18px} +#tab-montar .montar-delivery h3{margin:0 0 10px;font-size:13px;font-weight:650;color:var(--tx2)} +#tab-montar .montar-delivery-options{display:flex;flex-wrap:wrap;gap:8px} +#tab-montar .montar-radio{display:inline-flex;align-items:center;gap:8px;height:36px;padding:0 12px;border-radius:9px;border:1px solid var(--ln2);font-size:13px;font-weight:550;color:var(--tx2);cursor:pointer} +#tab-montar .montar-radio:has(input[type="radio"]:checked){border-color:var(--acc);color:var(--tx)} +#tab-montar .montar-radio input[type="number"]{width:110px;height:28px;padding:0 8px;border-radius:7px;border:1px solid var(--ln2);background:var(--bg);color:var(--tx);font-family:inherit;font-size:13px} +#tab-montar .montar-radio input[type="number"]:disabled{opacity:.5} +#tab-montar .montar-shipping{margin-top:12px} +#tab-montar .montar-cep{display:flex;align-items:flex-end;gap:10px;flex-wrap:wrap} +#tab-montar .montar-cep .fld{flex:1;min-width:180px} +#tab-montar .montar-cep .btn{height:42px} +#tab-montar #montar-ship-msg,#tab-montar #montar-freight-msg{margin:8px 0 0;padding:0} +#tab-montar #montar-freight-msg{flex:1;min-width:180px} +#tab-montar .montar-ship-fields{margin-top:12px} +#tab-montar .montar-freight-actions{display:flex;align-items:center;gap:12px;margin-top:14px;flex-wrap:wrap} +#tab-montar .montar-freights{display:flex;flex-direction:column;gap:6px;margin-top:10px} +#tab-montar .montar-freight{display:flex;align-items:center;gap:10px;padding:9px 12px;border:1px solid var(--ln2);border-radius:9px;cursor:pointer} +#tab-montar .montar-freight:has(input:checked){border-color:var(--acc)} +#tab-montar .montar-freight input{accent-color:var(--acc)} +#tab-montar .montar-freight-meta{display:flex;flex:1;align-items:baseline;gap:10px;flex-wrap:wrap;min-width:0} +#tab-montar .montar-freight-meta b{font-size:13.5px;font-weight:650} +#tab-montar .montar-freight-meta .sub{font-size:12.5px;color:var(--tx3)} +#tab-montar .montar-freight-meta em{margin-left:auto;font-style:normal;font-weight:650} +#tab-montar .montar-brand{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:8px} +#tab-montar .montar-brand .lbl{font-size:12px;color:var(--tx3)} +#tab-montar .montar-brand b{font-size:13.5px;font-weight:650} +#tab-montar .montar-brandinput{width:190px;height:34px;padding:0 10px;border-radius:8px;border:1px solid var(--ln2);background:var(--bg);color:var(--tx);font-family:inherit;font-size:13px} +#tab-montar .montar-brandinput:focus{border-color:var(--acc)} +#tab-montar .montar-public{display:inline-flex;align-items:center;gap:6px;font-size:12.5px;color:var(--tx2);cursor:pointer} +#tab-montar .montar-public input{accent-color:var(--acc)} +#tab-montar .montar-stampbody{display:flex;flex-direction:column;gap:4px;min-width:0} +#tab-montar .montar-interno-fields{padding:0 18px} @media (max-width:700px){ #tab-montar .montar-add{grid-template-columns:minmax(0,1fr) minmax(0,1fr);padding:14px 14px 0} #tab-montar .montar-add>.btn{grid-column:1/-1} @@ -1307,4 +1349,8 @@ dialog.viewer::backdrop{background:var(--scrim)} #tab-montar .montar-warn{padding:10px 14px} #tab-montar .montar-layout{height:260px;padding:8px} #tab-montar .montar-size-head,#tab-montar .montar-size-row{grid-template-columns:70px minmax(0,1fr) 36px;padding:6px 14px} + #tab-montar .montar-kindbar{padding:12px 14px} + #tab-montar .montar-delivery{padding:12px 14px} + #tab-montar .montar-interno-fields{padding:0 14px} + #tab-montar .montar-brandinput{width:100%} } diff --git a/web/kanban.html b/web/kanban.html index e0897f1..a5bc674 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -117,6 +117,13 @@