feat: Ajuste Fino Redesenho in the cart (Marcus 12/11, slice R1)

Under each art the Prumo warns about, the customer can choose Ajuste Fino
or Ajuste Fino Redesenho (vectorize or redraw, per art, +48 h, no batch
price). It is a disabled product until Gestão prices it in the Site tab;
the server charges it per chosen art, Tiny gets a DTFIMP.AJF.RED line and
two more business days, the card shows 'Redesenho · N artes' and the
designer gate applies. The preview loop is slice R2.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-12 11:05:17 -03:00
parent 5ca6792221
commit 38f947d632
23 changed files with 429 additions and 60 deletions

View File

@@ -198,6 +198,16 @@ class FakeTiny:
{'id': 1002, 'name': 'Maria Souza', 'document': '123.456.789-09',
'email': 'maria.souza@example.test', 'phone': '16988887777'},
]
# The code's SKUs, so a payload can be built on the local stack without
# asking Tiny: the modes' defaults and the designer services (front 1b).
SKUS = {
'DTFIMP.TX.100CM': 8001,
**{f'DTFIMP.TX.{cm:04d}CM': 8000 + cm // 10 for cm in range(10, 100, 10)},
'DTFIMP.UV.1MT': 8101, 'DTFIMP.UV.010CM': 8102,
'DTFIMP.TXP.100CM': 8201,
**{f'DTFIMP.TXP.{cm:04d}CM': 8200 + cm // 10 for cm in range(10, 100, 10)},
'DTFIMP.AJF.UN': 9001, 'DTFIMP.AJF.RED': 9002,
}
def deliver(self, event_key: str, payload: dict) -> dict:
return {'provider': 'fake-tiny', 'reference': f"LOCAL-{payload['number']}",
@@ -206,6 +216,10 @@ class FakeTiny:
def search_contacts(self, query: str) -> list:
return [dict(contact) for contact in self.CONTACTS]
def product_id(self, code: str) -> int:
"""The fake Tiny product id for a SKU code, as the real catalogue does."""
return self.SKUS[code]
class ObjectStorage(Protocol):
def begin(self, key: str) -> str: ...
def parts(self, key: str, upload_id: str) -> list: ...

View File

@@ -42,6 +42,7 @@ def session(request: Request, response: Response):
products = catalog.current(c)
rules = grade_rules.current_rules(c)
treatment = products['tratamento']
redesign = products['redesenho']
return {'environment': ENVIRONMENT, 'cart_scope': str(session_id), 'part_bytes': PART_BYTES,
'max_upload_bytes': upload_limit_bytes(), 'payment_provider': payment.name,
'password_recovery': mail.configured(),
@@ -53,6 +54,9 @@ def session(request: Request, response: Response):
'treatment_bands': [{'from_metres': float(band['from_metres']),
'unit_cents': band['unit_cents']}
for band in treatment['bands']] if treatment['enabled'] else [],
# Zero keeps Redesenho hidden, as an off product does. One price
# per art, never a band (front 1b).
'redesign_cents': redesign['unit_cents'] if redesign['enabled'] else 0,
# The grade rules the Site needs for the treatment requirement
# (front 8.5): {} when nothing is configured.
'grade_rules': rules,

View File

@@ -8,6 +8,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response
from pydantic import Field
from ... import hotfolder, machines, mail, payments, prumo, receipt, reviews
from ...cart_pricing import designer_hours
from ...core import db
from ...core.auth import audit, can, operator
from ...core.models import StrictModel
@@ -138,10 +139,10 @@ def assign_late(c, orders, limits):
since = since or order['created_at']
hours = max(0.0, (now - since).total_seconds() / 3600)
limit_hours = float(limit['hours'])
# A paid treatment gives Art received its extra hours to prepare the art.
treatment = (order.get('snapshot') or {}).get('treatment') or {}
if order['state'] == 'rec' and treatment:
limit_hours += float(treatment.get('hours', 24))
# Paid designer work gives Art received its extra hours to prepare the
# art: 48 h for a Redesenho, 24 h for the basic Ajuste Fino.
if order['state'] == 'rec':
limit_hours += designer_hours(order.get('snapshot') or {})
order['state_hours'] = round(hours, 2)
order['limit_hours'] = limit_hours
order['limit_by'] = limit['responsible']

View File

@@ -9,6 +9,7 @@ from pydantic import Field
from psycopg.types.json import Jsonb
from ... import hotfolder, machine_log, machines, payments, proof, receipt, reviews
from ...cart_pricing import needs_designer
from ...core import db
from ...core.auth import MOVERS, audit, can, may_move, may_reorder, operator
from ...core.models import Contraction, Move, Resolution, StrictModel, UploadStart
@@ -208,7 +209,7 @@ def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
# que o Prumo gerou entram como finais, e o pai segue para a fila.
# Itens que ainda dependem de preparo manual continuam em Arte
# recebida, com o botão de final disponível.
if parent['state'] == 'rec' and not parent['snapshot'].get('treatment'):
if parent['state'] == 'rec' and not needs_designer(parent['snapshot']):
generated = c.execute('''SELECT p.item_index,p.upload_id FROM dtf_local.print_files p
WHERE p.order_id=%s AND p.status='ready' AND p.upload_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f
@@ -221,7 +222,7 @@ def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
VALUES(%s,%s,%s,%s,'final',%s,'Prumo')''',
(uuid4(), parent['id'], row['upload_id'], row['item_index'],
f'Aprovado pela prova do #{card["number"]}'))
treatment_clause = f'AND {TREATED}' if parent['snapshot'].get('treatment') else ''
treatment_clause = f'AND {TREATED}' if needs_designer(parent['snapshot']) else ''
ready = parent['state'] == 'rec' and all(c.execute(f'''SELECT 1 FROM dtf_local.order_files f
JOIN dtf_local.orders o ON o.id=f.order_id
JOIN dtf_local.uploads u ON u.id=f.upload_id
@@ -495,7 +496,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}''', (uid,)).fetchall()
if {r['item_index'] for r in coverage} != set(range(len(row['snapshot']['items']))):
raise HTTPException(409, 'Aprove os arquivos finais de todos os itens antes de mandar para Arte conferida.')
if row['snapshot'].get('treatment') and not row['parent_id']:
if needs_designer(row['snapshot']) and not row['parent_id']:
treated = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
JOIN dtf_local.orders o ON o.id=f.order_id
JOIN dtf_local.uploads u ON u.id=f.upload_id

View File

@@ -5,6 +5,7 @@ from decimal import Decimal
from fastapi import APIRouter, Depends, HTTPException, Query
from ... import machines, payments, unpaid
from ...cart_pricing import designer_hours
from ...core import db
from ...core.auth import operator
from .common import ORIGINS, REAL_ORDER, TREATED, person
@@ -106,7 +107,7 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
late_rows = c.execute(f'''SELECT s.state,
extract(epoch FROM s.until-s.at) - {waited('s.id', 's.at', 's.until')} AS seconds,
(s.until AT TIME ZONE 'America/Sao_Paulo')::date AS day,
o.snapshot->'treatment' AS treatment
o.snapshot->'treatment' AS treatment, o.snapshot->'redesign' AS redesign
FROM ({spans}) s LEFT JOIN dtf_local.orders o ON o.id=s.id WHERE s.until IS NOT NULL''',
period + period).fetchall()
printed = machine_output(c, start, end)
@@ -214,9 +215,8 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
if not limit:
continue
hours = float(limit['hours'])
treatment = row.get('treatment') or {}
if row['state'] == 'rec' and treatment:
hours += float(treatment.get('hours', 24))
if row['state'] == 'rec':
hours += designer_hours({'treatment': row.get('treatment'), 'redesign': row.get('redesign')})
if row['seconds'] > hours * 3600:
late[row['state']]['count'] += 1
if row['day'] == today:

View File

@@ -57,7 +57,8 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
cart = cart_pricing.price_cart(
c, draft['items'], names, coupon_code=code,
customer_document=body.customer.cnpj,
wants_treatment=draft.get('treatment', False))
wants_treatment=draft.get('treatment', False),
wants_redesign=draft.get('redesign', []))
if reason is not None:
freight.quote(body.freight.service, body.freight.postal_code,
sum(Decimal(i['billed_metres']) for i in cart['items']),

View File

@@ -95,8 +95,11 @@ def toggle_product(product: str, body: SiteProductToggle, user=Depends(can('mana
def schedule_price(product: str, body: SitePriceNew, user=Depends(can('manage'))):
if product not in catalog.PRODUCTS:
raise HTTPException(404, 'Produto não encontrado.')
if product != 'tratamento' and body.unit_cents <= 0:
if product not in ('tratamento', 'redesenho') and body.unit_cents <= 0:
raise HTTPException(422, 'O preço precisa ser maior que zero.')
# Redesenho is one price per art: its batch band belongs to the basic only.
if product == 'redesenho' and body.bands:
raise HTTPException(422, 'O Redesenho não tem faixas de preço.')
bands = checked_bands(product, body.bands)
now = datetime.now(timezone.utc)
starts_at = body.starts_at or now

View File

@@ -43,6 +43,35 @@ def treatment_price(items, choice, offer):
return {'cents': unit * count, 'hours': 24, 'arts': count, 'unit_cents': unit}
def redesign_price(items, choice, offer):
"""Ajuste Fino Redesenho for the chosen arts: one price per art, never a
band. {} 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 = offer['unit_cents']
return {'cents': unit * count, 'hours': 48, 'arts': count, 'unit_cents': unit}
def designer_hours(snapshot):
"""The extra hours the paid designer work adds to the deadline: 48 h when
any art was sent to Redesenho, else 24 h for the basic Ajuste Fino."""
if snapshot.get('redesign'):
return 48
if snapshot.get('treatment'):
return 24
return 0
def needs_designer(snapshot):
"""Whether a designer must prepare the final PNG before the print queue:
a paid Ajuste Fino or Redesenho on any art."""
return bool(snapshot.get('treatment') or snapshot.get('redesign'))
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
@@ -70,13 +99,15 @@ def price_items(items, names, catalog_now, manual_extra):
def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
wants_treatment=False, treatment_rule=True):
wants_treatment=False, wants_redesign=(), treatment_rule=True):
"""Price a cart exactly as an order is charged. Returns
{'items': [priced item dicts], 'items_total': int, 'coupon': dict|None,
'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."""
'treatment': dict, 'treatment_cents': int, 'redesign': dict,
'redesign_cents': int, 'grade_flags': dict}.
Raises HTTPException(422) for a product switched off, a Redesenho not
offered, a required designer service 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)
for item in items:
@@ -89,7 +120,12 @@ def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
if not treatment_rule:
flags.pop('tratamento', None)
treatment = treatment_price(items, wants_treatment, offer)
if 'tratamento' in flags and not treatment:
redesign = redesign_price(items, wants_redesign, catalog_now['redesenho'])
if chosen_arts(items, wants_redesign) and not redesign:
raise HTTPException(422, 'O Redesenho não está disponível agora.')
# The grade rule wants a designer on the art: the stronger Redesenho
# satisfies it just as the basic Ajuste Fino does.
if 'tratamento' in flags and not treatment and not redesign:
raise HTTPException(422, grade_rules.treatment_message(flags['tratamento']))
coupon = None
if coupon_code:
@@ -99,4 +135,6 @@ def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
'coupon': coupon,
'treatment': treatment,
'treatment_cents': treatment.get('cents', 0),
'redesign': redesign,
'redesign_cents': redesign.get('cents', 0),
'grade_flags': flags}

View File

@@ -9,7 +9,8 @@ and an approved quote keeps the price it was approved with.
`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.
switched on and priced above zero. `redesenho` is Ajuste Fino Redesenho (front
1b): one price per art, no bands, and the same rule for being offered.
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
@@ -20,9 +21,9 @@ from decimal import Decimal
from .core import pricing
# The modes sold by the metre, and the treatment sold per order.
# The modes sold by the metre, and the services sold per art.
MODES = ('file', 'avulsa', 'uvfile', 'uv', 'premium')
PRODUCTS = (*MODES, 'tratamento')
PRODUCTS = (*MODES, 'tratamento', 'redesenho')
TITLES = {
'file': 'Têxtil folha pronta',
@@ -31,14 +32,21 @@ TITLES = {
'uv': 'UV artes avulsas',
'premium': 'Têxtil Premium · 8 passadas',
'tratamento': 'Ajuste Fino',
'redesenho': 'Ajuste Fino Redesenho',
}
UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro',
'premium': 'metro', 'tratamento': 'arte'}
'premium': 'metro', 'tratamento': 'arte', 'redesenho': 'arte'}
def fallback_cents(product: str) -> int:
"""The price in the code, used until a row in the database takes over."""
return pricing.treatment_cents() if product == 'tratamento' else pricing.PRICES[product]
"""The price in the code, used until a row in the database takes over.
Redesenho has no price in the code: it starts disabled and unpriced, and
Gestão sets both in the Site tab."""
if product == 'tratamento':
return pricing.treatment_cents()
if product == 'redesenho':
return 0
return pricing.PRICES[product]
def band_price(base_cents: int, bands: list, quantity: Decimal) -> int:

View File

@@ -277,6 +277,9 @@ class QuoteRequest(StrictModel):
# 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
# Ajuste Fino Redesenho (front 1b): the arts sent to be redrawn, in the
# same [item_index, source_index] identifiers. One service per art.
redesign: list[tuple[int, int]] = Field(default_factory=list)
# 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).
@@ -300,6 +303,24 @@ class QuoteRequest(StrictModel):
seen.add((item_index, source_index))
return self
@model_validator(mode='after')
def redesign_arts_exist(self):
seen = set()
for item_index, source_index in self.redesign:
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('Redesenho: arte não encontrada no pedido.')
if (item_index, source_index) in seen:
raise ValueError('Redesenho: cada arte aparece uma vez.')
seen.add((item_index, source_index))
# The customer chooses one service per art: basic or Redesenho.
if self.treatment is True:
if seen:
raise ValueError('Escolha Ajuste Fino ou Redesenho para cada arte, não os dois.')
elif isinstance(self.treatment, list) and seen & {(i, s) for i, s in self.treatment}:
raise ValueError('Escolha Ajuste Fino ou Redesenho para cada arte, não os dois.')
return self
@model_validator(mode='after')
def destination_matches_freight(self):
if self.freight.service == 'pickup':

View File

@@ -0,0 +1,11 @@
-- Front 1b (Marcus, 2026-11-12): Ajuste Fino Redesenho, a per-art service
-- beside the basic Ajuste Fino. Created switched OFF and without a price:
-- Gestão sets both in the Site tab. The products CHECK is the inline
-- constraint of dtf_local.products.id (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','redesenho'));
INSERT INTO dtf_local.products(id, enabled) VALUES ('redesenho', false)
ON CONFLICT (id) DO NOTHING;

View File

@@ -32,6 +32,7 @@ from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
from psycopg.types.json import Jsonb
from PIL import Image
from .cart_pricing import needs_designer
from .core.auth import audit
from .core.db import connect
from .printfile import Unsupported
@@ -177,7 +178,7 @@ def render_one(storage):
source_ids = [source['id']]
item = {**item, 'uploads': [str(source['id'])]}
job['proof_fallback'] = True
elif job['snapshot'].get('treatment'):
elif needs_designer(job['snapshot']):
job['wait_for_treatment'] = True
uploads = c.execute('''SELECT id,name,size,object_key,scan_state,purged_at,expires_at,
(expires_at<=now()) AS expired FROM dtf_local.uploads WHERE id=ANY(%s)''',

View File

@@ -75,6 +75,7 @@ def approve(c, row, items, reviewer):
coupon_code=draft.get('coupon'),
customer_document=(draft.get('customer') or {}).get('cnpj'),
wants_treatment=draft.get('treatment', False),
wants_redesign=draft.get('redesign', []),
treatment_rule=not draft.get('montador'))
# Keep the review snapshot's own fields with each priced item.
priced = cart['items']
@@ -100,6 +101,7 @@ def approve(c, row, items, reviewer):
discount = coupon['discount_cents'] if coupon else 0
flags = cart['grade_flags']
treatment = cart['treatment']
redesign = cart['redesign']
metres = sum(Decimal(i['billed_metres']) for i in priced)
try:
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
@@ -112,6 +114,8 @@ def approve(c, row, items, reviewer):
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
# Ajuste Fino: per art, with the row's band (front 1a).
**({'treatment': treatment} if treatment else {}),
# Ajuste Fino Redesenho: per art, one price, 48 h (front 1b).
**({'redesign': redesign} if redesign 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).
@@ -119,7 +123,7 @@ def approve(c, row, items, reviewer):
# 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.get('cents', 0)}
+ treatment.get('cents', 0) + redesign.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

@@ -145,11 +145,17 @@ def quote_view(c, row, order=None, attempt=None, known=False):
from .cart_pricing import treatment_price
treatment = treatment_price(items, (row['draft'] or {}).get('treatment'),
catalog.current(c)['tratamento']) or None
redesign = (row['approved'] or {}).get('redesign')
if not redesign and (row['draft'] or {}).get('redesign'):
from .cart_pricing import redesign_price
redesign = redesign_price(items, (row['draft'] or {}).get('redesign'),
catalog.current(c)['redesenho']) 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,
'expired_at': row['expired_at'].isoformat() if row.get('expired_at') else None,
'prumo': prumo.customer_summary(items), 'treatment': treatment,
'redesign': redesign,
'status': 'paid' if order else 'discarded' if row.get('discarded_at') else 'expired' if expired
else 'approved' if row['approved'] else 'pending_review',
'auto_approved': row.get('reviewed_by') == 'auto',

View File

@@ -558,6 +558,19 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
'valorUnitario': money(unit),
'infoAdicional': 'Ajuste Fino · '+str(arts)+
(' arte' if arts == 1 else ' artes')+' · +24 h'})
redesign = order.get('redesign') or {}
if redesign.get('cents'):
# Ajuste Fino Redesenho (front 1b): per art, resolved by its SKU code,
# one price (never a band), 48 h. Empty setting means the default code.
if product_id is None:
raise TinyError('TINY_SKU_REDESIGN needs the SKU looked up in Tiny')
code = os.environ.get('TINY_SKU_REDESIGN', '').strip() or 'DTFIMP.AJF.RED'
arts = int(redesign.get('arts') or 1)
unit = int(redesign.get('unit_cents') or redesign['cents'])
items.append({'produto': {'id': product_id(code)}, 'quantidade': arts,
'valorUnitario': money(unit),
'infoAdicional': 'Ajuste Fino Redesenho · '+str(arts)+
(' arte' if arts == 1 else ' artes')+' · +48 h'})
freight = order['freight']
service = freight.get('service')
pickup = service == 'pickup'
@@ -579,7 +592,9 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
# The carrier's time already counts production; a pickup is ready after it.
days = freight.get('days') if not pickup else int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0)
if days is not None:
days = int(days) + (1 if treatment.get('cents') else 0)
# Redesenho adds 48 h (two working days); the basic adds one.
extra = 2 if redesign.get('cents') else 1 if treatment.get('cents') else 0
days = int(days) + extra
pedido['dataPrevista'] = business_days_after(day, days).isoformat()
# Paid at once, in full, as the store's orders: one parcel on the day.
pedido['pagamento'] = {'categoria': {'id': CATEGORIES.get(payload.get('origin'), CATEGORY)}}