Merge main into fix-pdf-check

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-11 15:58:09 -03:00
81 changed files with 2827 additions and 288 deletions

View File

@@ -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: ...

View File

@@ -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.

View File

@@ -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,

View File

@@ -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)

View File

@@ -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):

View File

@@ -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."""

View File

@@ -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}

View File

@@ -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.')

View File

@@ -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'],

View File

@@ -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:

View File

@@ -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

View File

@@ -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)')

View File

@@ -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'],

View File

@@ -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):

View File

@@ -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}

View File

@@ -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:

View File

@@ -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

View File

@@ -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

View File

@@ -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`.

View File

@@ -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.')

View File

@@ -1,8 +1,9 @@
"""Each machine's hot folders (Dropstar's third round, item 10, 2026-10-29/30).
FlexiPRINT watches 3. Imprimindo/<máquina>/<C1|C2|C3>/ 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/<máquina>/<C1|C2|C3|PREMIUM>/ 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)

129
app/label.py Normal file
View File

@@ -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-<number> 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"""<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<title>Etiqueta {code}</title>
<style>
@page {{ size: 100mm 150mm; margin: 0 }}
* {{ box-sizing: border-box }}
html, body {{ margin: 0; padding: 0; background: #fff; color: #000 }}
body {{ font-family: system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif }}
.label {{ width: 100mm; height: 150mm; padding: 6mm 6mm 5mm; display: flex;
flex-direction: column; gap: 2mm; overflow: hidden }}
.code {{ font-size: {code_size}mm; line-height: .95; font-weight: 800; letter-spacing: -.02em;
white-space: nowrap; overflow: hidden }}
.customer {{ font-size: 6mm; line-height: 1.15; font-weight: 700 }}
.line {{ font-size: 4.6mm; line-height: 1.2 }}
.foot {{ font-size: 3.6mm; line-height: 1.35; margin-top: 2mm }}
.qr {{ margin-top: auto; display: flex; justify-content: center }}
.qr svg {{ width: 30mm; height: 30mm; display: block }}
</style>
</head>
<body>
<div class="label">
<div class="code">{code}</div>
<div class="customer">{customer}</div>
<div class="line">DTF · {sheets} · {metres} m</div>
<div class="line">{delivery}</div>
<div class="foot"><div>Finalizado em {finished}</div><div>Revisor: {revisor}</div></div>
<div class="qr">{qr_svg(fields['qr'])}</div>
</div>
</body>
</html>
"""

View File

@@ -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

View File

@@ -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):

View File

@@ -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;

View File

@@ -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'));

View File

@@ -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';

139
app/observability.py Normal file
View File

@@ -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'(?<!\d)(?:\d{2}\.?\d{3}\.?\d{3}/?\d{4}-?\d{2}'
r'|\d{3}\.?\d{3}\.?\d{3}-?\d{2})(?!\d)')
SENSITIVE_PARAM = re.compile(r'token|signature|x-amz', re.I)
SENSITIVE_HEADER = re.compile(r'^(cookie|authorization|x-.*token.*)$', re.I)
REDACTED = '[removido]'
def _clean(text):
"""Replace e-mail addresses and CPF/CNPJ in one string."""
if not isinstance(text, str):
return text
return DOCUMENT.sub(REDACTED, EMAIL.sub(REDACTED, text))
def _scrub_query(query):
"""A query string without token, signature and X-Amz parameters."""
if not isinstance(query, str) or not query:
return query
pairs = parse_qsl(query, keep_blank_values=True)
kept = [(key, value) for key, value in pairs if not SENSITIVE_PARAM.search(key)]
return query if len(kept) == len(pairs) else urlencode(kept, doseq=True)
def _scrub_url(url):
if not isinstance(url, str):
return url
parts = urlsplit(url)
if not parts.query:
return url
return urlunsplit(parts._replace(query=_scrub_query(parts.query)))
def _scrub_text(value):
"""Personal data and a URL query string inside a message or crumb."""
value = _clean(value)
if not isinstance(value, str) or '?' not in value:
return value
head, _, query = value.partition('?')
return head + '?' + _scrub_query(query)
def _scrub_value(value):
if isinstance(value, str):
return _scrub_text(value)
if isinstance(value, list):
return [_scrub_value(item) for item in value]
if isinstance(value, dict):
return {key: _scrub_value(item) for key, item in value.items()}
return value
def _scrub_request(request):
"""Cookies, credentials, query tokens and bodies never leave the server."""
if not isinstance(request, dict):
return
request.pop('cookies', None)
request.pop('data', None)
request.pop('body', None)
headers = request.get('headers')
if isinstance(headers, dict):
request['headers'] = {key: value for key, value in headers.items()
if not SENSITIVE_HEADER.match(str(key))}
if 'query_string' in request:
request['query_string'] = _scrub_query(request['query_string'])
if 'url' in request:
request['url'] = _scrub_url(request['url'])
def scrub(event, hint=None):
"""before_send: strip credentials, bodies and personal data from an event."""
if not isinstance(event, dict):
return event
_scrub_request(event.get('request'))
if 'message' in event:
event['message'] = _scrub_text(event['message'])
logentry = event.get('logentry')
if isinstance(logentry, dict) and 'message' in logentry:
logentry['message'] = _scrub_text(logentry['message'])
exception = event.get('exception')
if isinstance(exception, dict):
for value in exception.get('values') or []:
if isinstance(value, dict) and 'value' in value:
value['value'] = _scrub_text(value['value'])
breadcrumbs = event.get('breadcrumbs')
if isinstance(breadcrumbs, dict):
breadcrumbs = breadcrumbs.get('values') or []
if isinstance(breadcrumbs, list):
for crumb in breadcrumbs:
if not isinstance(crumb, dict):
continue
if 'message' in crumb:
crumb['message'] = _scrub_text(crumb['message'])
if 'data' in crumb:
crumb['data'] = _scrub_value(crumb['data'])
if 'extra' in event:
event['extra'] = _scrub_value(event['extra'])
return event
def _traces_rate():
try:
return float(os.environ.get('SENTRY_TRACES', '0') or 0)
except (TypeError, ValueError):
return 0.0
def init(component):
"""Start Sentry for this process; False (and no imports) without a DSN."""
dsn = os.environ.get('SENTRY_DSN_API', '').strip()
if not dsn:
return False
import sentry_sdk
environment = os.environ.get('SENTRY_ENVIRONMENT')
if not environment:
from .runtime import ENVIRONMENT
environment = ENVIRONMENT
sentry_sdk.init(
dsn=dsn,
environment=environment,
release=os.environ.get('IMAGE_TAG') or None,
send_default_pii=False,
traces_sample_rate=_traces_rate(),
before_send=scrub,
)
sentry_sdk.set_tag('component', component)
return True

