From 38f947d63227ca5334f2431662fda5e845a9c21f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Cau=C3=AA=20Faleiros?=
Date: Thu, 12 Nov 2026 11:05:17 -0300
Subject: [PATCH] feat: Ajuste Fino Redesenho in the cart (Marcus 12/11, slice
R1)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Under each art the Prumo warns about, the customer can choose Ajuste Fino
or Ajuste Fino Redesenho (vectorize or redraw, per art, +48 h, no batch
price). It is a disabled product until Gestão prices it in the Site tab;
the server charges it per chosen art, Tiny gets a DTFIMP.AJF.RED line and
two more business days, the card shows 'Redesenho · N artes' and the
designer gate applies. The preview loop is slice R2.
Co-Authored-By: Claude Opus 5.5 (1M context)
---
app/adapters.py | 14 ++++
app/api/health.py | 4 +
app/api/operator/board.py | 9 ++-
app/api/operator/orders.py | 7 +-
app/api/operator/stats.py | 8 +-
app/api/quotes.py | 3 +-
app/api/site_admin.py | 5 +-
app/cart_pricing.py | 50 +++++++++++--
app/catalog.py | 20 +++--
app/core/models.py | 21 ++++++
.../202611121200_redesign-product.sql | 11 +++
app/printjobs.py | 3 +-
app/quote_review.py | 6 +-
app/runtime.py | 6 ++
app/tiny.py | 17 ++++-
tests/site_admin_test.py | 66 +++++++++++++++-
tests/test_cart_pricing.py | 75 ++++++++++++++++++-
web/checkout.js | 11 +++
web/kanban-site.js | 8 +-
web/kanban.js | 22 ++++--
web/site-cart.js | 70 ++++++++++++++---
web/site-config.js | 2 +
web/site-pdf.js | 51 ++++++++++---
23 files changed, 429 insertions(+), 60 deletions(-)
create mode 100644 app/migrations/202611121200_redesign-product.sql
diff --git a/app/adapters.py b/app/adapters.py
index f8ea3e7..0d538e5 100644
--- a/app/adapters.py
+++ b/app/adapters.py
@@ -198,6 +198,16 @@ class FakeTiny:
{'id': 1002, 'name': 'Maria Souza', 'document': '123.456.789-09',
'email': 'maria.souza@example.test', 'phone': '16988887777'},
]
+ # The code's SKUs, so a payload can be built on the local stack without
+ # asking Tiny: the modes' defaults and the designer services (front 1b).
+ SKUS = {
+ 'DTFIMP.TX.100CM': 8001,
+ **{f'DTFIMP.TX.{cm:04d}CM': 8000 + cm // 10 for cm in range(10, 100, 10)},
+ 'DTFIMP.UV.1MT': 8101, 'DTFIMP.UV.010CM': 8102,
+ 'DTFIMP.TXP.100CM': 8201,
+ **{f'DTFIMP.TXP.{cm:04d}CM': 8200 + cm // 10 for cm in range(10, 100, 10)},
+ 'DTFIMP.AJF.UN': 9001, 'DTFIMP.AJF.RED': 9002,
+ }
def deliver(self, event_key: str, payload: dict) -> dict:
return {'provider': 'fake-tiny', 'reference': f"LOCAL-{payload['number']}",
@@ -206,6 +216,10 @@ class FakeTiny:
def search_contacts(self, query: str) -> list:
return [dict(contact) for contact in self.CONTACTS]
+ def product_id(self, code: str) -> int:
+ """The fake Tiny product id for a SKU code, as the real catalogue does."""
+ return self.SKUS[code]
+
class ObjectStorage(Protocol):
def begin(self, key: str) -> str: ...
def parts(self, key: str, upload_id: str) -> list: ...
diff --git a/app/api/health.py b/app/api/health.py
index 6e505a2..6af7c42 100644
--- a/app/api/health.py
+++ b/app/api/health.py
@@ -42,6 +42,7 @@ def session(request: Request, response: Response):
products = catalog.current(c)
rules = grade_rules.current_rules(c)
treatment = products['tratamento']
+ redesign = products['redesenho']
return {'environment': ENVIRONMENT, 'cart_scope': str(session_id), 'part_bytes': PART_BYTES,
'max_upload_bytes': upload_limit_bytes(), 'payment_provider': payment.name,
'password_recovery': mail.configured(),
@@ -53,6 +54,9 @@ def session(request: Request, response: Response):
'treatment_bands': [{'from_metres': float(band['from_metres']),
'unit_cents': band['unit_cents']}
for band in treatment['bands']] if treatment['enabled'] else [],
+ # Zero keeps Redesenho hidden, as an off product does. One price
+ # per art, never a band (front 1b).
+ 'redesign_cents': redesign['unit_cents'] if redesign['enabled'] else 0,
# The grade rules the Site needs for the treatment requirement
# (front 8.5): {} when nothing is configured.
'grade_rules': rules,
diff --git a/app/api/operator/board.py b/app/api/operator/board.py
index ca2664d..31a0adb 100644
--- a/app/api/operator/board.py
+++ b/app/api/operator/board.py
@@ -8,6 +8,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response
from pydantic import Field
from ... import hotfolder, machines, mail, payments, prumo, receipt, reviews
+from ...cart_pricing import designer_hours
from ...core import db
from ...core.auth import audit, can, operator
from ...core.models import StrictModel
@@ -138,10 +139,10 @@ def assign_late(c, orders, limits):
since = since or order['created_at']
hours = max(0.0, (now - since).total_seconds() / 3600)
limit_hours = float(limit['hours'])
- # A paid treatment gives Art received its extra hours to prepare the art.
- treatment = (order.get('snapshot') or {}).get('treatment') or {}
- if order['state'] == 'rec' and treatment:
- limit_hours += float(treatment.get('hours', 24))
+ # Paid designer work gives Art received its extra hours to prepare the
+ # art: 48 h for a Redesenho, 24 h for the basic Ajuste Fino.
+ if order['state'] == 'rec':
+ limit_hours += designer_hours(order.get('snapshot') or {})
order['state_hours'] = round(hours, 2)
order['limit_hours'] = limit_hours
order['limit_by'] = limit['responsible']
diff --git a/app/api/operator/orders.py b/app/api/operator/orders.py
index 9b07cf1..ab5d884 100644
--- a/app/api/operator/orders.py
+++ b/app/api/operator/orders.py
@@ -9,6 +9,7 @@ from pydantic import Field
from psycopg.types.json import Jsonb
from ... import hotfolder, machine_log, machines, payments, proof, receipt, reviews
+from ...cart_pricing import needs_designer
from ...core import db
from ...core.auth import MOVERS, audit, can, may_move, may_reorder, operator
from ...core.models import Contraction, Move, Resolution, StrictModel, UploadStart
@@ -208,7 +209,7 @@ def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
# que o Prumo gerou entram como finais, e o pai segue para a fila.
# Itens que ainda dependem de preparo manual continuam em Arte
# recebida, com o botão de final disponível.
- if parent['state'] == 'rec' and not parent['snapshot'].get('treatment'):
+ if parent['state'] == 'rec' and not needs_designer(parent['snapshot']):
generated = c.execute('''SELECT p.item_index,p.upload_id FROM dtf_local.print_files p
WHERE p.order_id=%s AND p.status='ready' AND p.upload_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f
@@ -221,7 +222,7 @@ def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
VALUES(%s,%s,%s,%s,'final',%s,'Prumo')''',
(uuid4(), parent['id'], row['upload_id'], row['item_index'],
f'Aprovado pela prova do #{card["number"]}'))
- treatment_clause = f'AND {TREATED}' if parent['snapshot'].get('treatment') else ''
+ treatment_clause = f'AND {TREATED}' if needs_designer(parent['snapshot']) else ''
ready = parent['state'] == 'rec' and all(c.execute(f'''SELECT 1 FROM dtf_local.order_files f
JOIN dtf_local.orders o ON o.id=f.order_id
JOIN dtf_local.uploads u ON u.id=f.upload_id
@@ -495,7 +496,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND {FINAL_OK}''', (uid,)).fetchall()
if {r['item_index'] for r in coverage} != set(range(len(row['snapshot']['items']))):
raise HTTPException(409, 'Aprove os arquivos finais de todos os itens antes de mandar para Arte conferida.')
- if row['snapshot'].get('treatment') and not row['parent_id']:
+ if needs_designer(row['snapshot']) and not row['parent_id']:
treated = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
JOIN dtf_local.orders o ON o.id=f.order_id
JOIN dtf_local.uploads u ON u.id=f.upload_id
diff --git a/app/api/operator/stats.py b/app/api/operator/stats.py
index 95eae47..ab80310 100644
--- a/app/api/operator/stats.py
+++ b/app/api/operator/stats.py
@@ -5,6 +5,7 @@ from decimal import Decimal
from fastapi import APIRouter, Depends, HTTPException, Query
from ... import machines, payments, unpaid
+from ...cart_pricing import designer_hours
from ...core import db
from ...core.auth import operator
from .common import ORIGINS, REAL_ORDER, TREATED, person
@@ -106,7 +107,7 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
late_rows = c.execute(f'''SELECT s.state,
extract(epoch FROM s.until-s.at) - {waited('s.id', 's.at', 's.until')} AS seconds,
(s.until AT TIME ZONE 'America/Sao_Paulo')::date AS day,
- o.snapshot->'treatment' AS treatment
+ o.snapshot->'treatment' AS treatment, o.snapshot->'redesign' AS redesign
FROM ({spans}) s LEFT JOIN dtf_local.orders o ON o.id=s.id WHERE s.until IS NOT NULL''',
period + period).fetchall()
printed = machine_output(c, start, end)
@@ -214,9 +215,8 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
if not limit:
continue
hours = float(limit['hours'])
- treatment = row.get('treatment') or {}
- if row['state'] == 'rec' and treatment:
- hours += float(treatment.get('hours', 24))
+ if row['state'] == 'rec':
+ hours += designer_hours({'treatment': row.get('treatment'), 'redesign': row.get('redesign')})
if row['seconds'] > hours * 3600:
late[row['state']]['count'] += 1
if row['day'] == today:
diff --git a/app/api/quotes.py b/app/api/quotes.py
index 54ed727..5be0c6a 100644
--- a/app/api/quotes.py
+++ b/app/api/quotes.py
@@ -57,7 +57,8 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
cart = cart_pricing.price_cart(
c, draft['items'], names, coupon_code=code,
customer_document=body.customer.cnpj,
- wants_treatment=draft.get('treatment', False))
+ wants_treatment=draft.get('treatment', False),
+ wants_redesign=draft.get('redesign', []))
if reason is not None:
freight.quote(body.freight.service, body.freight.postal_code,
sum(Decimal(i['billed_metres']) for i in cart['items']),
diff --git a/app/api/site_admin.py b/app/api/site_admin.py
index d9e3bd3..73b3bce 100644
--- a/app/api/site_admin.py
+++ b/app/api/site_admin.py
@@ -95,8 +95,11 @@ def toggle_product(product: str, body: SiteProductToggle, user=Depends(can('mana
def schedule_price(product: str, body: SitePriceNew, user=Depends(can('manage'))):
if product not in catalog.PRODUCTS:
raise HTTPException(404, 'Produto não encontrado.')
- if product != 'tratamento' and body.unit_cents <= 0:
+ if product not in ('tratamento', 'redesenho') and body.unit_cents <= 0:
raise HTTPException(422, 'O preço precisa ser maior que zero.')
+ # Redesenho is one price per art: its batch band belongs to the basic only.
+ if product == 'redesenho' and body.bands:
+ raise HTTPException(422, 'O Redesenho não tem faixas de preço.')
bands = checked_bands(product, body.bands)
now = datetime.now(timezone.utc)
starts_at = body.starts_at or now
diff --git a/app/cart_pricing.py b/app/cart_pricing.py
index bd7f985..c672f53 100644
--- a/app/cart_pricing.py
+++ b/app/cart_pricing.py
@@ -43,6 +43,35 @@ def treatment_price(items, choice, offer):
return {'cents': unit * count, 'hours': 24, 'arts': count, 'unit_cents': unit}
+def redesign_price(items, choice, offer):
+ """Ajuste Fino Redesenho for the chosen arts: one price per art, never a
+ band. {} when it is not offered or no art is chosen."""
+ if not offer or not offer.get('enabled') or offer.get('unit_cents', 0) <= 0:
+ return {}
+ arts = chosen_arts(items, choice)
+ if not arts:
+ return {}
+ count = len(arts)
+ unit = offer['unit_cents']
+ return {'cents': unit * count, 'hours': 48, 'arts': count, 'unit_cents': unit}
+
+
+def designer_hours(snapshot):
+ """The extra hours the paid designer work adds to the deadline: 48 h when
+ any art was sent to Redesenho, else 24 h for the basic Ajuste Fino."""
+ if snapshot.get('redesign'):
+ return 48
+ if snapshot.get('treatment'):
+ return 24
+ return 0
+
+
+def needs_designer(snapshot):
+ """Whether a designer must prepare the final PNG before the print queue:
+ a paid Ajuste Fino or Redesenho on any art."""
+ return bool(snapshot.get('treatment') or snapshot.get('redesign'))
+
+
def price_items(items, names, catalog_now, manual_extra):
"""Price the items without a database: price() per item with the product's
base price and the manual extra, bill_splits, then the band of each mode's
@@ -70,13 +99,15 @@ def price_items(items, names, catalog_now, manual_extra):
def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
- wants_treatment=False, treatment_rule=True):
+ wants_treatment=False, wants_redesign=(), treatment_rule=True):
"""Price a cart exactly as an order is charged. Returns
{'items': [priced item dicts], 'items_total': int, 'coupon': dict|None,
- 'treatment': dict, 'treatment_cents': int, 'grade_flags': dict}.
- Raises HTTPException(422) for a product switched off, a required Ajuste
- Fino the cart did not ask for, or a refused coupon.
- `treatment_rule=False` is for the montador, which assembles the sheet."""
+ 'treatment': dict, 'treatment_cents': int, 'redesign': dict,
+ 'redesign_cents': int, 'grade_flags': dict}.
+ Raises HTTPException(422) for a product switched off, a Redesenho not
+ offered, a required designer service the cart did not ask for, or a
+ refused coupon. `treatment_rule=False` is for the montador, which
+ assembles the sheet."""
from fastapi import HTTPException
catalog_now = catalog.current(c)
for item in items:
@@ -89,7 +120,12 @@ def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
if not treatment_rule:
flags.pop('tratamento', None)
treatment = treatment_price(items, wants_treatment, offer)
- if 'tratamento' in flags and not treatment:
+ redesign = redesign_price(items, wants_redesign, catalog_now['redesenho'])
+ if chosen_arts(items, wants_redesign) and not redesign:
+ raise HTTPException(422, 'O Redesenho não está disponível agora.')
+ # The grade rule wants a designer on the art: the stronger Redesenho
+ # satisfies it just as the basic Ajuste Fino does.
+ if 'tratamento' in flags and not treatment and not redesign:
raise HTTPException(422, grade_rules.treatment_message(flags['tratamento']))
coupon = None
if coupon_code:
@@ -99,4 +135,6 @@ def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
'coupon': coupon,
'treatment': treatment,
'treatment_cents': treatment.get('cents', 0),
+ 'redesign': redesign,
+ 'redesign_cents': redesign.get('cents', 0),
'grade_flags': flags}
diff --git a/app/catalog.py b/app/catalog.py
index 94db760..a94fa6a 100644
--- a/app/catalog.py
+++ b/app/catalog.py
@@ -9,7 +9,8 @@ and an approved quote keeps the price it was approved with.
`tratamento` is Ajuste Fino (front 1a): a price per art, with an optional band
by the order's number of arts (front 8.2). It counts as offered only when it is
-switched on and priced above zero.
+switched on and priced above zero. `redesenho` is Ajuste Fino Redesenho (front
+1b): one price per art, no bands, and the same rule for being offered.
A price row may carry bands by the order's quantity of that product (metres, or
arts for Ajuste Fino): below the first band the base price, then the highest
@@ -20,9 +21,9 @@ from decimal import Decimal
from .core import pricing
-# The modes sold by the metre, and the treatment sold per order.
+# The modes sold by the metre, and the services sold per art.
MODES = ('file', 'avulsa', 'uvfile', 'uv', 'premium')
-PRODUCTS = (*MODES, 'tratamento')
+PRODUCTS = (*MODES, 'tratamento', 'redesenho')
TITLES = {
'file': 'Têxtil folha pronta',
@@ -31,14 +32,21 @@ TITLES = {
'uv': 'UV artes avulsas',
'premium': 'Têxtil Premium · 8 passadas',
'tratamento': 'Ajuste Fino',
+ 'redesenho': 'Ajuste Fino Redesenho',
}
UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro',
- 'premium': 'metro', 'tratamento': 'arte'}
+ 'premium': 'metro', 'tratamento': 'arte', 'redesenho': 'arte'}
def fallback_cents(product: str) -> int:
- """The price in the code, used until a row in the database takes over."""
- return pricing.treatment_cents() if product == 'tratamento' else pricing.PRICES[product]
+ """The price in the code, used until a row in the database takes over.
+ Redesenho has no price in the code: it starts disabled and unpriced, and
+ Gestão sets both in the Site tab."""
+ if product == 'tratamento':
+ return pricing.treatment_cents()
+ if product == 'redesenho':
+ return 0
+ return pricing.PRICES[product]
def band_price(base_cents: int, bands: list, quantity: Decimal) -> int:
diff --git a/app/core/models.py b/app/core/models.py
index 66268d1..dae9319 100644
--- a/app/core/models.py
+++ b/app/core/models.py
@@ -277,6 +277,9 @@ class QuoteRequest(StrictModel):
# Ajuste Fino (front 1a): true selects every art of the cart (old carts and
# the grade rule), a list selects [item_index, source_index] arts.
treatment: bool | list[tuple[int, int]] = False
+ # Ajuste Fino Redesenho (front 1b): the arts sent to be redrawn, in the
+ # same [item_index, source_index] identifiers. One service per art.
+ redesign: list[tuple[int, int]] = Field(default_factory=list)
# A coupon code typed at checkout (front 8.3); the server prices it.
coupon: str | None = Field(default=None, max_length=30)
# What the browser measured while the customer built the cart (item 0.12).
@@ -300,6 +303,24 @@ class QuoteRequest(StrictModel):
seen.add((item_index, source_index))
return self
+ @model_validator(mode='after')
+ def redesign_arts_exist(self):
+ seen = set()
+ for item_index, source_index in self.redesign:
+ if (item_index < 0 or source_index < 0 or item_index >= len(self.items)
+ or source_index >= len(self.items[item_index].production.sources)):
+ raise ValueError('Redesenho: arte não encontrada no pedido.')
+ if (item_index, source_index) in seen:
+ raise ValueError('Redesenho: cada arte aparece uma vez.')
+ seen.add((item_index, source_index))
+ # The customer chooses one service per art: basic or Redesenho.
+ if self.treatment is True:
+ if seen:
+ raise ValueError('Escolha Ajuste Fino ou Redesenho para cada arte, não os dois.')
+ elif isinstance(self.treatment, list) and seen & {(i, s) for i, s in self.treatment}:
+ raise ValueError('Escolha Ajuste Fino ou Redesenho para cada arte, não os dois.')
+ return self
+
@model_validator(mode='after')
def destination_matches_freight(self):
if self.freight.service == 'pickup':
diff --git a/app/migrations/202611121200_redesign-product.sql b/app/migrations/202611121200_redesign-product.sql
new file mode 100644
index 0000000..0fcda0f
--- /dev/null
+++ b/app/migrations/202611121200_redesign-product.sql
@@ -0,0 +1,11 @@
+-- Front 1b (Marcus, 2026-11-12): Ajuste Fino Redesenho, a per-art service
+-- beside the basic Ajuste Fino. Created switched OFF and without a price:
+-- Gestão sets both in the Site tab. The products CHECK is the inline
+-- constraint of dtf_local.products.id (products_id_check); widening a list is
+-- a new migration that drops and adds that one constraint (never schema.sql).
+ALTER TABLE dtf_local.products DROP CONSTRAINT IF EXISTS products_id_check;
+ALTER TABLE dtf_local.products ADD CONSTRAINT products_id_check
+ CHECK (id IN ('file','avulsa','uvfile','uv','premium','tratamento','redesenho'));
+
+INSERT INTO dtf_local.products(id, enabled) VALUES ('redesenho', false)
+ON CONFLICT (id) DO NOTHING;
diff --git a/app/printjobs.py b/app/printjobs.py
index bf9fa7e..2e6c5b3 100644
--- a/app/printjobs.py
+++ b/app/printjobs.py
@@ -32,6 +32,7 @@ from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
from psycopg.types.json import Jsonb
from PIL import Image
+from .cart_pricing import needs_designer
from .core.auth import audit
from .core.db import connect
from .printfile import Unsupported
@@ -177,7 +178,7 @@ def render_one(storage):
source_ids = [source['id']]
item = {**item, 'uploads': [str(source['id'])]}
job['proof_fallback'] = True
- elif job['snapshot'].get('treatment'):
+ elif needs_designer(job['snapshot']):
job['wait_for_treatment'] = True
uploads = c.execute('''SELECT id,name,size,object_key,scan_state,purged_at,expires_at,
(expires_at<=now()) AS expired FROM dtf_local.uploads WHERE id=ANY(%s)''',
diff --git a/app/quote_review.py b/app/quote_review.py
index 5540171..efae981 100644
--- a/app/quote_review.py
+++ b/app/quote_review.py
@@ -75,6 +75,7 @@ def approve(c, row, items, reviewer):
coupon_code=draft.get('coupon'),
customer_document=(draft.get('customer') or {}).get('cnpj'),
wants_treatment=draft.get('treatment', False),
+ wants_redesign=draft.get('redesign', []),
treatment_rule=not draft.get('montador'))
# Keep the review snapshot's own fields with each priced item.
priced = cart['items']
@@ -100,6 +101,7 @@ def approve(c, row, items, reviewer):
discount = coupon['discount_cents'] if coupon else 0
flags = cart['grade_flags']
treatment = cart['treatment']
+ redesign = cart['redesign']
metres = sum(Decimal(i['billed_metres']) for i in priced)
try:
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
@@ -112,6 +114,8 @@ def approve(c, row, items, reviewer):
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
# Ajuste Fino: per art, with the row's band (front 1a).
**({'treatment': treatment} if treatment else {}),
+ # Ajuste Fino Redesenho: per art, one price, 48 h (front 1b).
+ **({'redesign': redesign} if redesign else {}),
# The art grade decision stored with the quote (front 8.5).
**({'grade_flags': flags} if flags else {}),
# The coupon used, for the order card, Números and Tiny (front 8.3).
@@ -119,7 +123,7 @@ def approve(c, row, items, reviewer):
# Browser timings are kept for Números, never for the price (0.12).
**({'timings': draft['timings']} if draft.get('timings') else {}),
'total_cents': items_total - discount + quoted_freight['total_cents']
- + treatment.get('cents', 0)}
+ + treatment.get('cents', 0) + redesign.get('cents', 0)}
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
(Jsonb(approved), reviewer, row['id']))
# Approved and payable now: the files wait for the payment, not for ever.
diff --git a/app/runtime.py b/app/runtime.py
index 798d038..6fd0997 100644
--- a/app/runtime.py
+++ b/app/runtime.py
@@ -145,11 +145,17 @@ def quote_view(c, row, order=None, attempt=None, known=False):
from .cart_pricing import treatment_price
treatment = treatment_price(items, (row['draft'] or {}).get('treatment'),
catalog.current(c)['tratamento']) or None
+ redesign = (row['approved'] or {}).get('redesign')
+ if not redesign and (row['draft'] or {}).get('redesign'):
+ from .cart_pricing import redesign_price
+ redesign = redesign_price(items, (row['draft'] or {}).get('redesign'),
+ catalog.current(c)['redesenho']) or None
return {'id': row['id'], 'created_at': row['created_at'],
'draft': row['draft'], 'approved': row['approved'],
'expires_at': expires_at.isoformat() if expires_at else None,
'expired_at': row['expired_at'].isoformat() if row.get('expired_at') else None,
'prumo': prumo.customer_summary(items), 'treatment': treatment,
+ 'redesign': redesign,
'status': 'paid' if order else 'discarded' if row.get('discarded_at') else 'expired' if expired
else 'approved' if row['approved'] else 'pending_review',
'auto_approved': row.get('reviewed_by') == 'auto',
diff --git a/app/tiny.py b/app/tiny.py
index 3c7c916..5628f97 100644
--- a/app/tiny.py
+++ b/app/tiny.py
@@ -558,6 +558,19 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
'valorUnitario': money(unit),
'infoAdicional': 'Ajuste Fino · '+str(arts)+
(' arte' if arts == 1 else ' artes')+' · +24 h'})
+ redesign = order.get('redesign') or {}
+ if redesign.get('cents'):
+ # Ajuste Fino Redesenho (front 1b): per art, resolved by its SKU code,
+ # one price (never a band), 48 h. Empty setting means the default code.
+ if product_id is None:
+ raise TinyError('TINY_SKU_REDESIGN needs the SKU looked up in Tiny')
+ code = os.environ.get('TINY_SKU_REDESIGN', '').strip() or 'DTFIMP.AJF.RED'
+ arts = int(redesign.get('arts') or 1)
+ unit = int(redesign.get('unit_cents') or redesign['cents'])
+ items.append({'produto': {'id': product_id(code)}, 'quantidade': arts,
+ 'valorUnitario': money(unit),
+ 'infoAdicional': 'Ajuste Fino Redesenho · '+str(arts)+
+ (' arte' if arts == 1 else ' artes')+' · +48 h'})
freight = order['freight']
service = freight.get('service')
pickup = service == 'pickup'
@@ -579,7 +592,9 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
# The carrier's time already counts production; a pickup is ready after it.
days = freight.get('days') if not pickup else int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0)
if days is not None:
- days = int(days) + (1 if treatment.get('cents') else 0)
+ # Redesenho adds 48 h (two working days); the basic adds one.
+ extra = 2 if redesign.get('cents') else 1 if treatment.get('cents') else 0
+ days = int(days) + extra
pedido['dataPrevista'] = business_days_after(day, days).isoformat()
# Paid at once, in full, as the store's orders: one parcel on the day.
pedido['pagamento'] = {'categoria': {'id': CATEGORIES.get(payload.get('origin'), CATEGORY)}}
diff --git a/tests/site_admin_test.py b/tests/site_admin_test.py
index 14ef8b5..cb7aa53 100644
--- a/tests/site_admin_test.py
+++ b/tests/site_admin_test.py
@@ -13,6 +13,7 @@ from uuid import uuid4
from PIL import Image, ImageDraw
from app import tiny
+from app.adapters import FakeTiny
from app.core import db
from tests.print_file_test import artwork
from tests.smoke_test import Client, item_spec, upload_bytes
@@ -20,6 +21,7 @@ from tests.smoke_test import Client, item_spec, upload_bytes
PASSWORD = 'senha-de-teste-123'
UV = 'uv'
PREMIUM = 'premium'
+REDESIGN = 'redesenho'
def premium_sheet():
@@ -61,11 +63,11 @@ def run():
manager.call('/session')
manager.call('/operator/me', operator=True)
manager = manager.operator_client
- prices, user, treatment_enabled = [], None, None
+ prices, user, treatment_enabled, redesign_enabled = [], None, None, None
try:
products = manager.call('/operator/site/products')['products']
assert {product['id'] for product in products} == \
- {'file', 'avulsa', 'uvfile', 'uv', 'premium', 'tratamento'}
+ {'file', 'avulsa', 'uvfile', 'uv', 'premium', 'tratamento', REDESIGN}
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).
@@ -128,6 +130,62 @@ def run():
{'produto': {'id': 105}, 'quantidade': 3, 'valorUnitario': 9.9,
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}], pedido['itens']
+ # Front 1b: Ajuste Fino Redesenho, one price per art, never a band.
+ redesign = next(product for product in products if product['id'] == REDESIGN)
+ redesign_enabled = redesign['enabled']
+ assert redesign['enabled'] is False, redesign
+ assert redesign['title'] == 'Ajuste Fino Redesenho', redesign
+ assert redesign['unit'] == 'arte', redesign
+ manager.call(f'/operator/site/products/{REDESIGN}', {'enabled': True})
+ # Enabled but still unpriced: the Site hides it and the server refuses it.
+ refused = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
+ 'items': [arts], 'redesign': [[0, 0]], 'freight': {'service': 'pickup'}}, expected=422)
+ assert refused['detail'] == 'O Redesenho não está disponível agora.', refused
+ banded = manager.call(f'/operator/site/products/{REDESIGN}/prices', {
+ 'unit_cents': 2990,
+ 'bands': [{'from_metres': '10', 'unit_cents': 690}]}, expected=422)
+ assert 'faixas' in banded['detail'], banded
+ made = manager.call(f'/operator/site/products/{REDESIGN}/prices', {'unit_cents': 2990})
+ prices.append(made['id'])
+ assert client.call('/session')['redesign_cents'] == 2990
+ two = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
+ 'items': [arts], 'redesign': [[0, 0], [0, 1]], 'freight': {'service': 'pickup'}})
+ assert two['status'] == 'approved', two
+ redesenho = client.call('/quotes/' + two['id'])['approved']
+ assert redesenho['redesign'] == {'cents': 5980, 'hours': 48, 'arts': 2,
+ 'unit_cents': 2990}, redesenho
+ assert redesenho['total_cents'] == redesenho['items'][0]['total_cents'] + 5980, redesenho
+ # Basic and Redesenho on different arts: each priced on its own service,
+ # and the basic band counts only the basic arts.
+ mixed = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
+ 'items': [arts], 'treatment': [[0, 0], [0, 1], [0, 2]],
+ 'redesign': [[0, 3], [0, 4]], 'freight': {'service': 'pickup'}})
+ mixed = client.call('/quotes/' + mixed['id'])['approved']
+ assert mixed['treatment'] == {'cents': 2970, 'hours': 24, 'arts': 3,
+ 'unit_cents': 990}, mixed
+ assert mixed['redesign'] == {'cents': 5980, 'hours': 48, 'arts': 2,
+ 'unit_cents': 2990}, mixed
+ assert mixed['total_cents'] == mixed['items'][0]['total_cents'] + 2970 + 5980, mixed
+ # Tiny: the line resolves DTFIMP.AJF.RED through the fake catalogue.
+ fake = FakeTiny()
+ pedido = tiny.order_payload({'order_id': two['id'], 'order': redesenho,
+ 'number': 2, 'payment': {}, 'origin': 'site'}, 777,
+ date(2026, 11, 12), product_id=fake.product_id)
+ red_code = fake.product_id('DTFIMP.AJF.RED')
+ assert [line for line in pedido['itens'] if line['produto']['id'] == red_code] == [
+ {'produto': {'id': red_code}, 'quantidade': 2, 'valorUnitario': 29.9,
+ 'infoAdicional': 'Ajuste Fino Redesenho · 2 artes · +48 h'}], pedido['itens']
+ # One service per art: a pair in both lists is refused by the model.
+ both = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
+ 'items': [arts], 'treatment': [[0, 0]], 'redesign': [[0, 0]],
+ 'freight': {'service': 'pickup'}}, expected=422)
+ assert 'Escolha Ajuste Fino ou Redesenho' in str(both['detail']), both
+ # Switched off again, a chosen Redesenho is refused.
+ manager.call(f'/operator/site/products/{REDESIGN}', {'enabled': False})
+ refused = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
+ 'items': [arts], 'redesign': [[0, 0]], 'freight': {'service': 'pickup'}}, expected=422)
+ assert refused['detail'] == 'O Redesenho não está disponível agora.', refused
+
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}
@@ -214,6 +272,7 @@ def run():
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, prices Ajuste Fino per art with its band,'
+ ' prices Redesenho per art without bands and sends it to Tiny,'
' schedules and cancels prices, charges the new price, and refuses a non-manage profile')
finally:
with db.connect() as c:
@@ -221,6 +280,9 @@ def run():
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 redesign_enabled is not None:
+ c.execute("UPDATE dtf_local.products SET enabled=%s WHERE id=%s",
+ (redesign_enabled, REDESIGN))
if treatment_enabled is not None:
try:
manager.call('/operator/site/products/tratamento', {'enabled': treatment_enabled})
diff --git a/tests/test_cart_pricing.py b/tests/test_cart_pricing.py
index 62b0df3..033dd74 100644
--- a/tests/test_cart_pricing.py
+++ b/tests/test_cart_pricing.py
@@ -8,10 +8,21 @@ extra. app/cart_pricing.price_items must return exactly the same list.
import unittest
from decimal import Decimal
+from uuid import uuid4
+
from app import catalog
-from app.cart_pricing import price_items, treatment_price
+from app.cart_pricing import (designer_hours, needs_designer, price_items,
+ redesign_price, treatment_price)
from app.core import pricing
+try:
+ from pydantic import ValidationError
+ from app.core.models import QuoteRequest
+except ImportError:
+ # The validate job runs this file on the host, without the runtime image's
+ # dependencies; the runtime suites exercise the model there.
+ QuoteRequest = ValidationError = None
+
BASE = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990}
UV_BANDS = [{'from_metres': '5', 'unit_cents': 8000},
@@ -24,6 +35,7 @@ def catalog_now(bands=None, prices=None):
now = {mode: {'enabled': True, 'unit_cents': prices[mode],
'bands': bands.get(mode, [])} for mode in BASE}
now['tratamento'] = {'enabled': True, 'unit_cents': 1000, 'bands': []}
+ now['redesenho'] = {'enabled': True, 'unit_cents': 2990, 'bands': []}
return now
@@ -171,6 +183,67 @@ class CartPricingCharacterizationTest(unittest.TestCase):
self.assertEqual(treatment_price(items, [], offer), {})
self.assertEqual(treatment_price(items, True, {**offer, 'enabled': False}), {})
+ def test_redesenho_is_per_art_never_a_band(self):
+ # Front 1b: R$ 29,90 per art, and the basic batch band never applies.
+ offer = {'enabled': True, 'unit_cents': 2990,
+ 'bands': [{'from_metres': '10', 'unit_cents': 690}]}
+ items = [item('file', '1', uid='u1'), item('file', '1', uid='u2')]
+ self.assertEqual(redesign_price(items, [[0, 0], [1, 0]], offer),
+ {'cents': 5980, 'hours': 48, 'arts': 2, 'unit_cents': 2990})
+ self.assertEqual(redesign_price(items, [], offer), {})
+ self.assertEqual(redesign_price(items, [[0, 0]], {**offer, 'enabled': False}), {})
+ self.assertEqual(redesign_price(items, [[0, 0]], {**offer, 'unit_cents': 0}), {})
+
+ def test_the_basic_band_counts_only_basic_arts(self):
+ offer = {'enabled': True, 'unit_cents': 990,
+ 'bands': [{'from_metres': '10', 'unit_cents': 690}]}
+ items = [item('avulsa', '1', uid=f'u{index}') for index in range(10)]
+ basic = [[index, 0] for index in range(9)]
+ self.assertEqual(treatment_price(items, basic, offer),
+ {'cents': 8910, 'hours': 24, 'arts': 9, 'unit_cents': 990})
+ redesign = redesign_price(items, [[9, 0]], offer={**offer, 'unit_cents': 2990})
+ self.assertEqual(redesign['arts'], 1)
+
+ def test_designer_helpers_read_both_services(self):
+ self.assertEqual(designer_hours({}), 0)
+ self.assertEqual(designer_hours({'treatment': {'cents': 990}}), 24)
+ self.assertEqual(designer_hours({'redesign': {'cents': 2990}}), 48)
+ self.assertEqual(designer_hours({'treatment': {'cents': 990},
+ 'redesign': {'cents': 2990}}), 48)
+ self.assertFalse(needs_designer({}))
+ self.assertTrue(needs_designer({'treatment': {'cents': 990}}))
+ self.assertTrue(needs_designer({'redesign': {'cents': 2990}}))
+
+ @unittest.skipUnless(QuoteRequest, 'pydantic is only in the runtime image')
+ def test_a_pair_cannot_be_basic_and_redesenho(self):
+ def quote(treatment=None, redesign=None, items=1):
+ entries = []
+ for _ in range(items):
+ uid = str(uuid4())
+ data = item('avulsa', '1', uid=uid)
+ data['production']['placements'] = [{
+ 'source_index': 0, 'copy_index': 0, 'x_cm': 0, 'y_cm': 0,
+ 'width_cm': 10, 'length_cm': 10, 'rotation_degrees': 0, 'mirrored': False}]
+ entries.append(data)
+ payload = {'request_key': str(uuid4()),
+ 'customer': {'cnpj': '11222333000181', 'zap': '11999999999',
+ 'mail': 'arte@example.test'},
+ 'items': entries, 'freight': {'service': 'pickup'}}
+ if treatment is not None:
+ payload['treatment'] = treatment
+ if redesign is not None:
+ payload['redesign'] = redesign
+ return payload
+ QuoteRequest.model_validate(quote(treatment=[[0, 0]], redesign=[[1, 0]], items=2))
+ with self.assertRaises(ValidationError):
+ QuoteRequest.model_validate(quote(treatment=[[0, 0]], redesign=[[0, 0]]))
+ with self.assertRaises(ValidationError):
+ QuoteRequest.model_validate(quote(treatment=True, redesign=[[0, 0]]))
+ with self.assertRaises(ValidationError):
+ QuoteRequest.model_validate(quote(redesign=[[0, 0], [0, 0]]))
+ with self.assertRaises(ValidationError):
+ QuoteRequest.model_validate(quote(redesign=[[1, 0]]))
+
if __name__ == '__main__':
unittest.main()
diff --git a/web/checkout.js b/web/checkout.js
index 97fd19f..454d9a0 100644
--- a/web/checkout.js
+++ b/web/checkout.js
@@ -102,6 +102,9 @@
// same amount and the 24 h to the quote.
TAXA_TRATAMENTO=(session.treatment_cents||0)/100;
FAIXAS.tratamento=session.treatment_bands||[];
+ // Ajuste Fino Redesenho (front 1b): one price per art, no band, only
+ // offered when the server prices it above zero.
+ TAXA_REDESENHO=(session.redesign_cents||0)/100;
const tratamentoBox=document.getElementById('tratamentoBox');
if(tratamentoBox){
tratamentoBox.hidden=!(TAXA_TRATAMENTO>0);
@@ -199,6 +202,11 @@
rows.push(linha('Ajuste Fino'+(arts?' · '+arts+(arts===1?' arte':' artes'):'')+' · +24 h',
rs(quote.treatment.cents/100)));
}
+ if(quote.redesign?.cents){
+ const arts=Number(quote.redesign.arts)||0;
+ rows.push(linha('Ajuste Fino Redesenho'+(arts?' · '+arts+(arts===1?' arte':' artes'):'')+' · +48 h',
+ rs(quote.redesign.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'));
@@ -500,6 +508,9 @@
// Ajuste Fino: true for every art, or the [item, source] pairs chosen.
const treatment=tratamentoParaItens(sheets);
if (treatment) content.treatment = treatment;
+ // Ajuste Fino Redesenho: the [item, source] pairs chosen, one per art.
+ const redesign=redesenhoParaItens(sheets);
+ if (redesign) content.redesign = redesign;
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/kanban-site.js b/web/kanban-site.js
index fd5e4e4..3052eca 100644
--- a/web/kanban-site.js
+++ b/web/kanban-site.js
@@ -67,7 +67,9 @@ 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. Ajuste Fino conta as faixas em artes, os produtos em metros.
+ // viajam com este preço. Ajuste Fino conta as faixas em artes, os produtos em
+ // metros. O Redesenho tem um preço único por arte, nunca faixas (front 1b).
+ const permiteFaixas=product.id!=='redesenho';
const bandUnit=product.unit==='arte'?'artes':'m';
const bandRows=node('div',undefined,'siteBandRows');
const addBand=node('button','Adicionar faixa','btn ghost');addBand.type='button';
@@ -105,11 +107,11 @@ 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:formBands()});
+ bands:permiteFaixas?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,bands);
+ form.append(priceLabel,startsLabel,save,...(permiteFaixas?[bands]:[]));
const scheduled=node('div',undefined,'siteScheduled');
if(product.scheduled.length){
diff --git a/web/kanban.js b/web/kanban.js
index ad48508..c8f4551 100644
--- a/web/kanban.js
+++ b/web/kanban.js
@@ -1069,6 +1069,11 @@ function cardFlags(order){
out.push(['warn','Ajuste Fino · '+n+(n===1?' arte':' artes'),
'O designer faz o Ajuste Fino antes de imprimir; prazo +24 h']);
}
+ if(order.snapshot.redesign){
+ const n=Number(order.snapshot.redesign.arts)||1;
+ out.push(['warn','Redesenho · '+n+(n===1?' arte':' artes'),
+ 'O designer redesenha ou vetoriza a arte antes de imprimir; prazo +48 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]);
@@ -1614,10 +1619,11 @@ function contractionList(order){
return box;
}
function approveParts(order,main=true){
- if(order.snapshot.treatment){
- const approve=button('Enviar arte do Ajuste Fino',()=>treatDialog(order),'btn lg'+(main?' pri':''));
+ if(designerPaid(order)){
+ const label=order.snapshot.redesign?'Ajuste Fino Redesenho':'Ajuste Fino';
+ const approve=button('Enviar arte do '+label,()=>treatDialog(order),'btn lg'+(main?' pri':''));
approve.dataset.treat='';
- return {text:'Ajuste Fino pago: o designer precisa enviar o PNG do Ajuste Fino de cada item antes da fila.',
+ return {text:label+' pago: o designer precisa enviar o PNG do '+label+' de cada item antes da fila.',
files:null,approve,extra:[]};
}
const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1;
@@ -1708,9 +1714,10 @@ function nextBox(order){
return composeNext(title,body,main,more);
}
if(st==='rec'||st==='cor'){
- if(st==='rec'&&order.snapshot.treatment&&!treatmentDone(order)&&finalDone(order)){
- 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(st==='rec'&&designerPaid(order)&&!treatmentDone(order)&&finalDone(order)){
+ title='Enviar a arte do '+(order.snapshot.redesign?'Ajuste Fino Redesenho':'Ajuste Fino');
+ note((order.snapshot.redesign?'O Ajuste Fino Redesenho foi pago.':'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);
}
@@ -1857,6 +1864,7 @@ const specialDelivery=s=>s.kind==='interno'?'Interno':s.with_order?'Junto com o
// ---- Final files: the file each item is printed from, approved by an operator.
const finalDone=order=>order.snapshot.items.every((_,index)=>(order.final_items||[]).includes(index));
const treatmentDone=order=>order.snapshot.items.every((_,index)=>order.treated?.items?.includes(index));
+const designerPaid=order=>!!(order.snapshot.treatment||order.snapshot.redesign);
const FINAL_SOURCE={correction:'correção do cliente',generated:'arquivo gerado',original:'original'};
const FINAL_TITLE={correction:'Correção do cliente',generated:'Gerado pelo sistema',original:'Original do cliente'};
// What the system generated for an item: one PNG, or the parts of a film
@@ -2190,7 +2198,7 @@ function treatDialog(order){
if(file)return {file};
const kept=(order.finals||[]).filter(f=>f.item_index===index).map(f=>f.upload_id);
const treated=order.treated?.items?.includes(index);
- return {ids:order.snapshot.treatment&&!treated?[]:
+ return {ids:designerPaid(order)&&!treated?[]:
kept.length?kept:ready[index]?ready[index].files.map(f=>f.upload_id):[]};
});
if(!plan.some(p=>p.file))throw new Error('Escolha o arquivo tratado.');
diff --git a/web/site-cart.js b/web/site-cart.js
index 4f278d4..59eba79 100644
--- a/web/site-cart.js
+++ b/web/site-cart.js
@@ -4,8 +4,9 @@
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.
+// Ajuste Fino (front 1a) and Ajuste Fino Redesenho (front 1b): each art may
+// be chosen under its warning, or the general switch chooses every art of the
+// paying items for the basic service.
function artesDoItem(it){
if(it.partes && it.partes.length)
return it.partes.reduce((t,p)=>t+((p.production&&p.production.sources||[]).length),0);
@@ -19,17 +20,29 @@ function artesSelecionadas(aPagar=itensAPagar()){
return t+(it.ajusteSources||[]).length;
},0);
}
+function redesenhosSelecionados(aPagar=itensAPagar()){
+ return aPagar.reduce((t,it)=>{
+ if(it.partes && it.partes.length)
+ return t+it.partes.reduce((s,p)=>s+(p.redesenhoSources||[]).length,0);
+ return t+(it.redesenhoSources||[]).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;
}
+function redesenhosEscolhidosNaTela(){
+ if(!modo) return 0;
+ return (ehFolha()?folhas:artes).filter(x=>x.redesenho).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||[])
+ redesenhos:it.redesenhoSources||[],
+ partes:(it.partes||[]).map(p=>({escolhas:p.ajusteSources||[], redesenhos:p.redesenhoSources||[]}))
}))};
}
// A final cart item (after a split sheet becomes its own items) to the pairs.
@@ -42,6 +55,14 @@ function tratamentoParaItens(itens){
});
return pairs.length?pairs:false;
}
+function redesenhoParaItens(itens){
+ if(!(TAXA_REDESENHO>0)) return false;
+ const pairs=[];
+ itens.forEach((it,itemIndex)=>{
+ for(const source of it.redesenhoSources||[]) pairs.push([itemIndex,source]);
+ });
+ return pairs.length?pairs:false;
+}
function materializaAjuste(){
if(!ajusteTudo) return;
ajusteTudo=false;
@@ -53,8 +74,8 @@ function materializaAjuste(){
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;
+ for(const x of folhas){x.ajuste=true;x.redesenho=false;}
+ for(const a of artes){a.ajuste=true;a.redesenho=false;}
}
function limpaAjuste(){
ajusteTudo=false;
@@ -65,6 +86,14 @@ function limpaAjuste(){
for(const x of folhas) x.ajuste=false;
for(const a of artes) a.ajuste=false;
}
+function limpaRedesenho(){
+ for(const it of itensAPagar()){
+ it.redesenhoSources=[];
+ for(const part of it.partes||[]) part.redesenhoSources=[];
+ }
+ for(const x of folhas) x.redesenho=false;
+ for(const a of artes) a.redesenho=false;
+}
// Update the per-art boxes without repainting the list, which would discard
// the item the customer is still building.
function pintaAjusteCheckboxes(){
@@ -74,6 +103,12 @@ function pintaAjusteCheckboxes(){
document.querySelectorAll('[data-ajustea]').forEach(el=>{
const a=artes[+el.dataset.ajustea]; if(a)el.checked=ajusteTudo||!!a.ajuste;
});
+ document.querySelectorAll('[data-redesenho]').forEach(el=>{
+ const x=folhas[+el.dataset.redesenho]; if(x)el.checked=!!x.redesenho;
+ });
+ document.querySelectorAll('[data-redesenhoa]').forEach(el=>{
+ const a=artes[+el.dataset.redesenhoa]; if(a)el.checked=!!a.redesenho;
+ });
}
function invalidaItemAtual(){
if(!itemAtual) return;
@@ -103,7 +138,8 @@ function limpaPaineis(){
// Front 8.5: when the worst grade of the paying items is below the rule and
// 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.
+// at least one art must be chosen, basic or Redesenho; with none, the general
+// switch selects every art for the basic service.
function mostraAvisoTratamento(texto){
const box=$('tratamentoBox'); if(!box)return;
let el=$('tratamentoAviso');
@@ -119,6 +155,7 @@ function aplicaTratamento(aPagar){
const worst=grades.length?Math.min(...grades):null;
const required=offered&&rule>0&&worst!==null&&worst0)) limpaRedesenho();
if(!offered){
check.checked=false;check.disabled=false;
ajusteTudo=false;
@@ -130,7 +167,8 @@ function aplicaTratamento(aPagar){
for(const a of artes) a.ajuste=false;
mostraAvisoTratamento('');
}else if(required){
- const chosen=!!ajusteTudo || artesSelecionadas(aPagar)>0 || artesEscolhidasNaTela()>0;
+ const chosen=!!ajusteTudo || artesSelecionadas(aPagar)>0 || artesEscolhidasNaTela()>0 ||
+ redesenhosSelecionados(aPagar)>0 || redesenhosEscolhidosNaTela()>0;
if(!chosen){
ajusteTudo=true;
for(const x of folhas) x.ajuste=true;
@@ -189,7 +227,14 @@ function pintaPedido(){
const frete = entrega.tipo==='frete' && entrega.cotado ? entrega.valor : 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 artesRedesenho = TAXA_REDESENHO>0 ? redesenhosSelecionados(aPagar) : 0;
+ const redesenho = artesRedesenho ? Math.round(TAXA_REDESENHO*artesRedesenho*100)/100 : 0;
+ // The whole order waits 48 h when any art was sent to Redesenho, else 24 h.
+ const prazoTratamento=document.querySelector('#tratamentoBox .provaOp span');
+ if(prazoTratamento) for(const no of prazoTratamento.childNodes)
+ if(no.nodeType===3) no.textContent=no.textContent.replace(/aumenta em \d+ h/,
+ 'aumenta em '+(artesRedesenho>0?48:24)+' h');
+ const soma = itens + frete + tratamento + redesenho;
const n = aPagar.length, noCarrinho = pedido.length + (itemAtual?1:0);
$('resLin').innerHTML =
'
'+n+(n===1?' item':' itens')+''+rs(itens)+'
'+
@@ -200,6 +245,8 @@ function pintaPedido(){
: entrega.cotado ? rs(frete) : 'a cotar')+''+
(tratamento?'
Ajuste Fino · '+artesAjuste+(artesAjuste===1?' arte':' artes')+
' · +24 h'+rs(tratamento)+'
';
$('carrTot').textContent=rs(soma);
@@ -246,6 +293,7 @@ function carrinho(){
$('carrLin').innerHTML=l;
$('atual').style.display='';
const escolhidas=lista=>lista.map((x,i)=>ajusteTudo||x.ajuste?i:null).filter(i=>i!==null);
+ const redesenhadas=lista=>lista.map((x,i)=>x.redesenho?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,
@@ -271,6 +319,7 @@ function carrinho(){
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),
+ redesenhoSources:redesenhadas(f.artes),
residueAccepted:residuosDasArtes(f.artes), ...tracoDoItem(f.artes,f.layout)}));
layout=null;
}else{
@@ -285,7 +334,8 @@ 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)}),
+ ...(partes?{}:{ajusteSources:escolhidas(ehFolha()?folhas:artes),
+ redesenhoSources:redesenhadas(ehFolha()?folhas:artes)}),
qualityStatus:$('ciente').classList.contains('recusa')?'rejected':
$('ciente').classList.contains('on')?'warning':nota===0?'unverified':'ok',
qualityAcknowledged:false,
@@ -308,7 +358,7 @@ function fechaDesfazer(){ clearTimeout(desfazerTimer); desfazerAcao=null; $('des
addEventListener('dtf-page-changed',fechaDesfazer);
$('desfazerBtn').addEventListener('click',()=>{ const acao=desfazerAcao; fechaDesfazer(); if(acao) acao(); });
$('fTratamento')?.addEventListener('change',()=>{
- if($('fTratamento').checked) ajusteTudo=true;
+ if($('fTratamento').checked){ ajusteTudo=true; limpaRedesenho(); }
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.
diff --git a/web/site-config.js b/web/site-config.js
index 5b7d272..3dcd9ea 100644
--- a/web/site-config.js
+++ b/web/site-config.js
@@ -68,6 +68,8 @@ const FAIXAS={};
let TAXA_MANUAL=0;
// Ajuste Fino, per art, set by the server (TREATMENT_CENTS).
let TAXA_TRATAMENTO=0;
+// Ajuste Fino Redesenho, one price per art, no band (REDESIGN_CENTS).
+let TAXA_REDESENHO=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;
diff --git a/web/site-pdf.js b/web/site-pdf.js
index 5c04dd9..cf2bb97 100644
--- a/web/site-pdf.js
+++ b/web/site-pdf.js
@@ -483,8 +483,9 @@ 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.
'+aceite:'');
}
-// 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.
+// Ajuste Fino (front 1a) and Ajuste Fino Redesenho (front 1b): under a Prumo
+// warning, the customer may hand this art to the designer. One service per
+// art, chosen radio-like; the cart has the general switch for the basic one.
function temAvisoFolha(x){
const a=x.an;
if(!a || a.grande) return false;
@@ -498,11 +499,25 @@ function temAvisoArte(a){
(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 '';
+ const folha=attr==='data-ajuste';
+ const x=folha?folhas[i]:artes[i];
+ const basico=TAXA_TRATAMENTO>0, redesenhado=TAXA_REDESENHO>0;
+ if(!basico && !redesenhado) return '';
+ let linha='';
+ if(basico){
+ const marcado=ajusteTudo || !!x.ajuste;
+ linha+='';
+ }
+ if(redesenhado){
+ const attrRedesenhado=folha?'data-redesenho':'data-redesenhoa';
+ linha+='';
+ }
+ return linha;
}
function detalhesDaFolha(a,i,aberto){
const linhas = a.grande
@@ -612,7 +627,16 @@ function pintaFolha(){
}));
$('lista').querySelectorAll('[data-ajuste]').forEach(el=>el.addEventListener('change',()=>{
if(ajusteTudo) materializaAjuste();
- folhas[+el.dataset.ajuste].ajuste=el.checked;
+ const x=folhas[+el.dataset.ajuste];
+ x.ajuste=el.checked;
+ if(el.checked) x.redesenho=false;
+ pintaFolha(); pintaPedido();
+ }));
+ $('lista').querySelectorAll('[data-redesenho]').forEach(el=>el.addEventListener('change',()=>{
+ if(ajusteTudo) materializaAjuste();
+ const x=folhas[+el.dataset.redesenho];
+ x.redesenho=el.checked;
+ if(el.checked) x.ajuste=false;
pintaFolha(); pintaPedido();
}));
$('lista').querySelectorAll('[data-det]').forEach(d=>d.addEventListener('toggle',()=>{
@@ -745,7 +769,16 @@ function pintaArtes(){
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;
+ const a=artes[+el.dataset.ajustea];
+ a.ajuste=el.checked;
+ if(el.checked) a.redesenho=false;
+ pintaArtes(); pintaPedido();
+ }));
+ $('lista').querySelectorAll('[data-redesenhoa]').forEach(el=>el.addEventListener('change',()=>{
+ if(ajusteTudo) materializaAjuste();
+ const a=artes[+el.dataset.redesenhoa];
+ a.redesenho=el.checked;
+ if(el.checked) a.ajuste=false;
pintaArtes(); pintaPedido();
}));
$('lista').querySelectorAll('[data-cm]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.cm].cm=+i.value||0;pintaArtes();}));