diff --git a/app/api/health.py b/app/api/health.py index 7125a99..d31bd70 100644 --- a/app/api/health.py +++ b/app/api/health.py @@ -47,8 +47,12 @@ def session(request: Request, response: Response): 'password_recovery': mail.configured(), # Per metre on a finished sheet someone opens by hand (app/core/pricing.py). 'manual_extra_cents': manual_extra_cents(), - # Zero keeps the designer's treatment hidden, as an off product does. + # Zero keeps Ajuste Fino hidden, as an off product does. Its bands + # are counted in arts, not metres. 'treatment_cents': treatment['unit_cents'] if treatment['enabled'] else 0, + 'treatment_bands': [{'from_metres': float(band['from_metres']), + 'unit_cents': band['unit_cents']} + for band in treatment['bands']] if treatment['enabled'] else [], # The grade rules the Site needs for the treatment requirement # (front 8.5): {} when nothing is configured. 'grade_rules': rules, diff --git a/app/api/operator/orders.py b/app/api/operator/orders.py index 806fcaa..9b07cf1 100644 --- a/app/api/operator/orders.py +++ b/app/api/operator/orders.py @@ -501,7 +501,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)): JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND {FINAL_OK} AND {TREATED}''', (uid,)).fetchall() if {r['item_index'] for r in treated} != set(range(len(row['snapshot']['items']))): - raise HTTPException(409, 'Tratamento pago: envie e aprove a arte tratada de todos os itens antes de entrar na fila.') + raise HTTPException(409, 'Ajuste Fino pago: envie e aprove a arte do Ajuste Fino de todos os itens antes de entrar na fila.') # Two at most per machine in Imprimindo (app/machines.py). if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)): raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.') diff --git a/app/api/site_admin.py b/app/api/site_admin.py index 70afd32..d9e3bd3 100644 --- a/app/api/site_admin.py +++ b/app/api/site_admin.py @@ -29,21 +29,20 @@ def price_row(row): def checked_bands(product, bands): - """The bands the row will store; 422 in Portuguese for anything invalid.""" - if product == 'tratamento' and bands: - raise HTTPException(422, 'O tratamento é um valor por pedido: não tem faixas.') + """The bands the row will store; 422 in Portuguese for anything invalid. + Ajuste Fino counts its bands in arts; the other products in metres.""" if len(bands) > 5: raise HTTPException(422, 'Um preço pode ter no máximo 5 faixas.') checked, last = [], None for band in bands: if not band.from_metres.is_finite() or band.from_metres <= 0: - raise HTTPException(422, 'A metragem de cada faixa precisa ser maior que zero.') + raise HTTPException(422, 'O início de cada faixa precisa ser maior que zero.') if band.unit_cents <= 0: raise HTTPException(422, 'O preço de cada faixa precisa ser maior que zero.') if band.unit_cents > 10000000: raise HTTPException(422, 'O preço de cada faixa é alto demais.') if last is not None and band.from_metres <= last: - raise HTTPException(422, 'As faixas precisam estar em ordem crescente de metragem.') + raise HTTPException(422, 'As faixas precisam estar em ordem crescente.') last = band.from_metres checked.append({'from_metres': str(band.from_metres), 'unit_cents': band.unit_cents}) return checked @@ -247,7 +246,7 @@ def site_grade_rules(user=Depends(can('manage'))): @router.post('/api/operator/site/grade-rules') def save_grade_rules(body: GradeRules, user=Depends(can('manage'))): if body.aviso is not None and body.tratamento is not None and body.tratamento > body.aviso: - raise HTTPException(422, 'A regra do tratamento precisa ser menor ou igual à do aviso.') + raise HTTPException(422, 'A regra do Ajuste Fino precisa ser menor ou igual à do aviso.') with db.connect() as c: for action, below in (('aviso', body.aviso), ('tratamento', body.tratamento)): if below is None: diff --git a/app/api/stamps.py b/app/api/stamps.py index b683f95..4b64213 100644 --- a/app/api/stamps.py +++ b/app/api/stamps.py @@ -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: diff --git a/app/cart_pricing.py b/app/cart_pricing.py index 96e414b..bd7f985 100644 --- a/app/cart_pricing.py +++ b/app/cart_pricing.py @@ -11,6 +11,38 @@ from . import catalog, coupons, grade_rules from .core import pricing +def art_pairs(items): + """[item_index, source_index] for every art in the cart: one artwork of + loose art, or one sheet file of a ready sheet.""" + return [[index, source] for index, item in enumerate(items) + for source in range(len((item.get('production') or {}).get('sources') or []))] + + +def chosen_arts(items, choice): + """The arts the draft's treatment selects: all of them for True (old carts + and the grade rule), the valid pairs for a list.""" + if choice is True: + return art_pairs(items) + if not isinstance(choice, (list, tuple)): + return [] + valid = {tuple(pair) for pair in art_pairs(items)} + return [list(pair) for pair in choice + if isinstance(pair, (list, tuple)) and len(pair) == 2 and tuple(pair) in valid] + + +def treatment_price(items, choice, offer): + """Ajuste Fino for the chosen arts, with the row's bands counted in arts. + {} when it is not offered or no art is chosen.""" + if not offer or not offer.get('enabled') or offer.get('unit_cents', 0) <= 0: + return {} + arts = chosen_arts(items, choice) + if not arts: + return {} + count = len(arts) + unit = catalog.band_price(offer['unit_cents'], offer.get('bands') or [], count) + return {'cents': unit * count, 'hours': 24, 'arts': count, 'unit_cents': unit} + + def price_items(items, names, catalog_now, manual_extra): """Price the items without a database: price() per item with the product's base price and the manual extra, bill_splits, then the band of each mode's @@ -41,9 +73,9 @@ def price_cart(c, items, names, *, coupon_code=None, customer_document=None, wants_treatment=False, treatment_rule=True): """Price a cart exactly as an order is charged. Returns {'items': [priced item dicts], 'items_total': int, 'coupon': dict|None, - 'treatment_cents': int, 'grade_flags': dict}. - Raises HTTPException(422) for a product switched off, a required treatment - the cart did not ask for, or a refused coupon (the same messages as today). + 'treatment': dict, 'treatment_cents': int, 'grade_flags': dict}. + Raises HTTPException(422) for a product switched off, a required Ajuste + Fino the cart did not ask for, or a refused coupon. `treatment_rule=False` is for the montador, which assembles the sheet.""" from fastapi import HTTPException catalog_now = catalog.current(c) @@ -56,14 +88,15 @@ def price_cart(c, items, names, *, coupon_code=None, customer_document=None, flags = grade_rules.triggered(grade_rules.current_rules(c), priced, offered) if not treatment_rule: flags.pop('tratamento', None) - if 'tratamento' in flags and not wants_treatment: + treatment = treatment_price(items, wants_treatment, offer) + if 'tratamento' in flags and not treatment: raise HTTPException(422, grade_rules.treatment_message(flags['tratamento'])) coupon = None if coupon_code: coupon = coupons.check(c, coupon_code, customer_document, priced) - treatment = offer['unit_cents'] if wants_treatment and offer['enabled'] else 0 return {'items': priced, 'items_total': sum(i['total_cents'] for i in priced), 'coupon': coupon, - 'treatment_cents': treatment, + 'treatment': treatment, + 'treatment_cents': treatment.get('cents', 0), 'grade_flags': flags} diff --git a/app/catalog.py b/app/catalog.py index 867c515..94db760 100644 --- a/app/catalog.py +++ b/app/catalog.py @@ -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: diff --git a/app/core/models.py b/app/core/models.py index 38b0fd5..4026a25 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -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): diff --git a/app/core/pricing.py b/app/core/pricing.py index e190df2..d0aad0e 100644 --- a/app/core/pricing.py +++ b/app/core/pricing.py @@ -25,7 +25,7 @@ def manual_extra_cents() -> int: def treatment_cents() -> int: - """The designer's treatment, a fixed amount per order (front 5). + """Ajuste Fino, a fixed amount per art (front 1a). Zero keeps the option hidden: the price is the client's decision, and the server and the Site read the same `TREATMENT_CENTS`. diff --git a/app/grade_rules.py b/app/grade_rules.py index a104d84..303fb63 100644 --- a/app/grade_rules.py +++ b/app/grade_rules.py @@ -2,8 +2,8 @@ With no rule nothing changes anywhere. An item triggers a rule when its grade is below the rule's `below`; the order's worst item decides. `aviso` flags the -order for the designer; `tratamento` makes the designer's treatment required, -but only while it is offered (enabled and priced above zero). +order for the designer; `tratamento` makes Ajuste Fino required, but only while +it is offered (enabled and priced above zero). """ @@ -29,6 +29,6 @@ def triggered(rules: dict, items, treatment_offered: bool) -> dict: def treatment_message(grade: int) -> str: - """The refusal the customer sees when the treatment is required.""" - return (f'Sua arte tem nota {grade}: para imprimir com qualidade, o tratamento ' - 'pelo designer é obrigatório neste pedido.') + """The refusal the customer sees when Ajuste Fino is required.""" + return (f'Sua arte tem nota {grade}: para imprimir com qualidade, o Ajuste Fino ' + 'é obrigatório neste pedido.') diff --git a/app/printjobs.py b/app/printjobs.py index 1956d39..bf9fa7e 100644 --- a/app/printjobs.py +++ b/app/printjobs.py @@ -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: ' diff --git a/app/quote_review.py b/app/quote_review.py index 20359d4..5540171 100644 --- a/app/quote_review.py +++ b/app/quote_review.py @@ -74,7 +74,7 @@ def approve(c, row, items, reviewer): c, [item.model_dump(mode='json') for item in items], names, coupon_code=draft.get('coupon'), customer_document=(draft.get('customer') or {}).get('cnpj'), - wants_treatment=bool(draft.get('treatment')), + wants_treatment=draft.get('treatment', False), treatment_rule=not draft.get('montador')) # Keep the review snapshot's own fields with each priced item. priced = cart['items'] @@ -99,7 +99,7 @@ def approve(c, row, items, reviewer): coupon = cart['coupon'] discount = coupon['discount_cents'] if coupon else 0 flags = cart['grade_flags'] - treatment = cart['treatment_cents'] + treatment = cart['treatment'] metres = sum(Decimal(i['billed_metres']) for i in priced) try: quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''), @@ -110,15 +110,16 @@ def approve(c, row, items, reviewer): 'destination': draft.get('destination'), # The customer's proof only above 10 m (Dropstar, 2026-10-28). **({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}), - # Designer treatment is one fixed service line (front 5). - **({'treatment': {'cents': treatment, 'hours': 24}} if treatment else {}), + # Ajuste Fino: per art, with the row's band (front 1a). + **({'treatment': treatment} if treatment else {}), # The art grade decision stored with the quote (front 8.5). **({'grade_flags': flags} if flags else {}), # The coupon used, for the order card, Números and Tiny (front 8.3). **({'coupon': coupon} if coupon else {}), # Browser timings are kept for Números, never for the price (0.12). **({'timings': draft['timings']} if draft.get('timings') else {}), - 'total_cents': items_total - discount + quoted_freight['total_cents'] + treatment} + 'total_cents': items_total - discount + quoted_freight['total_cents'] + + treatment.get('cents', 0)} c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s', (Jsonb(approved), reviewer, row['id'])) # Approved and payable now: the files wait for the payment, not for ever. diff --git a/app/runtime.py b/app/runtime.py index 1acee11..798d038 100644 --- a/app/runtime.py +++ b/app/runtime.py @@ -142,9 +142,9 @@ def quote_view(c, row, order=None, attempt=None, known=False): items = (row['approved'] or row['draft']).get('items') or [] treatment = (row['approved'] or {}).get('treatment') if not treatment and (row['draft'] or {}).get('treatment'): - offer = catalog.current(c)['tratamento'] - if offer['enabled'] and offer['unit_cents'] > 0: - treatment = {'cents': offer['unit_cents'], 'hours': 24} + from .cart_pricing import treatment_price + treatment = treatment_price(items, (row['draft'] or {}).get('treatment'), + catalog.current(c)['tratamento']) or None return {'id': row['id'], 'created_at': row['created_at'], 'draft': row['draft'], 'approved': row['approved'], 'expires_at': expires_at.isoformat() if expires_at else None, diff --git a/app/tiny.py b/app/tiny.py index f7cc62c..3c7c916 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -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' diff --git a/tests/grade_rules_test.py b/tests/grade_rules_test.py index 8be6828..6a2be79 100644 --- a/tests/grade_rules_test.py +++ b/tests/grade_rules_test.py @@ -49,17 +49,17 @@ def run(): refused = client.call('/quotes', quote_body(item, False, mail), expected=422) assert refused['detail'] == ('Sua arte tem nota 50: para imprimir com qualidade, ' - 'o tratamento pelo designer é obrigatório neste pedido.'), refused + 'o Ajuste Fino é obrigatório neste pedido.'), refused made = client.call('/quotes', quote_body(item, True, mail)) quote_id = made['id'] assert made['status'] == 'approved', made approved = client.call('/quotes/' + quote_id)['approved'] assert approved['grade_flags'] == {'aviso': 50, 'tratamento': 50}, approved - assert approved['treatment']['cents'] == 1000, approved + assert approved['treatment'] == {'cents': 1000, 'hours': 24, 'arts': 1, + 'unit_cents': 1000}, approved assert approved['total_cents'] == 9990, approved - print('PASS: the grade rule requires the designer treatment and flags the order' - ' with the worst grade') + print('PASS: the grade rule requires Ajuste Fino and flags the order with the worst grade') finally: if rules_set: try: diff --git a/tests/site_admin_test.py b/tests/site_admin_test.py index f8d75bf..14ef8b5 100644 --- a/tests/site_admin_test.py +++ b/tests/site_admin_test.py @@ -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) diff --git a/tests/stamps_test.py b/tests/stamps_test.py index 9b5a12e..6de72e5 100644 --- a/tests/stamps_test.py +++ b/tests/stamps_test.py @@ -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,)) diff --git a/tests/test_cart_pricing.py b/tests/test_cart_pricing.py index 95e91d9..62b0df3 100644 --- a/tests/test_cart_pricing.py +++ b/tests/test_cart_pricing.py @@ -9,7 +9,7 @@ import unittest from decimal import Decimal from app import catalog -from app.cart_pricing import price_items +from app.cart_pricing import price_items, treatment_price from app.core import pricing @@ -156,6 +156,21 @@ class CartPricingCharacterizationTest(unittest.TestCase): floating = priced('band-floating-metres')[0] self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.9', 24650)) + def test_ajuste_fino_is_per_art_with_the_band(self): + # Front 1a: 1 to 9 arts at R$ 9,90, from 10 at R$ 6,90, all arts charged + # at the band. `true` keeps meaning every art of the cart. + offer = {'enabled': True, 'unit_cents': 990, + 'bands': [{'from_metres': '10', 'unit_cents': 690}]} + for arts, unit in ((1, 990), (9, 990), (10, 690), (12, 690)): + items = [item('avulsa', '1', uid=f'u{index}') for index in range(arts)] + self.assertEqual(treatment_price(items, True, offer), + {'cents': unit * arts, 'hours': 24, 'arts': arts, 'unit_cents': unit}) + items = [item('file', '1', uid='u1'), item('file', '1', uid='u2')] + self.assertEqual(treatment_price(items, [[1, 0]], offer), + {'cents': 990, 'hours': 24, 'arts': 1, 'unit_cents': 990}) + self.assertEqual(treatment_price(items, [], offer), {}) + self.assertEqual(treatment_price(items, True, {**offer, 'enabled': False}), {}) + if __name__ == '__main__': unittest.main() diff --git a/tests/test_grade_rules.py b/tests/test_grade_rules.py index ceec3ef..cb0889b 100644 --- a/tests/test_grade_rules.py +++ b/tests/test_grade_rules.py @@ -34,7 +34,7 @@ class GradeRulesTest(unittest.TestCase): def test_treatment_message(self): self.assertEqual( treatment_message(45), - 'Sua arte tem nota 45: para imprimir com qualidade, o tratamento pelo designer ' + 'Sua arte tem nota 45: para imprimir com qualidade, o Ajuste Fino ' 'é obrigatório neste pedido.') diff --git a/tests/test_pricing.py b/tests/test_pricing.py index 784bd3c..e74780e 100644 --- a/tests/test_pricing.py +++ b/tests/test_pricing.py @@ -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}]}} diff --git a/tests/test_tiny.py b/tests/test_tiny.py index 0280510..903f2c7 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -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) diff --git a/tests/treatment_gate_test.py b/tests/treatment_gate_test.py index 4f34170..d264907 100644 --- a/tests/treatment_gate_test.py +++ b/tests/treatment_gate_test.py @@ -24,14 +24,14 @@ def run(): 'note': 'Gerado pelo Prumo'}, operator=True) blocked = client.call('/operator/orders/' + order['id'] + '/move', {'state': 'tra', 'version': approved['version']}, operator=True, expected=409) - assert 'Tratamento pago' in blocked['detail'], blocked + assert 'Ajuste Fino pago' in blocked['detail'], blocked prepared = upload_bytes(client, artwork(), name='LOCAL-TREATMENT-FINAL.png', order_id=order['id']) approved = client.call('/operator/orders/' + order['id'] + '/final-files', {'version': approved['version'], 'files': [{'item_index': 0, 'upload_id': prepared}], 'note': 'PNG tratado pelo designer'}, operator=True) client.call('/operator/orders/' + order['id'] + '/move', {'state': 'tra', 'version': approved['version']}, operator=True) - print('PASS: generated artwork cannot satisfy paid treatment; designer PNG opens the print queue') + print('PASS: generated artwork cannot satisfy paid Ajuste Fino; designer PNG opens the print queue') if __name__ == '__main__': diff --git a/web/checkout.js b/web/checkout.js index 89b3014..84ee1a9 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -27,7 +27,7 @@ stroke:item.strokeClass||null,strokeChoice:item.strokeChoice||null, sheets:(item.partes||[]).map(part=>part.production), files:(item.localFiles||[]).map(file=>({name:file.name,size:file.size,lastModified:file.lastModified})) - })),treatment:!!$('fTratamento')?.checked,coupon:cupomCode()}); + })),treatment:ajusteSnapshot(),coupon:cupomCode()}); } // The quote this browser is paying, forgotten. clearDraft also empties the // payment area; forgetDraft leaves on screen what is there (a confirmation). @@ -90,9 +90,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); @@ -126,6 +128,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); @@ -184,8 +187,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')); @@ -479,7 +485,9 @@ if (destination) content.destination = destination; // "Quero aprovar uma prova antes de imprimir": the order waits for the customer. if ($('fProva')?.checked) content.proof = true; - if ($('fTratamento')?.checked) content.treatment = true; + // Ajuste Fino: true for every art, or the [item, source] pairs chosen. + const treatment=tratamentoParaItens(sheets); + if (treatment) content.treatment = treatment; if (cartSnapshot()!==initialCart) throw new Error('O carrinho mudou durante o envio. Confira os itens e envie de novo.'); // Browser timings for Números (item 0.12); they never affect the price. const T=window.dtfTimings, timings={}; diff --git a/web/index.html b/web/index.html index ad2c9ff..c40bb6c 100644 --- a/web/index.html +++ b/web/index.html @@ -1121,9 +1121,9 @@ h2 em{font-style:normal;color:var(--laranja)}
O cliente fixo dos pedidos internos.
Envio com o frete do Site chega na próxima etapa.
Este PDF passa do tamanho que o formato comporta. '+ '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 PNG ou TIFF, ou divide em partes de até 5 m, que sai na hora.
':'')+ (larga? 'Esta folha não roda neste filme. 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(){ ''+ '