feat: Ajuste Fino priced per art, with the offer under each Prumo warning (Marcus 10/11, point 1)
The designer treatment becomes Ajuste Fino, priced per art with a batch band set in the Site tab (e.g. R$ 9,90, from 10 arts R$ 6,90). Under each art the Prumo warns about, the Site offers 'Quer que um designer resolva? Ajuste Fino'; the cart keeps 'Ajuste Fino em todas as artes'. The server counts the chosen arts, Tiny gets the line with that quantity, the card shows 'Ajuste Fino · N artes'. Old carts asking the treatment for the whole order keep working. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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.')
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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':
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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.')
|
||||
|
||||
@@ -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: '
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
11
app/tiny.py
11
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'
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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.')
|
||||
|
||||
|
||||
|
||||
@@ -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}]}}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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__':
|
||||
|
||||
@@ -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).
|
||||
@@ -80,9 +80,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);
|
||||
@@ -116,6 +118,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);
|
||||
@@ -174,8 +177,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'));
|
||||
@@ -435,7 +441,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={};
|
||||
|
||||
@@ -1121,9 +1121,9 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
</div>
|
||||
|
||||
<div class="cxE" id="tratamentoBox" hidden>
|
||||
<h4>Tratamento da arte</h4>
|
||||
<h4>Ajuste Fino</h4>
|
||||
<label class="provaOp"><input type="checkbox" id="fTratamento">
|
||||
<span><b>Quero o tratamento pelo designer — <span id="tratamentoPreco"></span></b>
|
||||
<span><b>Ajuste Fino em todas as artes — <span id="tratamentoPreco"></span> por arte</b>
|
||||
O designer ajusta a arte para DTF, com fundo transparente e 300 DPI, e sobe o arquivo
|
||||
pelo card. O prazo do pedido aumenta em 24 h.</span></label>
|
||||
</div>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
which defines api, may, money, when, say, node and button.
|
||||
A price is history: one that has started is never changed or deleted, so
|
||||
only a scheduled (future) price may be cancelled. */
|
||||
const SITE_UNIT_LABEL={metro:' /m',pedido:' por pedido'};
|
||||
const SITE_UNIT_LABEL={metro:' /m',pedido:' por pedido',arte:' por arte'};
|
||||
|
||||
// Reais with a comma, as the Site shows them: "19,90" is 1990 cents.
|
||||
function moneyInputCents(value){
|
||||
@@ -18,10 +18,11 @@ function moneyInputCents(value){
|
||||
// A price that already started is refused by the server (409).
|
||||
const cancelScheduledPrice=id=>api('/site/prices/'+id+'/cancel',{});
|
||||
|
||||
// "5" or "5,5": a band's start in metres, as the table reads it.
|
||||
// "5" or "5,5": a band's start, in metres or arts, as the table reads it.
|
||||
function bandMetres(value){return String(Number(value)).replace('.',',');}
|
||||
function bandsText(bands){
|
||||
return (bands||[]).map(band=>' · '+bandMetres(band.from_metres)+' m: '+money(band.unit_cents)).join('');
|
||||
function bandsText(bands,unit='metro'){
|
||||
return (bands||[]).map(band=>' · '+bandMetres(band.from_metres)+' '+
|
||||
(unit==='arte'?(Number(band.from_metres)===1?'arte':'artes'):'m')+': '+money(band.unit_cents)).join('');
|
||||
}
|
||||
|
||||
function siteProductRow(product){
|
||||
@@ -66,17 +67,18 @@ function sitePriceBlock(product){
|
||||
starts.setAttribute('aria-label','Quando o novo preço de '+product.title+' começa');
|
||||
startsLabel.append(starts);
|
||||
// Faixas progressivas (front 8.2): a nova tabela começa vazia; as faixas
|
||||
// viajam com este preço. O tratamento é um valor por pedido, sem faixas.
|
||||
// viajam com este preço. Ajuste Fino conta as faixas em artes, os produtos em metros.
|
||||
const bandUnit=product.unit==='arte'?'artes':'m';
|
||||
const bandRows=node('div',undefined,'siteBandRows');
|
||||
const addBand=node('button','Adicionar faixa','btn ghost');addBand.type='button';
|
||||
const paintAdd=()=>{addBand.disabled=bandRows.children.length>=5;};
|
||||
const bandRow=()=>{
|
||||
const row=node('div',undefined,'siteBandRow');
|
||||
const fromLabel=node('label');fromLabel.append(node('span','A partir de (m)'));
|
||||
const fromLabel=node('label');fromLabel.append(node('span','A partir de ('+bandUnit+')'));
|
||||
const from=node('input');from.type='text';from.inputMode='decimal';from.className='siteBandFrom';
|
||||
from.setAttribute('aria-label','Metragem da faixa de '+product.title);
|
||||
from.setAttribute('aria-label','Início da faixa em '+bandUnit+' de '+product.title);
|
||||
fromLabel.append(from);
|
||||
const priceLabel=node('label');priceLabel.append(node('span','R$ por metro'));
|
||||
const priceLabel=node('label');priceLabel.append(node('span','R$ por '+(product.unit==='arte'?'arte':'metro')));
|
||||
const bandPrice=node('input');bandPrice.type='text';bandPrice.inputMode='decimal';bandPrice.className='siteBandPrice';
|
||||
bandPrice.setAttribute('aria-label','Preço da faixa de '+product.title);
|
||||
priceLabel.append(bandPrice);
|
||||
@@ -93,7 +95,7 @@ function sitePriceBlock(product){
|
||||
const from=Number(row.querySelector('.siteBandFrom').value.replace(',','.'));
|
||||
const unit=moneyInputCents(row.querySelector('.siteBandPrice').value);
|
||||
if(!Number.isFinite(from)||from<=0||unit===null||unit<=0)
|
||||
throw new Error('Confira as faixas: metragem e preço maiores que zero.');
|
||||
throw new Error('Confira as faixas: início e preço maiores que zero.');
|
||||
return {from_metres:String(from),unit_cents:unit};
|
||||
});
|
||||
const save=button('Salvar',async()=>{
|
||||
@@ -103,18 +105,17 @@ function sitePriceBlock(product){
|
||||
if(whenDate&&Number.isNaN(whenDate.getTime()))throw new Error('Data inválida.');
|
||||
await api('/site/products/'+product.id+'/prices',
|
||||
{unit_cents:cents,starts_at:whenDate?whenDate.toISOString():null,
|
||||
bands:product.id==='tratamento'?[]:formBands()});
|
||||
bands:formBands()});
|
||||
say(whenDate?'Preço salvo para '+when(whenDate)+'.':'Preço salvo. Vale a partir de agora.');
|
||||
await loadSiteAdmin();
|
||||
},'btn pri');
|
||||
form.append(priceLabel,startsLabel,save);
|
||||
if(product.id!=='tratamento')form.append(bands);
|
||||
form.append(priceLabel,startsLabel,save,bands);
|
||||
|
||||
const scheduled=node('div',undefined,'siteScheduled');
|
||||
if(product.scheduled.length){
|
||||
for(const row of product.scheduled){
|
||||
const line=node('div',undefined,'siteScheduledRow');
|
||||
line.append(node('span',money(row.unit_cents)+SITE_UNIT_LABEL[product.unit]+bandsText(row.bands)+
|
||||
line.append(node('span',money(row.unit_cents)+SITE_UNIT_LABEL[product.unit]+bandsText(row.bands,product.unit)+
|
||||
' a partir de '+when(row.starts_at)));
|
||||
line.append(button('Cancelar',async()=>{
|
||||
await cancelScheduledPrice(row.id);
|
||||
@@ -132,7 +133,7 @@ function sitePriceBlock(product){
|
||||
const body=node('tbody');
|
||||
for(const row of product.history){
|
||||
const tr=node('tr');
|
||||
tr.append(node('td',money(row.unit_cents)+bandsText(row.bands),'nowrap'),node('td',when(row.starts_at),'nowrap'),
|
||||
tr.append(node('td',money(row.unit_cents)+bandsText(row.bands,product.unit),'nowrap'),node('td',when(row.starts_at),'nowrap'),
|
||||
node('td',row.created_by),node('td',when(row.created_at),'nowrap'));
|
||||
body.append(tr);
|
||||
}
|
||||
@@ -188,7 +189,7 @@ async function loadGradeRules(){
|
||||
ensureGradePanel();
|
||||
const data=await api('/site/grade-rules');
|
||||
const aviso=gradeRuleRow('Avisar o designer abaixo de',data.aviso);
|
||||
const tratamento=gradeRuleRow('Exigir o tratamento abaixo de',data.tratamento);
|
||||
const tratamento=gradeRuleRow('Exigir o Ajuste Fino abaixo de',data.tratamento);
|
||||
const save=button('Salvar',async()=>{
|
||||
const avisoValue=aviso.on.checked?Number(aviso.num.value):null;
|
||||
const tratamentoValue=tratamento.on.checked?Number(tratamento.num.value):null;
|
||||
@@ -196,14 +197,14 @@ async function loadGradeRules(){
|
||||
if(value!==null&&(!Number.isInteger(value)||value<1||value>100))
|
||||
throw new Error('A nota vai de 1 a 100.');
|
||||
if(avisoValue!==null&&tratamentoValue!==null&&tratamentoValue>avisoValue)
|
||||
throw new Error('A regra do tratamento precisa ser menor ou igual à do aviso.');
|
||||
throw new Error('A regra do Ajuste Fino precisa ser menor ou igual à do aviso.');
|
||||
await api('/site/grade-rules',{aviso:avisoValue,tratamento:tratamentoValue});
|
||||
say('Regras da nota da arte salvas.');
|
||||
await loadGradeRules();
|
||||
},'btn pri');
|
||||
const children=[aviso.row,tratamento.row];
|
||||
if(!data.treatment_offered)
|
||||
children.push(node('p','Ative e dê preço ao Tratamento pelo designer para esta regra valer.','siteGradeWarn'));
|
||||
children.push(node('p','Ative e dê preço ao Ajuste Fino para esta regra valer.','siteGradeWarn'));
|
||||
const foot=node('div',undefined,'siteGradeSave');foot.append(save);children.push(foot);
|
||||
$('site-grade-body').replaceChildren(...children);
|
||||
}
|
||||
|
||||
@@ -1053,7 +1053,11 @@ function cardFlags(order){
|
||||
if(redo.length)out.push(['bad','Retrabalho',redo.map(r=>'Retrabalho · '+REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join(' · ')]);
|
||||
if(live&&s.items.some(mirroredItem))out.push(['warn','Espelhada',MIRROR_NOTE]);
|
||||
if(waitingContact(order))out.push(['warn','Contato','Aguardando contato: '+order.contact_note+' · '+contactWho(order)]);
|
||||
if(order.snapshot.treatment)out.push(['warn','Tratamento pago','O designer trata a arte antes de imprimir; prazo +24 h']);
|
||||
if(order.snapshot.treatment){
|
||||
const n=Number(order.snapshot.treatment.arts)||1;
|
||||
out.push(['warn','Ajuste Fino · '+n+(n===1?' arte':' artes'),
|
||||
'O designer faz o Ajuste Fino antes de imprimir; prazo +24 h']);
|
||||
}
|
||||
if(order.proof_parent)out.push(['warn','Prova do #'+order.proof_parent.number,'Card da prova do pedido #'+order.proof_parent.number]);
|
||||
if(live&&waitingProof(order)&&order.state!=='tra')out.push(['warn','Aguardando prova','Entra na fila com Prova OK no card #'+order.proof_card.number]);
|
||||
if(live&&proofRejected(order))out.push(['bad','Prova reprovada',order.proof_card.proof_reason+' · '+order.proof_card.proof_decided_by]);
|
||||
@@ -1600,9 +1604,9 @@ function contractionList(order){
|
||||
}
|
||||
function approveParts(order,main=true){
|
||||
if(order.snapshot.treatment){
|
||||
const approve=button('Enviar arte tratada',()=>treatDialog(order),'btn lg'+(main?' pri':''));
|
||||
const approve=button('Enviar arte do Ajuste Fino',()=>treatDialog(order),'btn lg'+(main?' pri':''));
|
||||
approve.dataset.treat='';
|
||||
return {text:'Tratamento pago: o designer precisa enviar o PNG tratado de cada item antes da fila.',
|
||||
return {text:'Ajuste Fino pago: o designer precisa enviar o PNG do Ajuste Fino de cada item antes da fila.',
|
||||
files:null,approve,extra:[]};
|
||||
}
|
||||
const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1;
|
||||
@@ -1694,8 +1698,8 @@ function nextBox(order){
|
||||
}
|
||||
if(st==='rec'||st==='cor'){
|
||||
if(st==='rec'&&order.snapshot.treatment&&!treatmentDone(order)&&finalDone(order)){
|
||||
title='Enviar a arte tratada';
|
||||
note('O tratamento foi pago. Envie o PNG tratado de cada item antes de colocar o pedido na fila.');
|
||||
title='Enviar a arte do Ajuste Fino';
|
||||
note('O Ajuste Fino foi pago. Envie o PNG ajustado de cada item antes de colocar o pedido na fila.');
|
||||
if(may('produce'))main.push(button('Tratar a arte',()=>treatDialog(order),'btn pri lg'));
|
||||
return composeNext(title,body,main,more);
|
||||
}
|
||||
@@ -2392,7 +2396,7 @@ function filesView(order,revisions,view){
|
||||
// Rework (Dropstar's rules D-02 to D-04). Gestão opens it with its cause,
|
||||
// which never changes after; an Administrador authorizes or declines it,
|
||||
// never one they opened. Bad art the customer approved is outside the goal.
|
||||
const REWORK_CAUSES={impressao:'Falha de impressão',perfil_cor:'Perfil de cor',tratamento:'Erro de tratamento',
|
||||
const REWORK_CAUSES={impressao:'Falha de impressão',perfil_cor:'Perfil de cor',tratamento:'Erro de Ajuste Fino',
|
||||
pedido:'Erro de pedido',arte_cliente:'Arte aprovada pelo cliente'};
|
||||
const REWORK_OUTSIDE='arte_cliente';
|
||||
function reworkForm(order){
|
||||
|
||||
115
web/site-cart.js
115
web/site-cart.js
@@ -4,6 +4,77 @@
|
||||
scope and run top to bottom, exactly as the original did. */
|
||||
// ── carrinho
|
||||
let itemAtual=null;
|
||||
// Ajuste Fino (front 1a): each art may be chosen under its warning, or the
|
||||
// general switch chooses every art of the paying items.
|
||||
function artesDoItem(it){
|
||||
if(it.partes && it.partes.length)
|
||||
return it.partes.reduce((t,p)=>t+((p.production&&p.production.sources||[]).length),0);
|
||||
return (it.production&&it.production.sources||[]).length;
|
||||
}
|
||||
function artesSelecionadas(aPagar=itensAPagar()){
|
||||
if(ajusteTudo) return aPagar.reduce((t,it)=>t+artesDoItem(it),0);
|
||||
return aPagar.reduce((t,it)=>{
|
||||
if(it.partes && it.partes.length)
|
||||
return t+it.partes.reduce((s,p)=>s+(p.ajusteSources||[]).length,0);
|
||||
return t+(it.ajusteSources||[]).length;
|
||||
},0);
|
||||
}
|
||||
// While a product is open, its files are not in the cart yet; the rule must
|
||||
// still see the arts the customer already checked under their warnings.
|
||||
function artesEscolhidasNaTela(){
|
||||
if(!modo) return 0;
|
||||
return (ehFolha()?folhas:artes).filter(x=>x.ajuste).length;
|
||||
}
|
||||
// What the cart snapshot compares: the switch and every chosen source.
|
||||
function ajusteSnapshot(){
|
||||
return {tudo:!!ajusteTudo, itens:itensAPagar().map(it=>({
|
||||
escolhas:it.ajusteSources||[],
|
||||
partes:(it.partes||[]).map(p=>p.ajusteSources||[])
|
||||
}))};
|
||||
}
|
||||
// A final cart item (after a split sheet becomes its own items) to the pairs.
|
||||
function tratamentoParaItens(itens){
|
||||
if(!(TAXA_TRATAMENTO>0)) return false;
|
||||
if(ajusteTudo) return true;
|
||||
const pairs=[];
|
||||
itens.forEach((it,itemIndex)=>{
|
||||
for(const source of it.ajusteSources||[]) pairs.push([itemIndex,source]);
|
||||
});
|
||||
return pairs.length?pairs:false;
|
||||
}
|
||||
function materializaAjuste(){
|
||||
if(!ajusteTudo) return;
|
||||
ajusteTudo=false;
|
||||
for(const it of itensAPagar()){
|
||||
if(it.partes && it.partes.length){
|
||||
for(const part of it.partes)
|
||||
part.ajusteSources=Array.from({length:(part.production&&part.production.sources||[]).length},(_,i)=>i);
|
||||
}else{
|
||||
it.ajusteSources=Array.from({length:(it.production&&it.production.sources||[]).length},(_,i)=>i);
|
||||
}
|
||||
}
|
||||
for(const x of folhas) x.ajuste=true;
|
||||
for(const a of artes) a.ajuste=true;
|
||||
}
|
||||
function limpaAjuste(){
|
||||
ajusteTudo=false;
|
||||
for(const it of itensAPagar()){
|
||||
it.ajusteSources=[];
|
||||
for(const part of it.partes||[]) part.ajusteSources=[];
|
||||
}
|
||||
for(const x of folhas) x.ajuste=false;
|
||||
for(const a of artes) a.ajuste=false;
|
||||
}
|
||||
// Update the per-art boxes without repainting the list, which would discard
|
||||
// the item the customer is still building.
|
||||
function pintaAjusteCheckboxes(){
|
||||
document.querySelectorAll('[data-ajuste]').forEach(el=>{
|
||||
const x=folhas[+el.dataset.ajuste]; if(x)el.checked=ajusteTudo||!!x.ajuste;
|
||||
});
|
||||
document.querySelectorAll('[data-ajustea]').forEach(el=>{
|
||||
const a=artes[+el.dataset.ajustea]; if(a)el.checked=ajusteTudo||!!a.ajuste;
|
||||
});
|
||||
}
|
||||
function invalidaItemAtual(){
|
||||
if(!itemAtual) return;
|
||||
itemAtual=null;
|
||||
@@ -31,7 +102,8 @@ function limpaPaineis(){
|
||||
}
|
||||
|
||||
// Front 8.5: when the worst grade of the paying items is below the rule and
|
||||
// the treatment is offered, the designer's treatment is required.
|
||||
// Ajuste Fino is offered, it is required. The simple rule the server keeps:
|
||||
// at least one art must be chosen; with none, the general switch selects all.
|
||||
function mostraAvisoTratamento(texto){
|
||||
const box=$('tratamentoBox'); if(!box)return;
|
||||
let el=$('tratamentoAviso');
|
||||
@@ -48,12 +120,27 @@ function aplicaTratamento(aPagar){
|
||||
const required=offered&&rule>0&&worst!==null&&worst<rule;
|
||||
box.hidden=!offered;
|
||||
if(!offered){
|
||||
check.checked=false;check.disabled=false;mostraAvisoTratamento('');
|
||||
check.checked=false;check.disabled=false;
|
||||
ajusteTudo=false;
|
||||
for(const it of aPagar){
|
||||
it.ajusteSources=[];
|
||||
for(const part of it.partes||[]) part.ajusteSources=[];
|
||||
}
|
||||
for(const x of folhas) x.ajuste=false;
|
||||
for(const a of artes) a.ajuste=false;
|
||||
mostraAvisoTratamento('');
|
||||
}else if(required){
|
||||
check.checked=true;check.disabled=true;
|
||||
mostraAvisoTratamento('Sua arte tem nota '+worst+': para imprimir com qualidade, o tratamento pelo designer é obrigatório neste pedido.');
|
||||
const chosen=!!ajusteTudo || artesSelecionadas(aPagar)>0 || artesEscolhidasNaTela()>0;
|
||||
if(!chosen){
|
||||
ajusteTudo=true;
|
||||
for(const x of folhas) x.ajuste=true;
|
||||
for(const a of artes) a.ajuste=true;
|
||||
document.querySelectorAll('[data-ajuste],[data-ajustea]').forEach(el=>{el.checked=true;});
|
||||
}
|
||||
check.checked=ajusteTudo;check.disabled=true;
|
||||
mostraAvisoTratamento('Sua arte tem nota '+worst+': para imprimir com qualidade, o Ajuste Fino é obrigatório neste pedido.');
|
||||
}else{
|
||||
check.disabled=false;mostraAvisoTratamento('');
|
||||
check.checked=ajusteTudo;check.disabled=false;mostraAvisoTratamento('');
|
||||
}
|
||||
}
|
||||
// O carrinho junta itens de produtos diferentes e cobra uma vez só.
|
||||
@@ -100,7 +187,8 @@ function pintaPedido(){
|
||||
$('bEsvaziar').hidden = pedido.length+(itemAtual?1:0) < 2;
|
||||
const itens = aPagar.reduce((t,it)=>t+it.total,0);
|
||||
const frete = entrega.tipo==='frete' && entrega.cotado ? entrega.valor : 0;
|
||||
const tratamento=$('fTratamento')?.checked&&TAXA_TRATAMENTO>0?TAXA_TRATAMENTO:0;
|
||||
const artesAjuste = TAXA_TRATAMENTO>0 ? artesSelecionadas(aPagar) : 0;
|
||||
const tratamento = artesAjuste ? Math.round(precoAjuste(artesAjuste)*artesAjuste*100)/100 : 0;
|
||||
const soma = itens + frete + tratamento;
|
||||
const n = aPagar.length, noCarrinho = pedido.length + (itemAtual?1:0);
|
||||
$('resLin').innerHTML =
|
||||
@@ -110,7 +198,8 @@ function pintaPedido(){
|
||||
'</span><b>'+
|
||||
(entrega.tipo==='retira' ? '<span style="color:var(--verde-ml)">Grátis</span>'
|
||||
: entrega.cotado ? rs(frete) : 'a cotar')+'</b></div>'+
|
||||
(tratamento?'<div class="l"><span>Tratamento da arte · +24 h</span><b>'+rs(tratamento)+'</b></div>':'')+
|
||||
(tratamento?'<div class="l"><span>Ajuste Fino · '+artesAjuste+(artesAjuste===1?' arte':' artes')+
|
||||
' · +24 h</span><b>'+rs(tratamento)+'</b></div>':'')+
|
||||
'<div class="l"><span>Revisão e reencaixe</span>'+
|
||||
'<b><span style="color:var(--verde-ml)">Grátis</span></b></div>';
|
||||
$('carrTot').textContent=rs(soma);
|
||||
@@ -151,6 +240,7 @@ function carrinho(){
|
||||
'<div class="l" style="color:var(--laranja2)"><span>Revisão e reencaixe</span><b>grátis</b></div>';
|
||||
$('carrLin').innerHTML=l;
|
||||
$('atual').style.display='';
|
||||
const escolhidas=lista=>lista.map((x,i)=>ajusteTudo||x.ajuste?i:null).filter(i=>i!==null);
|
||||
const sources=(ehFolha()?folhas:artes).map(x=>ehFolha()
|
||||
? {kind:'sheet',width_cm:x.med?.larg||larguraFilme(),length_cm:+(x.m*100).toFixed(4),
|
||||
copies:x.rep||1,rotation_degrees:0,mirrored:false,
|
||||
@@ -175,6 +265,7 @@ function carrinho(){
|
||||
localFiles:f.artes.map(x=>x.f), fotos:f.artes.map(x=>x.fotoSrc||null),
|
||||
metros:+(f.layout.height_cm/100).toFixed(4),
|
||||
production:{version:3,film_width_cm:larguraFilme(),sources:f.artes.map(fonteDaArte),...f.layout},
|
||||
ajusteSources:escolhidas(f.artes),
|
||||
residueAccepted:residuosDasArtes(f.artes), ...tracoDoItem(f.artes,f.layout)}));
|
||||
layout=null;
|
||||
}else{
|
||||
@@ -189,6 +280,7 @@ function carrinho(){
|
||||
arquivos:(ehFolha()?folhas:artes).length,
|
||||
production:layout?{version:3,film_width_cm:larguraFilme(),sources,...layout}:null,
|
||||
partes,
|
||||
...(partes?{}:{ajusteSources:escolhidas(ehFolha()?folhas:artes)}),
|
||||
qualityStatus:$('ciente').classList.contains('recusa')?'rejected':
|
||||
$('ciente').classList.contains('on')?'warning':nota===0?'unverified':'ok',
|
||||
qualityAcknowledged:false,
|
||||
@@ -210,7 +302,14 @@ function avisaDesfazer(texto,acao){
|
||||
function fechaDesfazer(){ clearTimeout(desfazerTimer); desfazerAcao=null; $('desfazer').hidden=true; }
|
||||
addEventListener('dtf-page-changed',fechaDesfazer);
|
||||
$('desfazerBtn').addEventListener('click',()=>{ const acao=desfazerAcao; fechaDesfazer(); if(acao) acao(); });
|
||||
$('fTratamento')?.addEventListener('change',()=>pintaPedido());
|
||||
$('fTratamento')?.addEventListener('change',()=>{
|
||||
if($('fTratamento').checked) ajusteTudo=true;
|
||||
else limpaAjuste();
|
||||
// The art cards show the same choice, one checkbox under each warning; do
|
||||
// not repaint them, or the item being built is discarded.
|
||||
pintaAjusteCheckboxes();
|
||||
pintaPedido();
|
||||
});
|
||||
$('bEsvaziar').addEventListener('click',()=>{
|
||||
const antes=pedido.slice();
|
||||
pedido=[]; invalidaItemAtual(); pintaPedido();
|
||||
|
||||
@@ -66,8 +66,11 @@ const FAIXAS={};
|
||||
// Folha que alguém abre na mão (CDR, AI, PSD, TIFF): R$ a mais por metro.
|
||||
// Vem do servidor (/api/session), que cobra o mesmo; zero não soma nada.
|
||||
let TAXA_MANUAL=0;
|
||||
// Fixed price of the designer treatment, set by the server (TREATMENT_CENTS).
|
||||
// Ajuste Fino, per art, set by the server (TREATMENT_CENTS).
|
||||
let TAXA_TRATAMENTO=0;
|
||||
// Ajuste Fino for every art of the cart: the general switch, or true when
|
||||
// the grade rule requires it. Individual choices live on the art objects.
|
||||
let ajusteTudo=false;
|
||||
const folhaManual=()=>ehFolha() && folhas.some(x=>!x.med);
|
||||
const ehFolha=m=>!!MODOS[m||modo].folha;
|
||||
const precoMetro=m=>PRECO[m||modo];
|
||||
@@ -79,6 +82,16 @@ function precoNaMetragem(m, metros){
|
||||
for(const band of bands) if(metros>=Number(band.from_metres) && (!alta || Number(band.from_metres)>=Number(alta.from_metres))) alta=band;
|
||||
return alta ? alta.unit_cents/100 : PRECO[m];
|
||||
}
|
||||
// Ajuste Fino: the price of one art when the order has n arts. Below the first
|
||||
// band it is the base, then the highest band reached, as app/catalog.py does.
|
||||
function precoAjuste(n, base = TAXA_TRATAMENTO, bands = FAIXAS.tratamento) {
|
||||
let price = base, best = null;
|
||||
for (const band of bands || []) {
|
||||
const start = Number(band.from_metres);
|
||||
if (n >= start && (best === null || start >= best)) { best = start; price = band.unit_cents / 100; }
|
||||
}
|
||||
return price;
|
||||
}
|
||||
// A próxima faixa à frente, para o aviso de quanto falta.
|
||||
function proximaFaixa(m, metros){
|
||||
const bands=FAIXAS[m]||[];
|
||||
|
||||
@@ -483,6 +483,27 @@ function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
|
||||
'usou e envie de novo. '+(varios?'Os círculos vermelhos na prévia mostram onde estão.':'O círculo vermelho na prévia mostra onde está.')+
|
||||
(aceitavel?' Se '+(varios?'os pontos são':'o ponto é')+' da própria arte, marque abaixo.</p>'+aceite:'</p>');
|
||||
}
|
||||
// Ajuste Fino (front 1a): under a Prumo warning, the customer may hand this
|
||||
// art to the designer. One choice per art; the cart has the general switch.
|
||||
function temAvisoFolha(x){
|
||||
const a=x.an;
|
||||
if(!a || a.grande) return false;
|
||||
return !!(a.fundoChapado || a.residuos || a.dpi<DPI_AVISA ||
|
||||
(typeof tracoDoArquivo==='function' && typeof mista==='function' && mista(tracoDoArquivo(x))));
|
||||
}
|
||||
function temAvisoArte(a){
|
||||
const an=analiseDaArte(a);
|
||||
if(!an || an.grande) return false;
|
||||
return !!(an.fundoChapado || an.residuos || an.dpi<DPI_AVISA ||
|
||||
(typeof mista==='function' && mista(tracoDaArte(a))));
|
||||
}
|
||||
function ajusteLinha(i,attr){
|
||||
if(!(TAXA_TRATAMENTO>0)) return '';
|
||||
const marcado=ajusteTudo || (attr==='data-ajuste' ? folhas[i].ajuste : artes[i].ajuste);
|
||||
return '<label class="aceiteRes ajusteArte"><input type="checkbox" '+attr+'="'+i+'"'+
|
||||
(marcado?' checked':'')+'>'+
|
||||
'<span>Quer que um designer resolva? <b>Ajuste Fino</b> — '+rs(TAXA_TRATAMENTO)+'</span></label>';
|
||||
}
|
||||
function detalhesDaFolha(a,i,aberto){
|
||||
const linhas = a.grande
|
||||
? ['Resolução '+a.dpi+' DPI, lida do arquivo',
|
||||
@@ -514,6 +535,7 @@ function pintaFolha(){
|
||||
medida='<div class="repMed"><b>'+n1(x.med.larg)+' × '+n1(x.med.alt)+' cm</b>'+
|
||||
'<span>'+escapeHTML(extDe(x.f.name))+' · '+fmt(x.f.size)+'</span></div>'+
|
||||
(a? '<ul class="chips">'+chipsDaFolha(a,residuoAceito(x))+'</ul>'+avisosDaFolha(a,x.f.name,i,residuoAceito(x),true)+
|
||||
(temAvisoFolha(x)?ajusteLinha(i,'data-ajuste'):'')+
|
||||
detalhesDaFolha(a,i,x.detAberto) : '')+
|
||||
// Over 150 MB the browser cannot check a PDF: said before payment, as
|
||||
// for a file opened by hand (Dropstar, 2026-10-23).
|
||||
@@ -524,7 +546,7 @@ function pintaFolha(){
|
||||
'Exportando em <b>PNG</b>, ou num PDF menor, a conferência sai aqui, antes de pagar.</p>' : '')+
|
||||
(suspeito? '<p class="avisoF"><b>Este PDF passa do tamanho que o formato comporta.</b> '+
|
||||
'A especificação para em 508 cm e o seu tem '+n1(x.med.alt)+' cm. '+
|
||||
'Ele abre certo só em quem o gerou — aqui vai precisar de tratamento. '+
|
||||
'Ele abre certo só em quem o gerou — aqui vai precisar do Ajuste Fino. '+
|
||||
'Manda em <b>PNG ou TIFF</b>, ou divide em partes de até 5 m, que sai na hora.</p>':'')+
|
||||
(larga? '<p class="avisoF"><b>Esta folha não roda neste filme.</b> Ela tem '+n1(x.med.larg)+
|
||||
' cm de largura e o filme aqui tem '+n1(L)+' cm. Não dá para reduzir: '+
|
||||
@@ -588,6 +610,11 @@ function pintaFolha(){
|
||||
$('lista').querySelectorAll('[data-residuo]').forEach(el=>el.addEventListener('change',()=>{
|
||||
folhas[+el.dataset.residuo].residuoAceito=el.checked; pintaFolha();
|
||||
}));
|
||||
$('lista').querySelectorAll('[data-ajuste]').forEach(el=>el.addEventListener('change',()=>{
|
||||
if(ajusteTudo) materializaAjuste();
|
||||
folhas[+el.dataset.ajuste].ajuste=el.checked;
|
||||
pintaFolha(); pintaPedido();
|
||||
}));
|
||||
$('lista').querySelectorAll('[data-det]').forEach(d=>d.addEventListener('toggle',()=>{
|
||||
folhas[+d.dataset.det].detAberto=d.open;
|
||||
}));
|
||||
@@ -688,7 +715,8 @@ function pintaArtes(){
|
||||
'<button data-rm="'+i+'" aria-label="Remover '+escapeHTML(a.f.name)+'">'+icone('fechar')+'</button></div>'+
|
||||
'<div class="repMed">'+medida+'<span>'+(a.px>0? a.px+' × '+a.py+' px · ' : '')+
|
||||
escapeHTML(extDe(a.f.name))+' · '+fmt(a.f.size)+'</span></div>'+
|
||||
barra+chips+aviso+dica+
|
||||
barra+chips+aviso+
|
||||
(a.cm>0 && (a.src||a.semPrevia) && temAvisoArte(a) ? ajusteLinha(i,'data-ajustea') : '')+dica+
|
||||
'</div></div>'+
|
||||
'<div class="cps">'+
|
||||
'<div class="campo"><label for="cm'+i+'">Largura</label>'+
|
||||
@@ -715,6 +743,11 @@ function pintaArtes(){
|
||||
$('lista').querySelectorAll('[data-rm]').forEach(b=>b.addEventListener('click',()=>{artes.splice(+b.dataset.rm,1);pintaArtes();}));
|
||||
$('lista').querySelectorAll('[data-residuoa]').forEach(el=>el.addEventListener('change',()=>{
|
||||
artes[+el.dataset.residuoa].residuoAceito=el.checked; pintaArtes();}));
|
||||
$('lista').querySelectorAll('[data-ajustea]').forEach(el=>el.addEventListener('change',()=>{
|
||||
if(ajusteTudo) materializaAjuste();
|
||||
artes[+el.dataset.ajustea].ajuste=el.checked;
|
||||
pintaArtes(); pintaPedido();
|
||||
}));
|
||||
$('lista').querySelectorAll('[data-cm]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.cm].cm=+i.value||0;pintaArtes();}));
|
||||
$('lista').querySelectorAll('[data-q]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.q].q=Math.max(1,Math.min(200,Math.floor(+i.value||1)));pintaArtes();}));
|
||||
$('lista').querySelectorAll('[data-cm], [data-q]').forEach(i=>i.addEventListener('input',()=>{
|
||||
|
||||
Reference in New Issue
Block a user