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'

View File

@@ -49,17 +49,17 @@ def run():
refused = client.call('/quotes', quote_body(item, False, mail), expected=422)
assert refused['detail'] == ('Sua arte tem nota 50: para imprimir com qualidade, '
'o tratamento pelo designer é obrigatório neste pedido.'), refused
'o Ajuste Fino é obrigatório neste pedido.'), refused
made = client.call('/quotes', quote_body(item, True, mail))
quote_id = made['id']
assert made['status'] == 'approved', made
approved = client.call('/quotes/' + quote_id)['approved']
assert approved['grade_flags'] == {'aviso': 50, 'tratamento': 50}, approved
assert approved['treatment']['cents'] == 1000, approved
assert approved['treatment'] == {'cents': 1000, 'hours': 24, 'arts': 1,
'unit_cents': 1000}, approved
assert approved['total_cents'] == 9990, approved
print('PASS: the grade rule requires the designer treatment and flags the order'
' with the worst grade')
print('PASS: the grade rule requires Ajuste Fino and flags the order with the worst grade')
finally:
if rules_set:
try:

View File

@@ -4,12 +4,15 @@ Run against the local stack: SITE_BASE_URL=http://site SITE_HOST_HEADER=localhos
python -m tests.site_admin_test
"""
import io
import os
import secrets
from datetime import datetime, timedelta, timezone
from datetime import date, datetime, timedelta, timezone
from unittest import mock
from uuid import uuid4
from PIL import Image, ImageDraw
from app import tiny
from app.core import db
from tests.print_file_test import artwork
from tests.smoke_test import Client, item_spec, upload_bytes
@@ -34,6 +37,20 @@ def quote(client, item, mail, expected=200):
'items': [item], 'freight': {'service': 'pickup'}}, expected=expected)
def arts_item(upload_id, arts):
"""One loose-art item with `arts` sources of 10 x 10 cm, one metre long."""
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 10,
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
'measurement': 'customer'} for _ in range(arts)]
placements = [{'source_index': index, 'copy_index': 0, 'x_cm': 0, 'y_cm': index * 10,
'width_cm': 10, 'length_cm': 10, 'rotation_degrees': 0, 'mirrored': False}
for index in range(arts)]
return {'mode': 'avulsa', 'metres': '1', 'grade': 90, 'uploads': [upload_id] * arts,
'production': {'version': 3, 'film_width_cm': 57, 'height_cm': arts * 10,
'sources': sources, 'placements': placements},
'quality_status': 'ok', 'quality_acknowledged': False}
def run():
tag = secrets.token_hex(4)
mail = f'site-admin-{tag}@example.test'
@@ -44,12 +61,12 @@ def run():
manager.call('/session')
manager.call('/operator/me', operator=True)
manager = manager.operator_client
prices, user = [], None
prices, user, treatment_enabled = [], None, None
try:
products = manager.call('/operator/site/products')['products']
assert {product['id'] for product in products} == \
{'file', 'avulsa', 'uvfile', 'uv', 'premium', 'tratamento'}
assert all(product['unit'] in ('metro', 'pedido') and product['title'] for product in products)
assert all(product['unit'] in ('metro', 'pedido', 'arte') and product['title'] for product in products)
# Front 3: Premium is listed and starts switched off (Marcus, 2026-11-10).
premium_entry = next(product for product in products if product['id'] == PREMIUM)
@@ -71,6 +88,46 @@ def run():
assert approved['total_cents'] == 3990, approved
manager.call(f'/operator/site/products/{PREMIUM}', {'enabled': False})
# Front 1a: Ajuste Fino per art, with the batch band set in the Site tab.
treatment = next(product for product in products if product['id'] == 'tratamento')
treatment_enabled = treatment['enabled']
manager.call('/operator/site/products/tratamento', {'enabled': True})
made = manager.call('/operator/site/products/tratamento/prices', {
'unit_cents': 990, 'bands': [{'from_metres': '10', 'unit_cents': 690}]})
prices.append(made['id'])
session = client.call('/session')
assert session['treatment_cents'] == 990, session
assert session['treatment_bands'] == [{'from_metres': 10.0, 'unit_cents': 690}], session
arts = arts_item(upload_bytes(client, artwork(), name='LOCAL-AJUSTE-FINO.png'), 10)
customer = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail}
three = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
'items': [arts], 'treatment': [[0, 0], [0, 1], [0, 2]],
'freight': {'service': 'pickup'}})
assert three['status'] == 'approved', three
ajuste = client.call('/quotes/' + three['id'])['approved']
assert ajuste['treatment'] == {'cents': 2970, 'hours': 24, 'arts': 3,
'unit_cents': 990}, ajuste
assert ajuste['total_cents'] == ajuste['items'][0]['total_cents'] + 2970, ajuste
ten = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
'items': [arts], 'treatment': [[0, index] for index in range(10)],
'freight': {'service': 'pickup'}})
ten = client.call('/quotes/' + ten['id'])['approved']
assert ten['treatment'] == {'cents': 6900, 'hours': 24, 'arts': 10,
'unit_cents': 690}, ten
old = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
'items': [arts], 'treatment': True, 'freight': {'service': 'pickup'}})
old = client.call('/quotes/' + old['id'])['approved']
assert old['treatment'] == {'cents': 6900, 'hours': 24, 'arts': 10,
'unit_cents': 690}, old
# Tiny: the quantity is the number of arts and the unit is the band price.
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
pedido = tiny.order_payload({'order_id': three['id'], 'order': ajuste,
'number': 1, 'payment': {}, 'origin': 'site'}, 777,
date(2026, 11, 11), product_id=lambda code: 999)
assert [line for line in pedido['itens'] if line['produto']['id'] == 105] == [
{'produto': {'id': 105}, 'quantidade': 3, 'valorUnitario': 9.9,
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}], pedido['itens']
manager.call(f'/operator/site/products/{UV}', {'enabled': True})
uid = upload_bytes(client, artwork(), name='LOCAL-SITE-ADMIN.png')
item = {**item_spec('uv', '1', 0, uid), 'quality_status': 'warning', 'quality_acknowledged': True}
@@ -143,8 +200,6 @@ def run():
manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 12345, 'bands': [{'from_metres': str(i), 'unit_cents': 1900}
for i in range(1, 7)]}, expected=422)
manager.call('/operator/site/products/tratamento/prices', {
'unit_cents': 1000, 'bands': [{'from_metres': '5', 'unit_cents': 900}]}, expected=422)
# A profile without "manage" cannot see or change the Site tab.
email = f'site-staff-{tag}@example.test'
@@ -158,14 +213,19 @@ def run():
staff.call(f'/operator/site/products/{UV}/prices', {'unit_cents': 1000}, expected=403)
staff.call(f'/operator/site/prices/{made["id"]}/cancel', {}, expected=403)
print('PASS: the Site tab switches a product off and refuses quotes, lists Premium switched off'
' and accepts it once enabled, schedules and cancels prices, charges the new price,'
' and refuses a non-manage profile')
' and accepts it once enabled, prices Ajuste Fino per art with its band,'
' schedules and cancels prices, charges the new price, and refuses a non-manage profile')
finally:
with db.connect() as c:
if prices:
c.execute('DELETE FROM dtf_local.product_prices WHERE id=ANY(%s::bigint[])', (prices,))
c.execute("UPDATE dtf_local.products SET enabled=true WHERE id=%s", (UV,))
c.execute("UPDATE dtf_local.products SET enabled=false WHERE id=%s", (PREMIUM,))
if treatment_enabled is not None:
try:
manager.call('/operator/site/products/tratamento', {'enabled': treatment_enabled})
except Exception:
pass
if user:
try:
manager.call('/operator/users/' + str(user['id']) + '/delete', {}, expected=200)

View File

@@ -79,6 +79,8 @@ def run():
'zap': '1633334444', 'mail': f'interno-{tag}@example.test'}
venda_customer = {'name': 'Maria Souza', 'cnpj': '12345678909',
'zap': '16988887777', 'mail': f'venda-{tag}@example.test'}
envio_customer = {'name': 'Maria Souza', 'cnpj': '12345678909',
'zap': '16988887777', 'mail': f'envio-{tag}@example.test'}
identities = [operator_identity(emails['expedicao']), operator_identity(emails['vendedor'])]
made_orders, made_quotes = [], []
# A code of its own, so a brand someone saved in Estampas/ is never touched.
@@ -200,8 +202,36 @@ def run():
designer.call('/operator/montador/orders', {'request_key': str(uuid4()), **venda}, expected=403)
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'interno',
'items': [montador_item(stamp, 'file')]}, expected=422)
# Venda with Envio: the Site's freight, re-quoted by the server.
destination = {'recipient': 'Maria Souza', 'street': 'Rua das Flores', 'number': '100',
'complement': 'Sala 2', 'district': 'Centro', 'city': 'Franca',
'state': 'SP', 'postal_code': '14400000'}
envio_stamp = upload_stamp(seller)
envio = {'kind': 'venda', 'customer': envio_customer, 'items': [montador_item(envio_stamp)],
'freight': {'service': 'mock-standard', 'postal_code': '14400000'},
'destination': destination}
order_envio = seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **envio})
made_orders.append(UUID(order_envio['id']))
made_quotes.append(UUID(order_envio['quote_id']))
snapshot = order_envio['snapshot']
assert snapshot['destination'] == destination, snapshot.get('destination')
assert snapshot['freight']['service'] == 'mock-standard', snapshot.get('freight')
assert snapshot['freight']['total_cents'] > 0, snapshot.get('freight')
assert snapshot['total_cents'] == (sum(item['total_cents'] for item in snapshot['items']) +
snapshot['freight']['total_cents']), snapshot['total_cents']
with db.connect() as c:
assert c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s AND provider=%s',
(f"{order_envio['id']}:paid:tiny", 'tiny')).fetchone()
# Envio needs the full address; an Interno order never ships.
sem_destino = {key: value for key, value in envio.items() if key != 'destination'}
seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **sem_destino}, expected=422)
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'interno',
'items': [montador_item(stamp)],
'destination': destination}, expected=422)
print('PASS: Expedição makes Interno and Vendedor makes Venda; the internal customer, the Tiny '
'contacts, the stamp brand and the table price in Números work; invalid profiles and modes are refused')
'contacts, the stamp brand and the table price in Números work; a Venda with Envio carries '
'the destination and the quoted freight; invalid profiles, modes and deliveries are refused')
finally:
with db.connect() as c:
if made_orders:
@@ -215,8 +245,8 @@ def run():
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,))
if made_quotes:
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', (made_quotes,))
c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr IN (%s,%s)',
(internal_customer['mail'], venda_customer['mail']))
c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr IN (%s,%s,%s)',
(internal_customer['mail'], venda_customer['mail'], envio_customer['mail']))
for identity in identities:
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (identity,))
c.execute('DELETE FROM dtf_local.stamps WHERE code=%s', (stamp_code,))

View File

@@ -9,7 +9,7 @@ import unittest
from decimal import Decimal
from app import catalog
from app.cart_pricing import price_items
from app.cart_pricing import price_items, treatment_price
from app.core import pricing
@@ -156,6 +156,21 @@ class CartPricingCharacterizationTest(unittest.TestCase):
floating = priced('band-floating-metres')[0]
self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.9', 24650))
def test_ajuste_fino_is_per_art_with_the_band(self):
# Front 1a: 1 to 9 arts at R$ 9,90, from 10 at R$ 6,90, all arts charged
# at the band. `true` keeps meaning every art of the cart.
offer = {'enabled': True, 'unit_cents': 990,
'bands': [{'from_metres': '10', 'unit_cents': 690}]}
for arts, unit in ((1, 990), (9, 990), (10, 690), (12, 690)):
items = [item('avulsa', '1', uid=f'u{index}') for index in range(arts)]
self.assertEqual(treatment_price(items, True, offer),
{'cents': unit * arts, 'hours': 24, 'arts': arts, 'unit_cents': unit})
items = [item('file', '1', uid='u1'), item('file', '1', uid='u2')]
self.assertEqual(treatment_price(items, [[1, 0]], offer),
{'cents': 990, 'hours': 24, 'arts': 1, 'unit_cents': 990})
self.assertEqual(treatment_price(items, [], offer), {})
self.assertEqual(treatment_price(items, True, {**offer, 'enabled': False}), {})
if __name__ == '__main__':
unittest.main()

View File

@@ -34,7 +34,7 @@ class GradeRulesTest(unittest.TestCase):
def test_treatment_message(self):
self.assertEqual(
treatment_message(45),
'Sua arte tem nota 45: para imprimir com qualidade, o tratamento pelo designer '
'Sua arte tem nota 45: para imprimir com qualidade, o Ajuste Fino '
'é obrigatório neste pedido.')

View File

@@ -133,6 +133,22 @@ class PricingTests(unittest.TestCase):
with self.subTest(metres=metres):
self.assertEqual(cents, band_price(PRICES['file'], bands, Decimal(metres)))
def test_ajuste_fino_band_against_actual_site_javascript(self):
# Ajuste Fino counts its band in arts: the Site helper must charge the
# same unit price as catalog.band_price.
source = Path('web/site-config.js').read_text()
body = source.split('function precoAjuste', 1)[1].split('\n}', 1)[0]
bands = [{'from_metres': 10, 'unit_cents': 690}]
js = ('const TAXA_TRATAMENTO=9.9;const FAIXAS=' + json.dumps({'tratamento': bands}) + ';'
'function precoAjuste' + body + '\n}'
';const results=[];for(const n of [1,9,10,12])'
'results.push([n,Math.round(precoAjuste(n)*100)]);'
'process.stdout.write(JSON.stringify(results));')
cases = json.loads(subprocess.check_output(['node', '-e', js], text=True))
for arts, cents in cases:
with self.subTest(arts=arts):
self.assertEqual(cents, band_price(990, bands, Decimal(arts)))
def test_which_items_are_opened_by_hand(self):
def item(kind, measurement, uid='u1'):
return {'production': {'sources': [{'kind': kind, 'measurement': measurement, 'upload_id': uid}]}}

View File

@@ -160,8 +160,17 @@ class TinyTests(FakeTinyCase):
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
pedido = order_payload(treatment, 777, date(2026, 9, 24))
self.assertIn({'produto': {'id': 105}, 'quantidade': 1, 'valorUnitario': 9.9,
'infoAdicional': 'Tratamento da arte pelo designer · +24 h'}, pedido['itens'])
'infoAdicional': 'Ajuste Fino · 1 arte · +24 h'}, pedido['itens'])
self.assertNotEqual(pedido['dataPrevista'], order_payload(plain, 777, date(2026, 9, 24))['dataPrevista'])
# Per art: the quantity is the number of arts and the unit is the band price.
per_art = {'order': {**base, 'treatment': {'cents': 2070, 'hours': 24, 'arts': 3,
'unit_cents': 690},
'total_cents': base['total_cents'] + 2070},
**{k: v for k, v in PAID.items() if k != 'order'}}
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
pedido = order_payload(per_art, 777, date(2026, 9, 24))
self.assertIn({'produto': {'id': 105}, 'quantidade': 3, 'valorUnitario': 6.9,
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}, pedido['itens'])
def test_second_delivery_finds_the_first_order(self):
first = self.tiny.deliver('k1', PAID)

View File

@@ -24,14 +24,14 @@ def run():
'note': 'Gerado pelo Prumo'}, operator=True)
blocked = client.call('/operator/orders/' + order['id'] + '/move',
{'state': 'tra', 'version': approved['version']}, operator=True, expected=409)
assert 'Tratamento pago' in blocked['detail'], blocked
assert 'Ajuste Fino pago' in blocked['detail'], blocked
prepared = upload_bytes(client, artwork(), name='LOCAL-TREATMENT-FINAL.png', order_id=order['id'])
approved = client.call('/operator/orders/' + order['id'] + '/final-files',
{'version': approved['version'], 'files': [{'item_index': 0, 'upload_id': prepared}],
'note': 'PNG tratado pelo designer'}, operator=True)
client.call('/operator/orders/' + order['id'] + '/move',
{'state': 'tra', 'version': approved['version']}, operator=True)
print('PASS: generated artwork cannot satisfy paid treatment; designer PNG opens the print queue')
print('PASS: generated artwork cannot satisfy paid Ajuste Fino; designer PNG opens the print queue')
if __name__ == '__main__':

View File

@@ -27,7 +27,7 @@
stroke:item.strokeClass||null,strokeChoice:item.strokeChoice||null,
sheets:(item.partes||[]).map(part=>part.production),
files:(item.localFiles||[]).map(file=>({name:file.name,size:file.size,lastModified:file.lastModified}))
})),treatment:!!$('fTratamento')?.checked,coupon:cupomCode()});
})),treatment:ajusteSnapshot(),coupon:cupomCode()});
}
// The quote this browser is paying, forgotten. clearDraft also empties the
// payment area; forgetDraft leaves on screen what is there (a confirmation).
@@ -87,9 +87,11 @@
// The art grade rules (front 8.5): the Site uses only the treatment rule,
// forcing the checkbox when the cart's worst grade is below it.
window.dtfGradeRules=session.grade_rules||{};
// Treatment by the designer (front 5): only offered when TREATMENT_CENTS
// is set; the server adds the same amount and the 24 h to the quote.
// Ajuste Fino (front 1a): per art, with a band by the order's number of
// arts. Only offered when TREATMENT_CENTS is set; the server adds the
// same amount and the 24 h to the quote.
TAXA_TRATAMENTO=(session.treatment_cents||0)/100;
FAIXAS.tratamento=session.treatment_bands||[];
const tratamentoBox=document.getElementById('tratamentoBox');
if(tratamentoBox){
tratamentoBox.hidden=!(TAXA_TRATAMENTO>0);
@@ -123,6 +125,7 @@
}
window.dtfProducts=session.products;
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
if(typeof artes!=='undefined'&&artes.length&&typeof pintaArtes==='function')pintaArtes();
if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho();
if(typeof pintaTipoEnvio==='function')pintaTipoEnvio();
semPedidos=!Object.values(session.products).some(product=>product.enabled);
@@ -181,8 +184,11 @@
const prazo = approved.freight.days ? ' · até '+approved.freight.days+' dias úteis' : '';
rows.push(linha(pickup ? 'Retirada em Franca' : (approved.freight.description || 'Frete')+prazo,
approved.freight.total_cents ? rs(approved.freight.total_cents/100) : 'Grátis'));
if(quote.treatment?.cents)
rows.push(linha('Tratamento da arte pelo designer · +24 h', rs(quote.treatment.cents/100)));
if(quote.treatment?.cents){
const arts=Number(quote.treatment.arts)||0;
rows.push(linha('Ajuste Fino'+(arts?' · '+arts+(arts===1?' arte':' artes'):'')+' · +24 h',
rs(quote.treatment.cents/100)));
}
if(approved.coupon)
rows.push(linha('Cupom '+approved.coupon.code, '− '+rs(approved.coupon.discount_cents/100)));
rows.push(linha('Total', rs(approved.total_cents/100), 'tot'));
@@ -442,7 +448,9 @@
if (destination) content.destination = destination;
// "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
if ($('fProva')?.checked) content.proof = true;
if ($('fTratamento')?.checked) content.treatment = true;
// Ajuste Fino: true for every art, or the [item, source] pairs chosen.
const treatment=tratamentoParaItens(sheets);
if (treatment) content.treatment = treatment;
if (cartSnapshot()!==initialCart) throw new Error('O carrinho mudou durante o envio. Confira os itens e envie de novo.');
// Browser timings for Números (item 0.12); they never affect the price.
const T=window.dtfTimings, timings={};

View File

@@ -1123,9 +1123,9 @@ h2 em{font-style:normal;color:var(--laranja)}
</div>
<div class="cxE" id="tratamentoBox" hidden>
<h4>Tratamento da arte</h4>
<h4>Ajuste Fino</h4>
<label class="provaOp"><input type="checkbox" id="fTratamento">
<span><b>Quero o tratamento pelo designer — <span id="tratamentoPreco"></span></b>
<span><b>Ajuste Fino em todas as artes — <span id="tratamentoPreco"></span> por arte</b>
O designer ajusta a arte para DTF, com fundo transparente e 300 DPI, e sobe o arquivo
pelo card. O prazo do pedido aumenta em 24 h.</span></label>
</div>

View File

@@ -10,7 +10,8 @@ const MONTAR_DPI_REFUSE=96, MONTAR_DPI_WARN=200;
const MONTAR_FILM_CM=57, MONTAR_GAP_CM=0.5;
const MONTAR={sizes:[],lines:[],seq:0,preview:null,timer:null,dirty:false,token:0,
layout:null,layoutTimer:null,layoutToken:0,layoutPending:false,creating:false,requestKey:null,
kind:null,internal:null,internalDirty:false,brands:new Map(),contactToken:0,contactTimer:null};
kind:null,internal:null,internalDirty:false,brands:new Map(),contactToken:0,contactTimer:null,
freights:null,freight:null,catalog:null};
const montarFolderReady=()=>!!FOLDER.handle&&!!FOLDER.granted;
const montarDpi=found=>found.width/(found.widthCm/2.54);
@@ -66,15 +67,138 @@ function montarPaintCustomer(){
}
const montarDelivery=()=>document.querySelector('input[name="montar-delivery"]:checked')?.value||'pickup';
function montarPaintDelivery(){
const withOrder=montarDelivery()==='with_order';
const delivery=montarDelivery(),withOrder=delivery==='with_order',ship=delivery==='ship';
$('montar-with-order').disabled=!withOrder;
if(!withOrder)$('montar-with-order').value='';
$('montar-shipping').hidden=!ship;
if(ship&&!$('montar-ship-recipient').value.trim())
$('montar-ship-recipient').value=$('montar-name').value.trim();
montarPaintFreights();
}
function montarWithOrder(){
if(MONTAR.kind!=='venda'||montarDelivery()!=='with_order')return null;
const value=Math.round(Number($('montar-with-order').value));
return Number.isInteger(value)&&value>=1&&value<=999999?value:null;
}
// ---- Envio (front 7a.4): the Site's own freight ---------------------------
// The Site's public routes for the CEP and the carrier quotes (app/api/health.py);
// the Kanban's api() helper only reaches /api/operator.
// The Site's UFS list (web/site-config.js), copied for the address select.
const MONTAR_UFS='AC AL AP AM BA CE DF ES GO MA MT MS MG PA PB PR PE PI RJ RN RS RO RR SC SP SE TO'.split(' ');
const montarCep=()=>$('montar-ship-cep').value.replace(/\D/g,'').slice(0,8);
function montarDestination(){
const destination={recipient:$('montar-ship-recipient').value.trim(),
street:$('montar-ship-street').value.trim(),number:$('montar-ship-number').value.trim(),
complement:$('montar-ship-complement').value.trim(),
district:$('montar-ship-district').value.trim(),city:$('montar-ship-city').value.trim(),
state:$('montar-ship-state').value.trim().toUpperCase(),postal_code:montarCep()};
const ok=destination.postal_code.length===8&&destination.recipient.length>=2&&
destination.street.length>=2&&destination.number.length>=1&&
destination.district.length>=2&&destination.city.length>=2&&MONTAR_UFS.includes(destination.state);
return ok?destination:null;
}
const montarShipReady=()=>montarDelivery()==='ship'&&!!montarDestination()&&
!!MONTAR.freight&&MONTAR.freight.postal_code===montarCep();
function montarResetFreight(){
MONTAR.freights=null;MONTAR.freight=null;
$('montar-freights').replaceChildren();$('montar-freights').hidden=true;
$('montar-freight-msg').textContent='';
}
async function montarPublic(path,options={}){
const response=await fetch('/api'+path,options);
const data=await response.json().catch(()=>({}));
if(!response.ok)throw new Error(typeof data.detail==='string'?data.detail:'Não foi possível agora ('+response.status+').');
return data;
}
async function montarCepLookup(){
const msg=$('montar-ship-msg'),cep=montarCep();
if(cep.length!==8){msg.textContent='Informe um CEP com oito dígitos.';return;}
msg.textContent='Buscando o endereço…';
try{
const address=await montarPublic('/cep/'+cep);
$('montar-ship-street').value=address.street||'';
$('montar-ship-district').value=address.district||'';
$('montar-ship-city').value=address.city||'';
if(MONTAR_UFS.includes(address.state))$('montar-ship-state').value=address.state;
if(!$('montar-ship-recipient').value.trim())$('montar-ship-recipient').value=$('montar-name').value.trim();
msg.textContent='';MONTAR.requestKey=null;montarPaintActions();
}catch(e){msg.textContent=e.message;}
}
// The item's packed metres and the table value of the items, as the server
// will price them: the band price of the loose-art mode on the billed metres.
function montarQuoteFigures(lines){
const heights=montarGroups(lines).map(group=>{
const cargas=[];
group.sources.forEach((source,sourceIndex)=>{
for(let copyIndex=0;copyIndex<source.copies;copyIndex++)
cargas.push({a:{sourceIndex,giro:0,esp:false},img:source.line.img,copyIndex,
w:source.line.widthCm,h:source.line.heightCm,travado:false});
});
return encaixar(cargas,MONTAR_FILM_CM).altura/100;
});
const catalog=MONTAR.catalog?.avulsa;
if(!catalog)throw new Error('Preço de tabela indisponível agora.');
const billed=heights.map(metres=>Math.max(1,Math.ceil(metres*10)/10));
const total=+billed.reduce((sum,metres)=>sum+metres,0).toFixed(2);
let unit=catalog.unit_cents,best=null;
for(const band of catalog.bands||[]){
const from=Number(band.from_metres);
if(total>=from&&(best===null||from>=best)){best=from;unit=band.unit_cents;}
}
return {metres:+heights.reduce((sum,metres)=>sum+metres,0).toFixed(4),
cents:billed.reduce((sum,metres)=>sum+Math.floor(Number((metres*unit).toFixed(6))),0)};
}
async function montarCatalog(){
if(MONTAR.catalog)return MONTAR.catalog;
const session=await montarPublic('/session');
MONTAR.catalog=session.products||null;
return MONTAR.catalog;
}
async function montarFreightQuote(){
const msg=$('montar-freight-msg'),cep=montarCep();
if(cep.length!==8){msg.textContent='Informe o CEP de entrega primeiro.';return;}
if(!MONTAR.lines.length||!MONTAR.layout||MONTAR.layoutPending){
msg.textContent='Monte a folha antes de cotar o frete.';return;
}
msg.textContent='Cotando o frete…';
const token=MONTAR.layoutToken;
try{
await montarCatalog();
if(token!==MONTAR.layoutToken||montarCep()!==cep)return;
const figures=montarQuoteFigures([...MONTAR.lines]);
const result=await montarPublic('/freight/options',{method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify({postal_code:cep,metres:figures.metres,declared_cents:figures.cents})});
if(token!==MONTAR.layoutToken||montarCep()!==cep)return;
MONTAR.freights=result.options||[];
MONTAR.freight=MONTAR.freights.length?{...MONTAR.freights[0],postal_code:cep}:null;
MONTAR.requestKey=null;
msg.textContent='';montarPaintFreights();montarPaintActions();
}catch(e){
if(token!==MONTAR.layoutToken||montarCep()!==cep)return;
MONTAR.freights=null;MONTAR.freight=null;
$('montar-freights').replaceChildren();$('montar-freights').hidden=true;
msg.textContent=e.message;montarPaintActions();
}
}
function montarPaintFreights(){
const box=$('montar-freights'),options=MONTAR.freights||[];
box.hidden=!options.length;
box.replaceChildren(...options.map(option=>{
const label=node('label',undefined,'montar-freight');
const radio=node('input');radio.type='radio';radio.name='montar-freight';radio.value=option.service;
radio.checked=!!MONTAR.freight&&option.service===MONTAR.freight.service;
radio.onchange=()=>{
MONTAR.freight={...option,postal_code:montarCep()};MONTAR.requestKey=null;montarPaintActions();
};
const meta=node('span',undefined,'montar-freight-meta');
meta.append(node('b',option.description||option.service),
node('span',option.days?'até '+option.days+' dias úteis':'','sub'),
node('em',money(option.total_cents)));
label.append(radio,meta);
return label;
}));
}
// The brand of a stamp, recorded for the future catalogue (Marcus, 10/11):
// only Gestão edits it; everyone who assembles reads it.
async function montarStampBrand(code){
@@ -231,6 +355,7 @@ function montarChanged(){
MONTAR.layout=null;
MONTAR.layoutPending=true;
MONTAR.requestKey=null;
montarResetFreight();
montarPaintLines();
if(!MONTAR.lines.length)montarDrawPreview(null);
clearTimeout(MONTAR.layoutTimer);
@@ -302,6 +427,11 @@ function montarClearCustomer(){
for(const id of MONTAR_CUSTOMER)$(id).value='';
$('montar-customer-q').value='';
$('montar-customer-hits').hidden=true;
for(const id of ['montar-ship-cep','montar-ship-recipient','montar-ship-street','montar-ship-number',
'montar-ship-complement','montar-ship-district','montar-ship-city','montar-ship-state'])
$(id).value='';
$('montar-ship-msg').textContent='';
montarResetFreight();
document.querySelector('input[name="montar-delivery"][value="pickup"]').checked=true;
montarPaintDelivery();
MONTAR.requestKey=null;
@@ -311,13 +441,16 @@ function montarClearCustomer(){
function montarPaintActions(){
const build=$('montar-build');
const customerReady=MONTAR.kind==='interno'?montarInternalReady():montarCustomerFilled();
const deliveryReady=MONTAR.kind!=='venda'||montarDelivery()!=='ship'||montarShipReady();
const ready=!!(MONTAR.lines.length&&MONTAR.layout&&!MONTAR.layoutPending&&
customerReady&&!MONTAR.creating);
customerReady&&deliveryReady&&!MONTAR.creating);
build.disabled=!ready;
build.title=ready?'':(!MONTAR.lines.length?'Monte a folha primeiro.'
:(MONTAR.layoutPending||!MONTAR.layout)?'Aguarde a montagem da folha.'
:MONTAR.kind==='interno'?'Peça à Gestão para completar o cliente interno.'
:'Preencha os dados do cliente.');
:!customerReady?'Preencha os dados do cliente.'
:!deliveryReady?(!montarDestination()?'Preencha o endereço de entrega.':'Cote o frete e escolha uma opção.')
:'');
}
// The Site's grade for loose art (web/site-quality.js): each stamp's DPI over
// the ideal 200, from 6 to 100; the item's is the average of its stamps'.
@@ -345,13 +478,11 @@ function montarItem(sources){
}
// 20 sources and 4000 copies per item; a stamp above 200 copies becomes
// several sources of the same upload, 200 each; items in list order.
function montarItems(lines,uploads){
function montarGroups(lines){
const pool=[];
for(const line of lines){
const uploadId=uploads.get(line.id);
for(const line of lines)
for(let left=line.qty;left>0;left-=200)
pool.push({line,uploadId,copies:Math.min(200,left)});
}
pool.push({line,copies:Math.min(200,left)});
const groups=[];let current=null;
for(const source of pool){
if(!current||current.sources.length>=20||current.copies+source.copies>4000){
@@ -359,7 +490,11 @@ function montarItems(lines,uploads){
}
current.sources.push(source);current.copies+=source.copies;
}
return groups.map(group=>montarItem(group.sources));
return groups;
}
function montarItems(lines,uploads){
return montarGroups(lines).map(group=>montarItem(group.sources.map(source=>
({...source,uploadId:uploads.get(source.line.id)}))));
}
async function montarCreate(){
if(MONTAR.creating)return;
@@ -373,8 +508,18 @@ async function montarCreate(){
if(!montarCustomerFilled())return say('Preencha os dados do cliente.',true);
name=customer.name;
}
if(kind==='venda'&&montarDelivery()==='with_order'&&!montarWithOrder())
return say('Informe o número do pedido de roupa.',true);
let withOrder=null,deliveryFreight=null,destination=null;
if(kind==='venda'&&montarDelivery()==='with_order'){
withOrder=montarWithOrder();
if(!withOrder)return say('Informe o número do pedido de roupa.',true);
}
if(kind==='venda'&&montarDelivery()==='ship'){
destination=montarDestination();
if(!destination)return say('Preencha o endereço de entrega.',true);
if(!MONTAR.freight)return say('Cote o frete e escolha uma opção.',true);
if(MONTAR.freight.postal_code!==montarCep())return say('Cote o frete de novo para este CEP.',true);
deliveryFreight={service:MONTAR.freight.service,postal_code:montarCep()};
}
if(!MONTAR.lines.length)return say('Monte a folha primeiro.',true);
if(!MONTAR.layout||MONTAR.layoutPending)return say('A montagem ainda está sendo calculada.',true);
const lines=[...MONTAR.lines];
@@ -395,8 +540,9 @@ async function montarCreate(){
const body={request_key:MONTAR.requestKey,kind,items:montarItems(lines,uploads)};
if(kind==='venda'){
body.customer=customer;
const withOrder=montarWithOrder();
if(withOrder)body.with_order=withOrder;
if(deliveryFreight)body.freight=deliveryFreight;
if(destination)body.destination=destination;
}
const order=await api('/montador/orders',body);
MONTAR.requestKey=null;
@@ -574,12 +720,16 @@ function montarQueueContacts(){
MONTAR.contactTimer=setTimeout(()=>montarSearchContacts().catch(e=>say(e.message,true)),300);
}
function montarPickContact(contact){
const previous=$('montar-name').value.trim();
$('montar-name').value=contact.name||'';
$('montar-doc').value=contact.document||'';
$('montar-zap').value=contact.phone||'';
$('montar-mail').value=contact.email||'';
$('montar-customer-q').value=contact.name||contact.document||'';
$('montar-customer-hits').hidden=true;
const recipient=$('montar-ship-recipient').value.trim();
if(montarDelivery()==='ship'&&(!recipient||recipient===previous))
$('montar-ship-recipient').value=contact.name||'';
MONTAR.requestKey=null;
montarPaintActions();
const missing=MONTAR_CUSTOMER.find(id=>!$(id).value.trim());
@@ -643,8 +793,31 @@ $('montar-with-order').addEventListener('focus',()=>{
});
$('montar-with-order').addEventListener('input',()=>{MONTAR.requestKey=null;});
for(const radio of document.querySelectorAll('input[name="montar-delivery"]'))
radio.addEventListener('change',()=>{MONTAR.requestKey=null;montarPaintDelivery();});
radio.addEventListener('change',()=>{MONTAR.requestKey=null;montarPaintDelivery();montarPaintActions();});
$('montar-ship-cep').addEventListener('input',()=>{
const digits=$('montar-ship-cep').value.replace(/\D/g,'').slice(0,8);
$('montar-ship-cep').value=digits.length>5?digits.slice(0,5)+'-'+digits.slice(5):digits;
MONTAR.requestKey=null;montarResetFreight();montarPaintActions();
});
$('montar-cep-find').onclick=async()=>{
$('montar-cep-find').disabled=true;
try{await montarCepLookup();}catch(e){say(e.message,true);}
finally{$('montar-cep-find').disabled=false;}
};
$('montar-freight-quote').onclick=async()=>{
$('montar-freight-quote').disabled=true;
try{await montarFreightQuote();}catch(e){say(e.message,true);}
finally{$('montar-freight-quote').disabled=false;}
};
for(const id of ['montar-ship-recipient','montar-ship-street','montar-ship-number',
'montar-ship-complement','montar-ship-district','montar-ship-city'])
$(id).addEventListener('input',()=>{MONTAR.requestKey=null;montarPaintActions();});
$('montar-ship-state').addEventListener('change',()=>{MONTAR.requestKey=null;montarPaintActions();});
document.addEventListener('click',event=>{
if(!event.target.closest('.montar-customer-search'))$('montar-customer-hits').hidden=true;
});
const montarUfPlaceholder=node('option','UF');montarUfPlaceholder.value='';
$('montar-ship-state').append(montarUfPlaceholder,...MONTAR_UFS.map(uf=>{
const option=node('option',uf);option.value=uf;return option;
}));
montarPaintDelivery();

View File

@@ -3,7 +3,7 @@
which defines api, may, money, when, say, node and button.
A price is history: one that has started is never changed or deleted, so
only a scheduled (future) price may be cancelled. */
const SITE_UNIT_LABEL={metro:' /m',pedido:' por pedido'};
const SITE_UNIT_LABEL={metro:' /m',pedido:' por pedido',arte:' por arte'};
// Reais with a comma, as the Site shows them: "19,90" is 1990 cents.
function moneyInputCents(value){
@@ -18,10 +18,11 @@ function moneyInputCents(value){
// A price that already started is refused by the server (409).
const cancelScheduledPrice=id=>api('/site/prices/'+id+'/cancel',{});
// "5" or "5,5": a band's start in metres, as the table reads it.
// "5" or "5,5": a band's start, in metres or arts, as the table reads it.
function bandMetres(value){return String(Number(value)).replace('.',',');}
function bandsText(bands){
return (bands||[]).map(band=>' · '+bandMetres(band.from_metres)+' m: '+money(band.unit_cents)).join('');
function bandsText(bands,unit='metro'){
return (bands||[]).map(band=>' · '+bandMetres(band.from_metres)+' '+
(unit==='arte'?(Number(band.from_metres)===1?'arte':'artes'):'m')+': '+money(band.unit_cents)).join('');
}
function siteProductRow(product){
@@ -66,17 +67,18 @@ function sitePriceBlock(product){
starts.setAttribute('aria-label','Quando o novo preço de '+product.title+' começa');
startsLabel.append(starts);
// Faixas progressivas (front 8.2): a nova tabela começa vazia; as faixas
// viajam com este preço. O tratamento é um valor por pedido, sem faixas.
// viajam com este preço. Ajuste Fino conta as faixas em artes, os produtos em metros.
const bandUnit=product.unit==='arte'?'artes':'m';
const bandRows=node('div',undefined,'siteBandRows');
const addBand=node('button','Adicionar faixa','btn ghost');addBand.type='button';
const paintAdd=()=>{addBand.disabled=bandRows.children.length>=5;};
const bandRow=()=>{
const row=node('div',undefined,'siteBandRow');
const fromLabel=node('label');fromLabel.append(node('span','A partir de (m)'));
const fromLabel=node('label');fromLabel.append(node('span','A partir de ('+bandUnit+')'));
const from=node('input');from.type='text';from.inputMode='decimal';from.className='siteBandFrom';
from.setAttribute('aria-label','Metragem da faixa de '+product.title);
from.setAttribute('aria-label','Início da faixa em '+bandUnit+' de '+product.title);
fromLabel.append(from);
const priceLabel=node('label');priceLabel.append(node('span','R$ por metro'));
const priceLabel=node('label');priceLabel.append(node('span','R$ por '+(product.unit==='arte'?'arte':'metro')));
const bandPrice=node('input');bandPrice.type='text';bandPrice.inputMode='decimal';bandPrice.className='siteBandPrice';
bandPrice.setAttribute('aria-label','Preço da faixa de '+product.title);
priceLabel.append(bandPrice);
@@ -93,7 +95,7 @@ function sitePriceBlock(product){
const from=Number(row.querySelector('.siteBandFrom').value.replace(',','.'));
const unit=moneyInputCents(row.querySelector('.siteBandPrice').value);
if(!Number.isFinite(from)||from<=0||unit===null||unit<=0)
throw new Error('Confira as faixas: metragem e preço maiores que zero.');
throw new Error('Confira as faixas: início e preço maiores que zero.');
return {from_metres:String(from),unit_cents:unit};
});
const save=button('Salvar',async()=>{
@@ -103,18 +105,17 @@ function sitePriceBlock(product){
if(whenDate&&Number.isNaN(whenDate.getTime()))throw new Error('Data inválida.');
await api('/site/products/'+product.id+'/prices',
{unit_cents:cents,starts_at:whenDate?whenDate.toISOString():null,
bands:product.id==='tratamento'?[]:formBands()});
bands:formBands()});
say(whenDate?'Preço salvo para '+when(whenDate)+'.':'Preço salvo. Vale a partir de agora.');
await loadSiteAdmin();
},'btn pri');
form.append(priceLabel,startsLabel,save);
if(product.id!=='tratamento')form.append(bands);
form.append(priceLabel,startsLabel,save,bands);
const scheduled=node('div',undefined,'siteScheduled');
if(product.scheduled.length){
for(const row of product.scheduled){
const line=node('div',undefined,'siteScheduledRow');
line.append(node('span',money(row.unit_cents)+SITE_UNIT_LABEL[product.unit]+bandsText(row.bands)+
line.append(node('span',money(row.unit_cents)+SITE_UNIT_LABEL[product.unit]+bandsText(row.bands,product.unit)+
' a partir de '+when(row.starts_at)));
line.append(button('Cancelar',async()=>{
await cancelScheduledPrice(row.id);
@@ -132,7 +133,7 @@ function sitePriceBlock(product){
const body=node('tbody');
for(const row of product.history){
const tr=node('tr');
tr.append(node('td',money(row.unit_cents)+bandsText(row.bands),'nowrap'),node('td',when(row.starts_at),'nowrap'),
tr.append(node('td',money(row.unit_cents)+bandsText(row.bands,product.unit),'nowrap'),node('td',when(row.starts_at),'nowrap'),
node('td',row.created_by),node('td',when(row.created_at),'nowrap'));
body.append(tr);
}
@@ -188,7 +189,7 @@ async function loadGradeRules(){
ensureGradePanel();
const data=await api('/site/grade-rules');
const aviso=gradeRuleRow('Avisar o designer abaixo de',data.aviso);
const tratamento=gradeRuleRow('Exigir o tratamento abaixo de',data.tratamento);
const tratamento=gradeRuleRow('Exigir o Ajuste Fino abaixo de',data.tratamento);
const save=button('Salvar',async()=>{
const avisoValue=aviso.on.checked?Number(aviso.num.value):null;
const tratamentoValue=tratamento.on.checked?Number(tratamento.num.value):null;
@@ -196,14 +197,14 @@ async function loadGradeRules(){
if(value!==null&&(!Number.isInteger(value)||value<1||value>100))
throw new Error('A nota vai de 1 a 100.');
if(avisoValue!==null&&tratamentoValue!==null&&tratamentoValue>avisoValue)
throw new Error('A regra do tratamento precisa ser menor ou igual à do aviso.');
throw new Error('A regra do Ajuste Fino precisa ser menor ou igual à do aviso.');
await api('/site/grade-rules',{aviso:avisoValue,tratamento:tratamentoValue});
say('Regras da nota da arte salvas.');
await loadGradeRules();
},'btn pri');
const children=[aviso.row,tratamento.row];
if(!data.treatment_offered)
children.push(node('p','Ative e dê preço ao Tratamento pelo designer para esta regra valer.','siteGradeWarn'));
children.push(node('p','Ative e dê preço ao Ajuste Fino para esta regra valer.','siteGradeWarn'));
const foot=node('div',undefined,'siteGradeSave');foot.append(save);children.push(foot);
$('site-grade-body').replaceChildren(...children);
}

View File

@@ -1306,6 +1306,22 @@ dialog.viewer::backdrop{background:var(--scrim)}
#tab-montar .montar-radio:has(input[type="radio"]:checked){border-color:var(--acc);color:var(--tx)}
#tab-montar .montar-radio input[type="number"]{width:110px;height:28px;padding:0 8px;border-radius:7px;border:1px solid var(--ln2);background:var(--bg);color:var(--tx);font-family:inherit;font-size:13px}
#tab-montar .montar-radio input[type="number"]:disabled{opacity:.5}
#tab-montar .montar-shipping{margin-top:12px}
#tab-montar .montar-cep{display:flex;align-items:flex-end;gap:10px;flex-wrap:wrap}
#tab-montar .montar-cep .fld{flex:1;min-width:180px}
#tab-montar .montar-cep .btn{height:42px}
#tab-montar #montar-ship-msg,#tab-montar #montar-freight-msg{margin:8px 0 0;padding:0}
#tab-montar #montar-freight-msg{flex:1;min-width:180px}
#tab-montar .montar-ship-fields{margin-top:12px}
#tab-montar .montar-freight-actions{display:flex;align-items:center;gap:12px;margin-top:14px;flex-wrap:wrap}
#tab-montar .montar-freights{display:flex;flex-direction:column;gap:6px;margin-top:10px}
#tab-montar .montar-freight{display:flex;align-items:center;gap:10px;padding:9px 12px;border:1px solid var(--ln2);border-radius:9px;cursor:pointer}
#tab-montar .montar-freight:has(input:checked){border-color:var(--acc)}
#tab-montar .montar-freight input{accent-color:var(--acc)}
#tab-montar .montar-freight-meta{display:flex;flex:1;align-items:baseline;gap:10px;flex-wrap:wrap;min-width:0}
#tab-montar .montar-freight-meta b{font-size:13.5px;font-weight:650}
#tab-montar .montar-freight-meta .sub{font-size:12.5px;color:var(--tx3)}
#tab-montar .montar-freight-meta em{margin-left:auto;font-style:normal;font-weight:650}
#tab-montar .montar-brand{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:8px}
#tab-montar .montar-brand .lbl{font-size:12px;color:var(--tx3)}
#tab-montar .montar-brand b{font-size:13.5px;font-weight:650}

View File

@@ -154,12 +154,33 @@
<p class="phint" id="montar-interno-note" hidden>O cliente fixo dos pedidos internos.</p>
</div>
<div class="montar-delivery" id="montar-delivery">
<h3>Envio</h3>
<h3>Entrega</h3>
<div class="montar-delivery-options">
<label class="montar-radio"><input type="radio" name="montar-delivery" value="pickup" checked> Retirada</label>
<label class="montar-radio"><input type="radio" name="montar-delivery" value="with_order"> Junto com o pedido de roupa nº <input id="montar-with-order" type="number" min="1" max="999999" step="1" inputmode="numeric" disabled></label>
<label class="montar-radio"><input type="radio" name="montar-delivery" value="ship"> Envio</label>
</div>
<div class="montar-shipping" id="montar-shipping" hidden>
<div class="montar-cep">
<label class="fld"><span>CEP de entrega</span><input id="montar-ship-cep" inputmode="numeric" maxlength="9" autocomplete="off" placeholder="00000-000"></label>
<button class="btn" id="montar-cep-find" type="button">Buscar endereço</button>
</div>
<p class="phint" id="montar-ship-msg" role="status"></p>
<div class="montar-customer-fields montar-ship-fields">
<label class="fld"><span>Quem recebe</span><input id="montar-ship-recipient" maxlength="120" autocomplete="off" placeholder="Nome ou empresa"></label>
<label class="fld"><span>Rua / avenida</span><input id="montar-ship-street" maxlength="160" autocomplete="off"></label>
<label class="fld"><span>Número</span><input id="montar-ship-number" maxlength="20" autocomplete="off" placeholder="123 ou S/N"></label>
<label class="fld"><span>Complemento</span><input id="montar-ship-complement" maxlength="80" autocomplete="off"></label>
<label class="fld"><span>Bairro</span><input id="montar-ship-district" maxlength="80" autocomplete="off"></label>
<label class="fld"><span>Cidade</span><input id="montar-ship-city" maxlength="80" autocomplete="off"></label>
<label class="fld"><span>UF</span><select id="montar-ship-state"></select></label>
</div>
<div class="montar-freight-actions">
<button class="btn" id="montar-freight-quote" type="button">Cotar frete</button>
<span class="phint" id="montar-freight-msg" role="status"></span>
</div>
<div class="montar-freights" id="montar-freights" role="radiogroup" aria-label="Opções de entrega" hidden></div>
</div>
<p class="phint">Envio com o frete do Site chega na próxima etapa.</p>
</div>
<div class="montar-actions">
<button class="btn ghost" id="montar-clear" type="button">Limpar lista</button>

View File

@@ -1064,7 +1064,11 @@ function cardFlags(order){
if(redo.length)out.push(['bad','Retrabalho',redo.map(r=>'Retrabalho · '+REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join(' · ')]);
if(live&&s.items.some(mirroredItem))out.push(['warn','Espelhada',MIRROR_NOTE]);
if(waitingContact(order))out.push(['warn','Contato','Aguardando contato: '+order.contact_note+' · '+contactWho(order)]);
if(order.snapshot.treatment)out.push(['warn','Tratamento pago','O designer trata a arte antes de imprimir; prazo +24 h']);
if(order.snapshot.treatment){
const n=Number(order.snapshot.treatment.arts)||1;
out.push(['warn','Ajuste Fino · '+n+(n===1?' arte':' artes'),
'O designer faz o Ajuste Fino antes de imprimir; prazo +24 h']);
}
if(order.proof_parent)out.push(['warn','Prova do #'+order.proof_parent.number,'Card da prova do pedido #'+order.proof_parent.number]);
if(live&&waitingProof(order)&&order.state!=='tra')out.push(['warn','Aguardando prova','Entra na fila com Prova OK no card #'+order.proof_card.number]);
if(live&&proofRejected(order))out.push(['bad','Prova reprovada',order.proof_card.proof_reason+' · '+order.proof_card.proof_decided_by]);
@@ -1611,9 +1615,9 @@ function contractionList(order){
}
function approveParts(order,main=true){
if(order.snapshot.treatment){
const approve=button('Enviar arte tratada',()=>treatDialog(order),'btn lg'+(main?' pri':''));
const approve=button('Enviar arte do Ajuste Fino',()=>treatDialog(order),'btn lg'+(main?' pri':''));
approve.dataset.treat='';
return {text:'Tratamento pago: o designer precisa enviar o PNG tratado de cada item antes da fila.',
return {text:'Ajuste Fino pago: o designer precisa enviar o PNG do Ajuste Fino de cada item antes da fila.',
files:null,approve,extra:[]};
}
const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1;
@@ -1705,8 +1709,8 @@ function nextBox(order){
}
if(st==='rec'||st==='cor'){
if(st==='rec'&&order.snapshot.treatment&&!treatmentDone(order)&&finalDone(order)){
title='Enviar a arte tratada';
note('O tratamento foi pago. Envie o PNG tratado de cada item antes de colocar o pedido na fila.');
title='Enviar a arte do Ajuste Fino';
note('O Ajuste Fino foi pago. Envie o PNG ajustado de cada item antes de colocar o pedido na fila.');
if(may('produce'))main.push(button('Tratar a arte',()=>treatDialog(order),'btn pri lg'));
return composeNext(title,body,main,more);
}
@@ -2403,7 +2407,7 @@ function filesView(order,revisions,view){
// Rework (Dropstar's rules D-02 to D-04). Gestão opens it with its cause,
// which never changes after; an Administrador authorizes or declines it,
// never one they opened. Bad art the customer approved is outside the goal.
const REWORK_CAUSES={impressao:'Falha de impressão',perfil_cor:'Perfil de cor',tratamento:'Erro de tratamento',
const REWORK_CAUSES={impressao:'Falha de impressão',perfil_cor:'Perfil de cor',tratamento:'Erro de Ajuste Fino',
pedido:'Erro de pedido',arte_cliente:'Arte aprovada pelo cliente'};
const REWORK_OUTSIDE='arte_cliente';
function reworkForm(order){

View File

@@ -4,6 +4,77 @@
scope and run top to bottom, exactly as the original did. */
// ── carrinho
let itemAtual=null;
// Ajuste Fino (front 1a): each art may be chosen under its warning, or the
// general switch chooses every art of the paying items.
function artesDoItem(it){
if(it.partes && it.partes.length)
return it.partes.reduce((t,p)=>t+((p.production&&p.production.sources||[]).length),0);
return (it.production&&it.production.sources||[]).length;
}
function artesSelecionadas(aPagar=itensAPagar()){
if(ajusteTudo) return aPagar.reduce((t,it)=>t+artesDoItem(it),0);
return aPagar.reduce((t,it)=>{
if(it.partes && it.partes.length)
return t+it.partes.reduce((s,p)=>s+(p.ajusteSources||[]).length,0);
return t+(it.ajusteSources||[]).length;
},0);
}
// While a product is open, its files are not in the cart yet; the rule must
// still see the arts the customer already checked under their warnings.
function artesEscolhidasNaTela(){
if(!modo) return 0;
return (ehFolha()?folhas:artes).filter(x=>x.ajuste).length;
}
// What the cart snapshot compares: the switch and every chosen source.
function ajusteSnapshot(){
return {tudo:!!ajusteTudo, itens:itensAPagar().map(it=>({
escolhas:it.ajusteSources||[],
partes:(it.partes||[]).map(p=>p.ajusteSources||[])
}))};
}
// A final cart item (after a split sheet becomes its own items) to the pairs.
function tratamentoParaItens(itens){
if(!(TAXA_TRATAMENTO>0)) return false;
if(ajusteTudo) return true;
const pairs=[];
itens.forEach((it,itemIndex)=>{
for(const source of it.ajusteSources||[]) pairs.push([itemIndex,source]);
});
return pairs.length?pairs:false;
}
function materializaAjuste(){
if(!ajusteTudo) return;
ajusteTudo=false;
for(const it of itensAPagar()){
if(it.partes && it.partes.length){
for(const part of it.partes)
part.ajusteSources=Array.from({length:(part.production&&part.production.sources||[]).length},(_,i)=>i);
}else{
it.ajusteSources=Array.from({length:(it.production&&it.production.sources||[]).length},(_,i)=>i);
}
}
for(const x of folhas) x.ajuste=true;
for(const a of artes) a.ajuste=true;
}
function limpaAjuste(){
ajusteTudo=false;
for(const it of itensAPagar()){
it.ajusteSources=[];
for(const part of it.partes||[]) part.ajusteSources=[];
}
for(const x of folhas) x.ajuste=false;
for(const a of artes) a.ajuste=false;
}
// Update the per-art boxes without repainting the list, which would discard
// the item the customer is still building.
function pintaAjusteCheckboxes(){
document.querySelectorAll('[data-ajuste]').forEach(el=>{
const x=folhas[+el.dataset.ajuste]; if(x)el.checked=ajusteTudo||!!x.ajuste;
});
document.querySelectorAll('[data-ajustea]').forEach(el=>{
const a=artes[+el.dataset.ajustea]; if(a)el.checked=ajusteTudo||!!a.ajuste;
});
}
function invalidaItemAtual(){
if(!itemAtual) return;
itemAtual=null;
@@ -31,7 +102,8 @@ function limpaPaineis(){
}
// Front 8.5: when the worst grade of the paying items is below the rule and
// the treatment is offered, the designer's treatment is required.
// Ajuste Fino is offered, it is required. The simple rule the server keeps:
// at least one art must be chosen; with none, the general switch selects all.
function mostraAvisoTratamento(texto){
const box=$('tratamentoBox'); if(!box)return;
let el=$('tratamentoAviso');
@@ -48,12 +120,27 @@ function aplicaTratamento(aPagar){
const required=offered&&rule>0&&worst!==null&&worst<rule;
box.hidden=!offered;
if(!offered){
check.checked=false;check.disabled=false;mostraAvisoTratamento('');
check.checked=false;check.disabled=false;
ajusteTudo=false;
for(const it of aPagar){
it.ajusteSources=[];
for(const part of it.partes||[]) part.ajusteSources=[];
}
for(const x of folhas) x.ajuste=false;
for(const a of artes) a.ajuste=false;
mostraAvisoTratamento('');
}else if(required){
check.checked=true;check.disabled=true;
mostraAvisoTratamento('Sua arte tem nota '+worst+': para imprimir com qualidade, o tratamento pelo designer é obrigatório neste pedido.');
const chosen=!!ajusteTudo || artesSelecionadas(aPagar)>0 || artesEscolhidasNaTela()>0;
if(!chosen){
ajusteTudo=true;
for(const x of folhas) x.ajuste=true;
for(const a of artes) a.ajuste=true;
document.querySelectorAll('[data-ajuste],[data-ajustea]').forEach(el=>{el.checked=true;});
}
check.checked=ajusteTudo;check.disabled=true;
mostraAvisoTratamento('Sua arte tem nota '+worst+': para imprimir com qualidade, o Ajuste Fino é obrigatório neste pedido.');
}else{
check.disabled=false;mostraAvisoTratamento('');
check.checked=ajusteTudo;check.disabled=false;mostraAvisoTratamento('');
}
}
// O carrinho junta itens de produtos diferentes e cobra uma vez só.
@@ -100,7 +187,8 @@ function pintaPedido(){
$('bEsvaziar').hidden = pedido.length+(itemAtual?1:0) < 2;
const itens = aPagar.reduce((t,it)=>t+it.total,0);
const frete = entrega.tipo==='frete' && entrega.cotado ? entrega.valor : 0;
const tratamento=$('fTratamento')?.checked&&TAXA_TRATAMENTO>0?TAXA_TRATAMENTO:0;
const artesAjuste = TAXA_TRATAMENTO>0 ? artesSelecionadas(aPagar) : 0;
const tratamento = artesAjuste ? Math.round(precoAjuste(artesAjuste)*artesAjuste*100)/100 : 0;
const soma = itens + frete + tratamento;
const n = aPagar.length, noCarrinho = pedido.length + (itemAtual?1:0);
$('resLin').innerHTML =
@@ -110,7 +198,8 @@ function pintaPedido(){
'</span><b>'+
(entrega.tipo==='retira' ? '<span style="color:var(--verde-ml)">Grátis</span>'
: entrega.cotado ? rs(frete) : 'a cotar')+'</b></div>'+
(tratamento?'<div class="l"><span>Tratamento da arte · +24 h</span><b>'+rs(tratamento)+'</b></div>':'')+
(tratamento?'<div class="l"><span>Ajuste Fino · '+artesAjuste+(artesAjuste===1?' arte':' artes')+
' · +24 h</span><b>'+rs(tratamento)+'</b></div>':'')+
'<div class="l"><span>Revisão e reencaixe</span>'+
'<b><span style="color:var(--verde-ml)">Grátis</span></b></div>';
$('carrTot').textContent=rs(soma);
@@ -151,6 +240,7 @@ function carrinho(){
'<div class="l" style="color:var(--laranja2)"><span>Revisão e reencaixe</span><b>grátis</b></div>';
$('carrLin').innerHTML=l;
$('atual').style.display='';
const escolhidas=lista=>lista.map((x,i)=>ajusteTudo||x.ajuste?i:null).filter(i=>i!==null);
const sources=(ehFolha()?folhas:artes).map(x=>ehFolha()
? {kind:'sheet',width_cm:x.med?.larg||larguraFilme(),length_cm:+(x.m*100).toFixed(4),
copies:x.rep||1,rotation_degrees:0,mirrored:false,
@@ -175,6 +265,7 @@ function carrinho(){
localFiles:f.artes.map(x=>x.f), fotos:f.artes.map(x=>x.fotoSrc||null),
metros:+(f.layout.height_cm/100).toFixed(4),
production:{version:3,film_width_cm:larguraFilme(),sources:f.artes.map(fonteDaArte),...f.layout},
ajusteSources:escolhidas(f.artes),
residueAccepted:residuosDasArtes(f.artes), ...tracoDoItem(f.artes,f.layout)}));
layout=null;
}else{
@@ -189,6 +280,7 @@ function carrinho(){
arquivos:(ehFolha()?folhas:artes).length,
production:layout?{version:3,film_width_cm:larguraFilme(),sources,...layout}:null,
partes,
...(partes?{}:{ajusteSources:escolhidas(ehFolha()?folhas:artes)}),
qualityStatus:$('ciente').classList.contains('recusa')?'rejected':
$('ciente').classList.contains('on')?'warning':nota===0?'unverified':'ok',
qualityAcknowledged:false,
@@ -210,7 +302,14 @@ function avisaDesfazer(texto,acao){
function fechaDesfazer(){ clearTimeout(desfazerTimer); desfazerAcao=null; $('desfazer').hidden=true; }
addEventListener('dtf-page-changed',fechaDesfazer);
$('desfazerBtn').addEventListener('click',()=>{ const acao=desfazerAcao; fechaDesfazer(); if(acao) acao(); });
$('fTratamento')?.addEventListener('change',()=>pintaPedido());
$('fTratamento')?.addEventListener('change',()=>{
if($('fTratamento').checked) ajusteTudo=true;
else limpaAjuste();
// The art cards show the same choice, one checkbox under each warning; do
// not repaint them, or the item being built is discarded.
pintaAjusteCheckboxes();
pintaPedido();
});
$('bEsvaziar').addEventListener('click',()=>{
const antes=pedido.slice();
pedido=[]; invalidaItemAtual(); pintaPedido();

View File

@@ -66,8 +66,11 @@ const FAIXAS={};
// Folha que alguém abre na mão (CDR, AI, PSD, TIFF): R$ a mais por metro.
// Vem do servidor (/api/session), que cobra o mesmo; zero não soma nada.
let TAXA_MANUAL=0;
// Fixed price of the designer treatment, set by the server (TREATMENT_CENTS).
// Ajuste Fino, per art, set by the server (TREATMENT_CENTS).
let TAXA_TRATAMENTO=0;
// Ajuste Fino for every art of the cart: the general switch, or true when
// the grade rule requires it. Individual choices live on the art objects.
let ajusteTudo=false;
const folhaManual=()=>ehFolha() && folhas.some(x=>!x.med);
const ehFolha=m=>!!MODOS[m||modo].folha;
const precoMetro=m=>PRECO[m||modo];
@@ -79,6 +82,16 @@ function precoNaMetragem(m, metros){
for(const band of bands) if(metros>=Number(band.from_metres) && (!alta || Number(band.from_metres)>=Number(alta.from_metres))) alta=band;
return alta ? alta.unit_cents/100 : PRECO[m];
}
// Ajuste Fino: the price of one art when the order has n arts. Below the first
// band it is the base, then the highest band reached, as app/catalog.py does.
function precoAjuste(n, base = TAXA_TRATAMENTO, bands = FAIXAS.tratamento) {
let price = base, best = null;
for (const band of bands || []) {
const start = Number(band.from_metres);
if (n >= start && (best === null || start >= best)) { best = start; price = band.unit_cents / 100; }
}
return price;
}
// A próxima faixa à frente, para o aviso de quanto falta.
function proximaFaixa(m, metros){
const bands=FAIXAS[m]||[];

View File

@@ -483,6 +483,27 @@ function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
'usou e envie de novo. '+(varios?'Os círculos vermelhos na prévia mostram onde estão.':'O círculo vermelho na prévia mostra onde está.')+
(aceitavel?' Se '+(varios?'os pontos são':'o ponto é')+' da própria arte, marque abaixo.</p>'+aceite:'</p>');
}
// Ajuste Fino (front 1a): under a Prumo warning, the customer may hand this
// art to the designer. One choice per art; the cart has the general switch.
function temAvisoFolha(x){
const a=x.an;
if(!a || a.grande) return false;
return !!(a.fundoChapado || a.residuos || a.dpi<DPI_AVISA ||
(typeof tracoDoArquivo==='function' && typeof mista==='function' && mista(tracoDoArquivo(x))));
}
function temAvisoArte(a){
const an=analiseDaArte(a);
if(!an || an.grande) return false;
return !!(an.fundoChapado || an.residuos || an.dpi<DPI_AVISA ||
(typeof mista==='function' && mista(tracoDaArte(a))));
}
function ajusteLinha(i,attr){
if(!(TAXA_TRATAMENTO>0)) return '';
const marcado=ajusteTudo || (attr==='data-ajuste' ? folhas[i].ajuste : artes[i].ajuste);
return '<label class="aceiteRes ajusteArte"><input type="checkbox" '+attr+'="'+i+'"'+
(marcado?' checked':'')+'>'+
'<span>Quer que um designer resolva? <b>Ajuste Fino</b> — '+rs(TAXA_TRATAMENTO)+'</span></label>';
}
function detalhesDaFolha(a,i,aberto){
const linhas = a.grande
? ['Resolução '+a.dpi+' DPI, lida do arquivo',
@@ -514,6 +535,7 @@ function pintaFolha(){
medida='<div class="repMed"><b>'+n1(x.med.larg)+' × '+n1(x.med.alt)+' cm</b>'+
'<span>'+escapeHTML(extDe(x.f.name))+' · '+fmt(x.f.size)+'</span></div>'+
(a? '<ul class="chips">'+chipsDaFolha(a,residuoAceito(x))+'</ul>'+avisosDaFolha(a,x.f.name,i,residuoAceito(x),true)+
(temAvisoFolha(x)?ajusteLinha(i,'data-ajuste'):'')+
detalhesDaFolha(a,i,x.detAberto) : '')+
// Over 150 MB the browser cannot check a PDF: said before payment, as
// for a file opened by hand (Dropstar, 2026-10-23).
@@ -524,7 +546,7 @@ function pintaFolha(){
'Exportando em <b>PNG</b>, ou num PDF menor, a conferência sai aqui, antes de pagar.</p>' : '')+
(suspeito? '<p class="avisoF"><b>Este PDF passa do tamanho que o formato comporta.</b> '+
'A especificação para em 508 cm e o seu tem '+n1(x.med.alt)+' cm. '+
'Ele abre certo só em quem o gerou — aqui vai precisar de tratamento. '+
'Ele abre certo só em quem o gerou — aqui vai precisar do Ajuste Fino. '+
'Manda em <b>PNG ou TIFF</b>, ou divide em partes de até 5 m, que sai na hora.</p>':'')+
(larga? '<p class="avisoF"><b>Esta folha não roda neste filme.</b> Ela tem '+n1(x.med.larg)+
' cm de largura e o filme aqui tem '+n1(L)+' cm. Não dá para reduzir: '+
@@ -588,6 +610,11 @@ function pintaFolha(){
$('lista').querySelectorAll('[data-residuo]').forEach(el=>el.addEventListener('change',()=>{
folhas[+el.dataset.residuo].residuoAceito=el.checked; pintaFolha();
}));
$('lista').querySelectorAll('[data-ajuste]').forEach(el=>el.addEventListener('change',()=>{
if(ajusteTudo) materializaAjuste();
folhas[+el.dataset.ajuste].ajuste=el.checked;
pintaFolha(); pintaPedido();
}));
$('lista').querySelectorAll('[data-det]').forEach(d=>d.addEventListener('toggle',()=>{
folhas[+d.dataset.det].detAberto=d.open;
}));
@@ -688,7 +715,8 @@ function pintaArtes(){
'<button data-rm="'+i+'" aria-label="Remover '+escapeHTML(a.f.name)+'">'+icone('fechar')+'</button></div>'+
'<div class="repMed">'+medida+'<span>'+(a.px>0? a.px+' × '+a.py+' px · ' : '')+
escapeHTML(extDe(a.f.name))+' · '+fmt(a.f.size)+'</span></div>'+
barra+chips+aviso+dica+
barra+chips+aviso+
(a.cm>0 && (a.src||a.semPrevia) && temAvisoArte(a) ? ajusteLinha(i,'data-ajustea') : '')+dica+
'</div></div>'+
'<div class="cps">'+
'<div class="campo"><label for="cm'+i+'">Largura</label>'+
@@ -715,6 +743,11 @@ function pintaArtes(){
$('lista').querySelectorAll('[data-rm]').forEach(b=>b.addEventListener('click',()=>{artes.splice(+b.dataset.rm,1);pintaArtes();}));
$('lista').querySelectorAll('[data-residuoa]').forEach(el=>el.addEventListener('change',()=>{
artes[+el.dataset.residuoa].residuoAceito=el.checked; pintaArtes();}));
$('lista').querySelectorAll('[data-ajustea]').forEach(el=>el.addEventListener('change',()=>{
if(ajusteTudo) materializaAjuste();
artes[+el.dataset.ajustea].ajuste=el.checked;
pintaArtes(); pintaPedido();
}));
$('lista').querySelectorAll('[data-cm]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.cm].cm=+i.value||0;pintaArtes();}));
$('lista').querySelectorAll('[data-q]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.q].q=Math.max(1,Math.min(200,Math.floor(+i.value||1)));pintaArtes();}));
$('lista').querySelectorAll('[data-cm], [data-q]').forEach(i=>i.addEventListener('input',()=>{