View File

@@ -60,18 +60,19 @@ def is_test(order):
# (Dropstar's rule D-35, 2026-10-26; the user's answers of 2026-10-27).
MANUAL_PROVIDER = 'manual'
OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit')
# A montador order is invoiced, not paid at the counter: it is not one of the
# Cotações "registrar" methods.
# A montador Venda order is invoiced, not paid at the counter: it is not one of
# the Cotações "registrar" methods. It goes to Tiny as an approved quote does.
INVOICED_METHOD = 'faturado'
# A montador Interno order: the marketplace's own sale, already invoiced there.
# It stays in house and never reaches Tiny (Marcus, 2026-11-10).
INTERNAL_METHOD = 'interno'
def in_tiny(order):
"""Whether the order goes to Tiny: every order but a test or a proof card
(app/proof.py), which is no sale. A Dropflow order goes in its own revenue
category (app/tiny.py, CATEGORIES)."""
if (order.get('payment') or {}).get('method') == INVOICED_METHOD:
# Held until Dropstar decides how invoiced montador orders reach Tiny
# (asked 2026-11-09).
"""Whether the order goes to Tiny: every order but an internal one, a test
or a proof card (app/proof.py), which is no sale. A Dropflow order goes in
its own revenue category (app/tiny.py, CATEGORIES)."""
if (order.get('payment') or {}).get('method') == INTERNAL_METHOD:
return False
return not is_test(order) and not order.get('parent_id')
@@ -153,9 +154,9 @@ def create_order(c, quote, payment, origin):
proof.create_child(c, order)
if is_test(order):
return order, True
# An invoiced montador order was not paid: no "pedido pago" e-mail until
# Dropstar says what the customer hears (asked 2026-11-09).
if payment.get('method') != INVOICED_METHOD:
# An invoiced or internal montador order was not paid here: no "pedido
# pago" e-mail for either (front 7a.3).
if payment.get('method') not in (INVOICED_METHOD, INTERNAL_METHOD):
mail.order_paid(c, order, PUBLIC_ORIGIN)
if not in_tiny(order):
return order, True

View File

@@ -187,7 +187,7 @@ def render_one(storage):
(source_ids,)).fetchone()['e']
by_id = {str(row['id']): row for row in uploads}
if job.get('wait_for_treatment'):
finish(job, 'manual', {'reason': 'Tratamento pago: prepare e aprove o PNG completo no pedido pai para gerar a prova.'})
finish(job, 'manual', {'reason': 'Ajuste Fino pago: prepare e aprove o PNG completo no pedido pai para gerar a prova.'})
return True
if any(row['size'] > 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: '

View File

@@ -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.

View File

@@ -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}

View File

@@ -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,

View File

@@ -59,29 +59,34 @@ AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect'
# Not TINY_PRODUCT_<MODE>: 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'

View File

@@ -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)