diff --git a/app/api/operator.py b/app/api/operator.py
index 3d45ee3..850559e 100644
--- a/app/api/operator.py
+++ b/app/api/operator.py
@@ -11,16 +11,17 @@ from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from fastapi.responses import RedirectResponse
from pydantic import Field
+from psycopg.types.json import Jsonb
from ..core import db
from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can, client_ip, operator,
login_failed, may_move, may_reorder, password_matches, throttle)
-from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart
+from ..core.models import Contraction, Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart
from ..printjobs import file_prefix, queue as queue_print_files
from .. import cnpj, machines, mail, payments, proof, quote_review, receipt
from .. import tiny
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES,
- TRANSITIONS, payment, enqueue, freight, operator_identity, quote_view, storage, upload_row)
+ TRANSITIONS, payment, enqueue, freight, operator_identity, quote_view, quote_views, storage, upload_row)
from .uploads import begin_upload
from ..scanning import require_clean
@@ -134,7 +135,7 @@ def board(user=Depends(operator)):
issues_total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events
WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') AND resolved_at IS NULL''').fetchone()['n']
backup = backup_status(c)
- quotes = [quote_view(c, q) for q in pending + approved]
+ quotes = quote_views(c, pending + approved)
return {'states': STATES, 'transitions': TRANSITIONS, 'back': BACK,
'orders': orders, 'payment_issues_total': issues_total, 'tiny': tiny_status(), 'operator': user,
'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup,
@@ -403,7 +404,7 @@ def quote_page(kind: Literal['pending','approved'], before_created_at: datetime
total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE {where}''', params).fetchone()['n']
- quotes = [quote_view(c,row) for row in rows[:limit]]
+ quotes = quote_views(c, rows[:limit])
return {'quotes': quotes, 'has_more': len(rows)>limit, 'total': total,
'thumbnails': thumbnails(c, quotes), 'names': company_names(c, quotes)}
@@ -433,7 +434,7 @@ def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator))
WHERE o.id IS NULL AND {LIVE_QUOTE} AND {quote_match}
ORDER BY q.created_at DESC LIMIT 8''', quote_params).fetchall()
orders = with_print_files(c, orders)
- quotes = [quote_view(c, row) for row in rows]
+ quotes = quote_views(c, rows)
return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
'names': company_names(c, orders, quotes)}
@@ -674,6 +675,31 @@ def choose_machine(uid: UUID, body: MachineChoice, request: Request, user=Depend
return {'ok': True}
+@router.post('/api/operator/orders/{uid}/contraction')
+def choose_contraction(uid: UUID, body: Contraction, user=Depends(can('produce'))):
+ """The contraction class of an item (Dropstar, 2026-10-30): the browser's
+ measure comes prefilled, and whoever prepares the art may change it until
+ the order prints. Both stay: the measure in the snapshot, the choice here."""
+ with db.connect() as c:
+ row = c.execute('SELECT snapshot,state,cancelled_at,contraction FROM dtf_local.orders WHERE id=%s FOR UPDATE',
+ (uid,)).fetchone()
+ if not row:
+ raise HTTPException(404, 'Pedido não encontrado.')
+ if row['cancelled_at'] or row['state'] not in ('rec', 'tra', 'cor'):
+ raise HTTPException(409, 'A contração muda até o pedido ir para Imprimindo.')
+ if body.item_index >= len(row['snapshot']['items']):
+ raise HTTPException(422, 'Item não encontrado no pedido.')
+ chosen = dict(row['contraction'] or {})
+ key = str(body.item_index)
+ if body.value is None:
+ chosen.pop(key, None)
+ else:
+ chosen[key] = {'class': body.value, 'by': user, 'at': datetime.now(timezone.utc).isoformat()}
+ c.execute('UPDATE dtf_local.orders SET contraction=%s WHERE id=%s', (Jsonb(chosen), uid))
+ audit('order_contraction_chosen', order=str(uid), item=body.item_index, value=body.value or '', operator=user)
+ return {'ok': True, 'contraction': chosen}
+
+
class ContactWait(StrictModel):
waiting: bool
note: str = Field(default='', max_length=500)
diff --git a/app/core/models.py b/app/core/models.py
index 568ce0b..8af77ba 100644
--- a/app/core/models.py
+++ b/app/core/models.py
@@ -150,6 +150,28 @@ class ProductionSpec(StrictModel):
sources: list[ProductionSource] = Field(min_length=1, max_length=20)
placements: list[ProductionPlacement] = Field(min_length=1, max_length=4000)
+class Split(StrictModel):
+ """One sheet of loose art the Site split by contraction class (item 17,
+ Dropstar 2026-10-30): fine lines (C1, C2) on one sheet, thick (C3) on
+ another, each its own item and print file, billed together."""
+ group: str = Field(pattern=r'^[a-z0-9]{1,16}$')
+ part: int = Field(ge=1, le=10, strict=True)
+ of: int = Field(ge=2, le=10, strict=True)
+
+
+def check_splits(items):
+ """Every split group has each of its parts once, of one product."""
+ groups = {}
+ for item in items:
+ if item.split:
+ groups.setdefault(item.split.group, []).append(item)
+ for parts in groups.values():
+ of = parts[0].split.of
+ if sorted(item.split.part for item in parts) != list(range(1, of + 1)) or \
+ any(item.split.of != of or item.mode != parts[0].mode for item in parts):
+ raise ValueError('Split sheets must list each part once, of one product')
+
+
class Item(StrictModel):
mode: Literal['file','avulsa','uvfile','uv']
metres: Decimal = Field(gt=0, le=12000)
@@ -161,9 +183,19 @@ class Item(StrictModel):
# Residue dots under 2 mm the customer accepted printing on a ready sheet,
# rather than erasing them (Dropstar, 2026-10-29): 0 when none.
residue_accepted: int = Field(default=0, ge=0, le=1000000, strict=True)
+ # The thinnest stroke the browser measured, in pixels at 300 DPI, and its
+ # contraction class (Dropstar, 2026-10-30): up to 4 C1, 5 to 19 C2, 20+ C3.
+ stroke_px: int | None = Field(default=None, ge=1, le=10000, strict=True)
+ stroke_class: Literal['C1', 'C2', 'C3'] | None = None
+ # A sheet with fine lines and solid areas (item 16): the customer kept the
+ # measure (protect the fine lines) or chose to protect the solid areas (C3).
+ stroke_choice: Literal['measured', 'client_c3'] | None = None
+ split: Split | None = None
@model_validator(mode='after')
def production_matches_uploads(self):
+ if self.split and (self.mode not in ('avulsa', 'uv') or self.split.part > self.split.of):
+ raise ValueError('Only loose artwork is split into sheets')
if [source.upload_id for source in self.production.sources] != self.uploads:
raise ValueError('Production sources must match uploaded files in order')
is_sheet = self.mode in ('file', 'uvfile')
@@ -214,6 +246,11 @@ class QuoteRequest(StrictModel):
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
proof: bool = False
+ @model_validator(mode='after')
+ def splits_complete(self):
+ check_splits(self.items)
+ return self
+
@model_validator(mode='after')
def destination_matches_freight(self):
if self.freight.service == 'pickup':
@@ -228,6 +265,11 @@ class QuoteRequest(StrictModel):
class Review(StrictModel):
items: list[Item] = Field(min_length=1, max_length=30)
+ @model_validator(mode='after')
+ def splits_complete(self):
+ check_splits(self.items)
+ return self
+
class Pay(StrictModel):
quote_id: UUID
@@ -267,6 +309,11 @@ class Move(StrictModel):
# Pulled into Imprimindo onto a machine's lane: the machine it prints on.
machine_id: UUID | None = None
+class Contraction(StrictModel):
+ item_index: int = Field(ge=0, le=100)
+ # None returns the item to the class the browser measured.
+ value: Literal['C1', 'C2', 'C3'] | None = None
+
class Resolution(StrictModel):
note: str = Field(min_length=3, max_length=1000)
diff --git a/app/core/pricing.py b/app/core/pricing.py
index 0702d86..07ef1fc 100644
--- a/app/core/pricing.py
+++ b/app/core/pricing.py
@@ -32,15 +32,16 @@ def is_manual(item, names) -> bool:
for source in item['production']['sources'])
-def price(mode: str, metres: str, grade: int, extra_cents: int = 0) -> dict:
+def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Decimal = Decimal('1')) -> dict:
"""The item's charge. The grade is validated and kept with the item; the
- price does not depend on it."""
+ price does not depend on it. A split sheet has no minimum of its own: its
+ group has one (bill_splits)."""
length = Decimal(str(metres))
if mode not in PRICES or not length.is_finite() or not 0 < length <= 12000:
raise ValueError('Invalid product or length')
if isinstance(grade, bool) or not isinstance(grade, int) or not 0 <= grade <= 100:
raise ValueError('Grade must be an integer between 0 and 100')
- billed = max(Decimal('1'), (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10)
+ billed = max(minimum, (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10)
if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
raise ValueError('Invalid extra charge')
unit = PRICES[mode] + extra_cents
@@ -50,3 +51,22 @@ def price(mode: str, metres: str, grade: int, extra_cents: int = 0) -> dict:
if extra_cents:
priced['manual_extra_cents'] = extra_cents
return priced
+
+
+def bill_splits(priced: list) -> list:
+ """The order minimum of 1 m once per split group, on its first sheet: the
+ customer did not choose the split (item 17), so it never costs a metre more."""
+ for group in dict.fromkeys(i['split']['group'] for i in priced if i.get('split')):
+ parts = [i for i in priced if (i.get('split') or {}).get('group') == group]
+ short = Decimal('1') - sum(Decimal(i['billed_metres']) for i in parts)
+ if short > 0:
+ first = min(parts, key=lambda i: i['split']['part'])
+ billed = Decimal(first['billed_metres']) + short
+ first.update(billed_metres=str(billed), total_cents=int(billed * first['unit_cents']))
+ return priced
+
+
+def sheet_label(item: dict) -> str:
+ """' · folha 1 de 2' on a split sheet (item 17), for the customer's lists."""
+ split = item.get('split')
+ return f" · folha {split['part']} de {split['of']}" if split else ''
diff --git a/app/mail.py b/app/mail.py
index 7fa1186..f1fc9e6 100644
--- a/app/mail.py
+++ b/app/mail.py
@@ -23,6 +23,8 @@ import ssl
from email.message import EmailMessage
from email.utils import formataddr, formatdate, make_msgid, parseaddr
+from .core.pricing import sheet_label
+
ADAPTER = os.environ.get('MAIL_ADAPTER', 'off')
RESET_MINUTES = 60
CODE_MINUTES = 15
@@ -70,7 +72,7 @@ def order_paid(c, order, origin):
delivery = freight.get('description') or 'Entrega'
if freight.get('days'):
delivery += f" · até {freight['days']} dias úteis"
- rows = [('Itens', '\n'.join(f"{PRODUCTS.get(i.get('mode'), i.get('mode'))} · "
+ rows = [('Itens', '\n'.join(f"{PRODUCTS.get(i.get('mode'), i.get('mode'))}{sheet_label(i)} · "
f"{str(i.get('billed_metres') or i.get('metres')).replace('.', ',')} m"
for i in snapshot.get('items', []))),
('Entrega', delivery),
diff --git a/app/quote_review.py b/app/quote_review.py
index a1fc2c2..47bd86b 100644
--- a/app/quote_review.py
+++ b/app/quote_review.py
@@ -22,7 +22,7 @@ from psycopg.types.json import Jsonb
from . import payments
from .proof import PROOF_ABOVE_METRES
from .core.models import PRODUCTION_VERSIONS
-from .core.pricing import is_manual, manual_extra_cents, price
+from .core.pricing import bill_splits, is_manual, manual_extra_cents, price
from .runtime import freight, upload_row
from .scanning import require_clean
@@ -64,7 +64,7 @@ def approve(c, row, items, reviewer):
for item, original in zip(items, draft['items']):
if item.mode != original['mode'] or list(map(str, item.uploads)) != original['uploads']:
raise HTTPException(422, 'O produto e os arquivos não podem mudar na revisão.')
- if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged'] or item.residue_accepted != original.get('residue_accepted', 0):
+ if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged'] or item.residue_accepted != original.get('residue_accepted', 0) or item.stroke_class != original.get('stroke_class') or item.stroke_px != original.get('stroke_px') or item.stroke_choice != original.get('stroke_choice') or (item.split and item.split.model_dump()) != original.get('split'):
raise HTTPException(422, 'A montagem e a confirmação do cliente não podem mudar na revisão.')
names = {}
for upload_id in item.uploads:
@@ -72,11 +72,17 @@ def approve(c, row, items, reviewer):
require_clean(upload)
names[str(upload_id)] = upload['name']
extra = manual_extra_cents() if is_manual(original, names) else 0
- priced.append({**price(item.mode, str(item.metres), item.grade, extra),
+ priced.append({**price(item.mode, str(item.metres), item.grade, extra,
+ minimum=Decimal('0') if item.split else Decimal('1')),
'uploads': original['uploads'], 'production': original['production'],
'quality_status': original['quality_status'],
'quality_acknowledged': original['quality_acknowledged'],
- 'residue_accepted': original.get('residue_accepted', 0)})
+ 'residue_accepted': original.get('residue_accepted', 0),
+ **({'stroke_px': original['stroke_px'], 'stroke_class': original['stroke_class']}
+ if original.get('stroke_class') else {}),
+ **({'stroke_choice': original['stroke_choice']} if original.get('stroke_choice') else {}),
+ **({'split': original['split']} if original.get('split') else {})})
+ bill_splits(priced)
metres = sum(Decimal(i['billed_metres']) for i in priced)
try:
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
diff --git a/app/receipt.py b/app/receipt.py
index e21485a..713ceed 100644
--- a/app/receipt.py
+++ b/app/receipt.py
@@ -11,6 +11,7 @@ import io
import unicodedata
from datetime import datetime
+from .core.pricing import sheet_label
from .printfile import Name, PdfWriter, deflate, serialize, _HELVETICA, _HELVETICA_BOLD
from .printjobs import LOCAL, file_prefix
@@ -95,7 +96,7 @@ def lines(order, paid_with, issued):
out.append(('Produto', 7.5, False, 10))
for item in snapshot.get('items') or []:
metres = str(item.get('billed_metres') or item.get('metres') or '').replace('.', ',')
- out += [(part, 9.5, False, 2) for part in wrap(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))} — {metres} m", 9.5)]
+ out += [(part, 9.5, False, 2) for part in wrap(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))}{sheet_label(item)} — {metres} m", 9.5)]
out += [('Valor', 7.5, False, 10), (money(snapshot.get('total_cents') or 0), 12, True, 1),
('Pagamento', 7.5, False, 6), (METHODS.get(paid_with, 'Teste' if paid_with == 'teste' else paid_with or '—'), 10, False, 1),
(f"Emitido em {issued.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')}", 8.5, False, 10),
diff --git a/app/runtime.py b/app/runtime.py
index 376330e..7419203 100644
--- a/app/runtime.py
+++ b/app/runtime.py
@@ -103,15 +103,31 @@ def order_code(order_id):
return str(order_id).replace('-', '')[:8].upper()
-def quote_view(c, row):
+def quote_views(c, rows):
+ """quote_view for a list of quotes, in two queries whatever its length: the
+ board shows up to 240 quotes, and asking per quote made 480 queries."""
+ ids = [row['id'] for row in rows]
+ if not ids:
+ return []
+ orders = {r['quote_id']: {k: r[k] for k in ('id', 'number', 'state')} for r in c.execute(
+ 'SELECT quote_id,id,number,state FROM dtf_local.orders WHERE quote_id=ANY(%s)', (ids,)).fetchall()}
+ attempts = {r['quote_id']: {k: r[k] for k in ('method', 'status', 'status_detail', 'expires_at', 'created_at')}
+ for r in c.execute('''SELECT DISTINCT ON (quote_id) quote_id,method,status,
+ response->>'status_detail' AS status_detail, response->>'expires_at' AS expires_at, created_at
+ FROM dtf_local.payment_intents WHERE quote_id=ANY(%s) ORDER BY quote_id, created_at DESC''', (ids,)).fetchall()}
+ return [quote_view(c, row, order=orders.get(row['id']), attempt=attempts.get(row['id']), known=True) for row in rows]
+
+
+def quote_view(c, row, order=None, attempt=None, known=False):
from .quote_review import review_reason # it imports this module
- order = c.execute('SELECT id,number,state FROM dtf_local.orders WHERE quote_id=%s', (row['id'],)).fetchone()
- # The latest payment attempt, so the payment page can tell a refused card
- # (the notification updates it) from one still waiting.
- # Its PIX expiry and time let the Kanban tell "tried to pay" from "never tried".
- attempt = c.execute('''SELECT method,status,response->>'status_detail' AS status_detail,
- response->>'expires_at' AS expires_at, created_at
- FROM dtf_local.payment_intents WHERE quote_id=%s ORDER BY created_at DESC LIMIT 1''', (row['id'],)).fetchone()
+ if not known:
+ order = c.execute('SELECT id,number,state FROM dtf_local.orders WHERE quote_id=%s', (row['id'],)).fetchone()
+ # The latest payment attempt, so the payment page can tell a refused card
+ # (the notification updates it) from one still waiting.
+ # Its PIX expiry and time let the Kanban tell "tried to pay" from "never tried".
+ attempt = c.execute('''SELECT method,status,response->>'status_detail' AS status_detail,
+ response->>'expires_at' AS expires_at, created_at
+ FROM dtf_local.payment_intents WHERE quote_id=%s ORDER BY created_at DESC LIMIT 1''', (row['id'],)).fetchone()
if attempt and attempt['status'] == 'rejected':
from .payment_messages import rejection
attempt = {**attempt, 'message': rejection(attempt['status_detail'])}
diff --git a/app/schema.sql b/app/schema.sql
index 3ab6eef..3d46210 100644
--- a/app/schema.sql
+++ b/app/schema.sql
@@ -423,6 +423,9 @@ ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_photo uuid REFER
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_id uuid REFERENCES dtf_local.machines(id) ON DELETE SET NULL;
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_at timestamptz;
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_answered boolean NOT NULL DEFAULT false;
+-- The contraction class chosen per item (item 9), keyed by item index, with
+-- who chose it and when; the measured class stays in the order's snapshot.
+ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contraction jsonb NOT NULL DEFAULT '{}'::jsonb;
-- When the session was last used (Usuários: who is on the system now).
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS seen_at timestamptz;
-- The machine of whoever moved a card, as it was named then: "Imprimindo ·
diff --git a/tests/smoke_test.py b/tests/smoke_test.py
index 381bf19..d288145 100644
--- a/tests/smoke_test.py
+++ b/tests/smoke_test.py
@@ -214,6 +214,29 @@ def run():
kept=client.call('/quotes',accepted)
assert kept['status']=='approved'
assert client.call('/quotes/'+kept['id'])['approved']['items'][0]['residue_accepted']==3
+ # The thinnest stroke and its contraction class (item 9) stay with the item too.
+ stroked={**small,'request_key':str(uuid4()),'items':[{**item_spec('avulsa','2.75',90,graded),'stroke_px':6,'stroke_class':'C2'}]}
+ client.call('/quotes',{**stroked,'items':[{**stroked['items'][0],'stroke_class':'C4'}]},expected=422)
+ held_stroke=client.call('/quotes',stroked)
+ assert held_stroke['status']=='approved'
+ stroke_item=client.call('/quotes/'+held_stroke['id'])['approved']['items'][0]
+ assert (stroke_item['stroke_px'],stroke_item['stroke_class'])==(6,'C2'), stroke_item
+ # A sheet with fine lines and solid areas (item 16) keeps the customer's choice.
+ mixed={**stroked,'request_key':str(uuid4()),'items':[{**stroked['items'][0],'stroke_choice':'client_c3'}]}
+ client.call('/quotes',{**mixed,'items':[{**mixed['items'][0],'stroke_choice':'both'}]},expected=422)
+ mixed_item=client.call('/quotes/'+client.call('/quotes',mixed)['id'])['approved']['items'][0]
+ assert mixed_item['stroke_choice']=='client_c3', mixed_item
+ # Loose art split by stroke (item 17): each sheet is an item, and the pair
+ # has one 1 m minimum, on its first sheet.
+ part=lambda metres,n,mode='avulsa':{**item_spec(mode,metres,90,graded),'split':{'group':'f0','part':n,'of':2}}
+ split={**small,'request_key':str(uuid4()),'items':[part('0.3',1),part('0.15',2)]}
+ client.call('/quotes',{**split,'items':split['items'][:1]},expected=422)
+ client.call('/quotes',{**split,'items':[part('0.3',1),part('0.15',1)]},expected=422)
+ client.call('/quotes',{**split,'items':[part('0.3',1,'file'),part('0.15',2,'file')]},expected=422)
+ held_split=client.call('/quotes',split)
+ assert held_split['status']=='approved', held_split
+ sheets=client.call('/quotes/'+held_split['id'])['approved']['items']
+ assert [(i['billed_metres'],i['total_cents'],i['split']['part']) for i in sheets]==[('0.8',1752,1),('0.2',438,2)], sheets
# The Site grades only art it analysed. A grade on art it did not analyse
# is checked against the file like any other, and this one cannot be.
claimed={**item_spec('avulsa','2.75',0,uid),'grade':90}
diff --git a/tests/users_test.py b/tests/users_test.py
index 7c40e1c..1d7d973 100644
--- a/tests/users_test.py
+++ b/tests/users_test.py
@@ -426,6 +426,15 @@ def run():
onto = su.call(f'/operator/orders/{lane}/move', {'state': 'imp', 'version': 0, 'reason': '', 'machine_id': textil2},
operator=True)
assert str(onto['machine_id']) == textil2 and onto['machine_chosen'], onto
+ # The contraction class (item 9): chosen per item until the order prints,
+ # and back to the browser's measure with None.
+ su.call(f'/operator/orders/{third}/contraction', {'item_index': 0, 'value': 'C3'}, operator=True)
+ chosen = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == third)['contraction']
+ assert chosen['0']['class'] == 'C3' and chosen['0']['by'], chosen
+ su.call(f'/operator/orders/{third}/contraction', {'item_index': 5, 'value': 'C1'}, operator=True, expected=422)
+ su.call(f'/operator/orders/{lane}/contraction', {'item_index': 0, 'value': 'C1'}, operator=True, expected=409)
+ su.call(f'/operator/orders/{third}/contraction', {'item_index': 0, 'value': None}, operator=True)
+ assert next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == third)['contraction'] == {}
loaded = su.call('/operator/board', operator=True)
board = {o['id']: o for o in loaded['orders']}
assert (board[first]['printing'], board[second_in]['printing'], board[third]['printing']) == \
diff --git a/web/checkout.js b/web/checkout.js
index 40dc8ed..92ad86b 100644
--- a/web/checkout.js
+++ b/web/checkout.js
@@ -21,6 +21,8 @@
quality:item.qualityStatus,
acknowledged:item.qualityAcknowledged,
residue:item.residueAccepted||0,
+ 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}))
}))});
}
@@ -106,8 +108,16 @@
const amount=document.createElement('b'); amount.textContent=value;
row.append(name,amount); return row;
};
- const rows = approved.items.map(item => linha(
- (MODOS[item.mode]?.tit || item.mode)+' · '+fmtM(Number(item.billed_metres))+' m', rs(item.total_cents/100)));
+ // The sheets of a split (item 17) are one line, as in the cart.
+ const linhas=[];
+ for (const item of approved.items) {
+ const grupo=item.split && linhas.find(l=>l.split?.group===item.split.group);
+ if (grupo) { grupo.billed_metres=String(Number(grupo.billed_metres)+Number(item.billed_metres)); grupo.total_cents+=item.total_cents; grupo.folhas++; }
+ else linhas.push({...item,folhas:1});
+ }
+ const rows = linhas.map(item => linha(
+ (MODOS[item.mode]?.tit || item.mode)+(item.folhas>1?' · '+item.folhas+' folhas':'')+' · '+
+ fmtM(Number(item.billed_metres))+' m', rs(item.total_cents/100)));
const pickup = approved.freight.service === 'pickup';
const prazo = approved.freight.days ? ' · até '+approved.freight.days+' dias úteis' : '';
rows.push(linha(pickup ? 'Retirada em Franca' : (approved.freight.description || 'Frete')+prazo,
@@ -327,7 +337,12 @@
if((await api('/session')).cart_scope !== (await ready).cart_scope) throw new Error('Sua conta ou sessão mudou. Recarregue a página antes de enviar o carrinho.');
const items=[];
pintaEnvio();
- for (const item of cart) {
+ // Loose art split by stroke (item 17) is one cart line and one order item
+ // per sheet, billed together.
+ const sheets=cart.flatMap((line,index)=>line.partes?.length
+ ? line.partes.map((part,i)=>({...line,...part,split:{group:'f'+index,part:i+1,of:line.partes.length}}))
+ : [line]);
+ for (const item of sheets) {
if (!item.localFiles?.length) throw new Error('Selecione novamente os arquivos deste item.');
const uploads=[];
for (const [index,file] of item.localFiles.entries()) {
@@ -341,7 +356,10 @@
production:{...item.production,sources:item.production.sources.map((source,index)=>({
upload_id:uploads[index],...source}))},
quality_status:item.qualityStatus,quality_acknowledged:item.qualityAcknowledged,
- residue_accepted:item.residueAccepted||0});
+ residue_accepted:item.residueAccepted||0,
+ ...(item.strokeClass?{stroke_px:item.strokePx,stroke_class:item.strokeClass}:{}),
+ ...(item.strokeChoice?{stroke_choice:item.strokeChoice}:{}),
+ ...(item.split?{split:item.split}:{})});
}
const service = entrega.tipo==='retira' ? 'pickup' : entrega.servico;
if (!service) throw new Error('A entrega ainda não está disponível. Escolha a retirada em Franca.');
diff --git a/web/index.html b/web/index.html
index 7e2e91a..0339f57 100644
--- a/web/index.html
+++ b/web/index.html
@@ -942,11 +942,25 @@ h2 em{font-style:normal;color:var(--laranja)}
Li e entendi. Quero imprimir assim mesmo.
+
+
Traços finos e áreas chapadas na mesma folha
+
O branco por baixo precisa de ajuste diferente pra cada um. Escolha o que proteger:
+
+
+
+
Revisamos e reencaixamos antes de imprimir, sem custo.