Merge main into sentry

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-11 14:48:01 -03:00
31 changed files with 711 additions and 137 deletions

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,

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

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

@@ -111,11 +111,11 @@ 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 card a montador sheet becomes (front 7a.3): Interno (the fixed
internal customer, origin dropflow, never Tiny) or Venda (a Tiny customer,
origin atendimento, invoiced and sent to Tiny). Pickup in both, at the
Site's table price; the order records whether it travels with a clothing
order."""
"""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.')
@@ -127,7 +127,8 @@ def montador_order(body: MontadorOrder, request: Request, user=Depends(can('asse
customer = body.customer
origin, method = 'atendimento', payments.INVOICED_METHOD
draft = QuoteRequest(request_key=body.request_key, customer=customer, items=body.items,
freight=Freight(service='pickup')).model_dump(mode='json', exclude={'request_key'})
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:

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

@@ -7,13 +7,14 @@ app/core/pricing.py stays as the seed and the fallback for the five modes;
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
@@ -29,10 +30,10 @@ TITLES = {
'uvfile': 'UV folha pronta',
'uv': 'UV artes avulsas',
'premium': 'Têxtil Premium · 8 passadas',
'tratamento': 'Tratamento pelo designer',
'tratamento': 'Ajuste Fino',
}
UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro',
'premium': 'metro', 'tratamento': 'pedido'}
'premium': 'metro', 'tratamento': 'arte'}
def fallback_cents(product: str) -> int:
@@ -40,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
@@ -77,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

@@ -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,10 +303,11 @@ class QuoteRequest(StrictModel):
return self
class MontadorOrder(StrictModel):
"""What the montador sends (front 7a.3): Interno or Venda, loose artwork
only and pickup; the server prices and approves it as a quote. An Interno
"""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."""
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
kind: Literal['interno', 'venda']
# Empty for an Interno order: the server reads the internal customer.
@@ -300,6 +315,9 @@ class MontadorOrder(StrictModel):
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 order_kind(self):
@@ -307,8 +325,21 @@ class MontadorOrder(StrictModel):
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.')
if self.kind == 'interno' and self.with_order is not None:
raise ValueError('O pedido interno não tem envio.')
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):

View File

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

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

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

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