Compare commits

...

9 Commits

Author SHA1 Message Date
Cauê Faleiros
6ec0ea31a6 feat: billed every 10 cm with 8 mm in the customer's favour, and the Site shows the whole sum (Marcus, 2026-11-27)
All checks were successful
Build and deploy / Validate source (push) Successful in 14s
Build and deploy / Integration suite on a real stack (push) Successful in 8m42s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m10s
Marcus: a length that passes a 10 cm step by up to 8 mm is billed at that
step; by more, at the next. One rule for every product, on the server
(pricing.billed_length), the Site (arredonda10) and the Montador's estimate;
the print file accepts the 8 mm past the billed length instead of sending
the sheet to hand preparation.

The Site showed four numbers that did not add up (0,88 m, 4,42 m, 4,45 m,
4,50 m), and the team read 4,40 m. The copies line now gives the whole
sum ("5 × 88,4 cm + 4 espaços de 8 mm = 445,2 cm"), and the buy box says
why the billed metres are what they are, as a benefit ("os 4 mm a mais
ficam por nossa conta"). The buy box's parts note said 20 m; parts are
10 m since 18/11.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:04:10 -03:00
Cauê Faleiros
5f84db708c fix: the folders' download links last an hour, and one that ran out is fetched again quietly
All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 7m49s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m8s
The folders download a whole list of files one after another, from links
made when the list was asked for, valid 5 minutes. With films of 10 m the
last ones began after that and failed with "erro 403": a red error, a
Sentry report, and only the next pass got new links. The folders' and hot
folder's links now last an hour (customer downloads keep 5 minutes), and an
expired link waits for the next pass like a dropped network.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:37:57 -03:00
Cauê Faleiros
2ff11688bc fix: the folders change only the files of orders the server answered for
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 8m7s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m21s
The Kanban asks the server about at most 1000 orders a pass; an order left
out had no state in the answer and was taken for deleted, so its files left
the folders although it was still in Correção or Revisão. Orders still in
the flow are asked first, then those in Finalizado, and a file whose order
was not asked this pass stays as it is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:25:20 -03:00
Cauê Faleiros
a652d734ea ci: run again (run 383: the cancelled run 381 left the test Site pointing at the old API, 502)
All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 7m56s
Build and deploy / Secret scan and release gate (push) Successful in 4s
Build and deploy / Publish images (push) Successful in 1m41s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:06:14 -03:00
Cauê Faleiros
48d8b2f434 ci: the release gate no longer looks for the worker's fake Tiny, which production no longer uses
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 49s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Has been skipped
Since 4a1994b the production worker uses the real Tiny or holds the sends,
never the simulator; the marker no longer named something true, and the
fast checks failed on it (validate job).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:04:38 -03:00
Cauê Faleiros
4a1994bd06 fix: deleting a cancelled order keeps its Tiny cancellation, and production without the real Tiny holds the sends
Some checks failed
Build and deploy / Validate source (push) Failing after 7s
Build and deploy / Integration suite on a real stack (push) Has been skipped
Build and deploy / Secret scan and release gate (push) Has been skipped
Build and deploy / Publish images (push) Has been skipped
- Deleting an order removed its Tiny events, delivered or not: cancelled
  and deleted before the worker sent it (or with Tiny down), the order stayed
  open in Tiny. A real order's events now stay; only a test order's go.
- With TINY_ADAPTER missing from the production stack, the simulator marked
  paid orders delivered with made-up receipts, and they had to be queued
  again by hand. Production now holds the sends (the outbox retries and
  Sentry is told); with the real Tiny back, the worker sends them at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:04:01 -03:00
Cauê Faleiros
bb6fb14b1a fix: the server refuses stacked pieces and files laid out at other proportions, and never cuts a strip with ink
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Secret scan and release gate (push) Has been cancelled
Build and deploy / Integration suite on a real stack (push) Has been cancelled
The price came from the layout the browser sent, checked only in part:
- Pieces on top of each other passed: 100 copies stacked in one place bill
  10 cm and print over each other. The layout validator now refuses any
  overlap.
- A file laid out at proportions it does not have (a 5 m sheet sent as
  10 cm) was found only by the print file, after payment. The quote now
  checks each raster file's proportions from the bytes it already reads.
- The empty strips the Site cuts from a ready sheet were cut on its word.
  The print file now reads them: a strip with ink sends the item to hand
  preparation with the reason, instead of printing the art cut off.

Test fixtures that laid real images out at impossible proportions now keep
the image's own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:56:00 -03:00
Cauê Faleiros
6970434e5d fix: a payment started in time is the order when approved late, a second payment is listed for a refund, a coupon's limit is checked at payment
All checks were successful
Build and deploy / Validate source (push) Successful in 13s
Build and deploy / Integration suite on a real stack (push) Successful in 8m10s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m17s
- A PIX paid in its last minutes after the quote's 24 h, or a card approved
  after Mercado Pago's review, was refused ("quote expired before payment"):
  money in, no order. A payment whose attempt began while the quote was
  valid is now honoured; a card in review keeps its quote, files and the
  reconciliation for 72 h.
- A second approved payment of the same cart (a PIX and a card) was taken
  for a re-sent approval and logged only. It is now listed on the Kanban as
  attention, with the order, for a refund.
- A coupon's uses were counted only when the cart was made, so carts made
  before it ran out, or before it was paused or ended, still paid with the
  discount. The intent checks it again and asks for a new cart without it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:29:58 -03:00
Cauê Faleiros
7454f6b840 fix: a cancelled order takes its open proof card, a renamed machine keeps its hot folder, a film is approved with all its parts
All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 8m8s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m11s
- Cancelling an order left its proof card not yet answered on the board,
  where it could still be pulled and printed. It is cancelled with it.
- The hot folder path was the machine's current name, so renaming a machine
  sent its next files to a folder FlexiPRINT does not watch. Each machine now
  keeps the folder it was created with (migration fills it with today's
  names); no other machine may take that name, and the machine form shows
  the folder.
- A final set with only some parts of a film was accepted, the #130 failure
  through the manual path. The server now refuses it and names the parts
  missing.
- The proof card note says up to 30 cm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:19:27 -03:00
43 changed files with 568 additions and 79 deletions

View File

@@ -232,7 +232,7 @@ class ObjectStorage(Protocol):
def part_url(self, key: str, upload_id: str, part: int, size: int) -> str: ...
def complete(self, key: str, upload_id: str, parts: list): ...
def size(self, key: str) -> int: ...
def download(self, key: str, name: str) -> str: ...
def download(self, key: str, name: str, expires: int = 300) -> str: ...
def fetch(self, key: str, path: str): ...
def store(self, key: str, path: str, content_type: str): ...
def health(self): ...
@@ -299,12 +299,12 @@ class LocalS3Storage:
"""Upload a file the service generated itself, such as a print file."""
self.patient.upload_file(path, self.bucket, key, ExtraArgs={'ContentType': content_type})
def download(self, key, name):
def download(self, key, name, expires=300):
from urllib.parse import quote
return self.public.generate_presigned_url('get_object', Params={
'Bucket': self.bucket, 'Key': key,
'ResponseContentDisposition': "attachment; filename*=UTF-8''" + quote(name, safe=''),
'ResponseContentType': 'application/octet-stream'}, ExpiresIn=300)
'ResponseContentType': 'application/octet-stream'}, ExpiresIn=expires)
def view(self, key, content_type, expires=3600):
"""A link to show an object in the page, not download it: the Kanban's

View File

@@ -16,6 +16,10 @@ from ...scanning import require_clean
from .common import FINAL_OK
router = APIRouter()
# The folders download a whole list of files, one after another, from links
# made when the list was asked for: with films of 10 m, 5 minutes ran out
# before the last ones began (erro 403). Only the team's computers see them.
FOLDER_LINK_SECONDS = 3600
def named_files(rows):
"""Each file named after its order and item, so a folder of them stays
@@ -39,7 +43,7 @@ def named_files(rows):
names.add(name)
files.append({'order': str(row['order_id']), 'state': row['state'], 'number': row['number'],
'item': row['item_index'] + 1, 'name': name, 'upload_id': str(row['upload_id']),
'url': storage.download(row['object_key'], name)})
'url': storage.download(row['object_key'], name, FOLDER_LINK_SECONDS)})
return files
@@ -163,7 +167,7 @@ def queue_hot(user=Depends(can('print'))):
watched = hotfolder.watched(c)
return {'folder': hotfolder.PRINTING_FOLDER,
'write': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name'],
'url': storage.download(keys[str(r['upload_id'])], r['name'])} for r in due],
'url': storage.download(keys[str(r['upload_id'])], r['name'], FOLDER_LINK_SECONDS)} for r in due],
'watch': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']}
for r in watched if r['state'] == 'written'],
'withdraw': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']}

View File

@@ -50,7 +50,11 @@ def delete_order(uid: UUID, user=Depends(can('manage'))):
cards = [r['id'] for r in c.execute('SELECT id FROM dtf_local.orders WHERE parent_id=%s', (uid,)).fetchall()]
for table in ('movements', 'order_files', 'print_files'):
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=ANY(%s)', ([uid] + cards,))
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',))
# A real order's Tiny events stay: its cancellation may not have
# reached Tiny yet (Tiny down, or deleted at once), and what was sent
# stays on record. A test order never goes to Tiny.
if test:
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (uid,))
if not test:
c.execute('UPDATE dtf_local.quotes SET discarded_at=COALESCE(discarded_at,now()), discarded_by=COALESCE(discarded_by,%s) WHERE id=%s',
@@ -73,6 +77,14 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))):
if not row:
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
hotfolder.stop(c, uid)
# Its proof card not yet answered goes with it: left on the board, it
# could still be pulled and printed for an order no one will take.
cards = c.execute('''UPDATE dtf_local.orders SET cancelled_at=now(), cancelled_by=%s, cancel_reason=%s,
version=version+1, updated_at=now()
WHERE parent_id=%s AND cancelled_at IS NULL AND proof_result IS NULL RETURNING id''',
(user, f"Pedido #{row['number']} cancelado: {body.note}", uid)).fetchall()
for card in cards:
hotfolder.stop(c, card['id'])
if payments.in_tiny(row):
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
(f'{uid}:paid:tiny',)).fetchone()

View File

@@ -11,7 +11,7 @@ import httpx
from fastapi import APIRouter, Depends, HTTPException, Request
from psycopg.types.json import Jsonb
from .. import payment_messages as messages, payments
from .. import coupons, payment_messages as messages, payments
from ..core import db
from ..core.auth import audit, client_ip, owner, rate_limit
from ..core.models import PaymentIntent
@@ -104,6 +104,15 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
raise HTTPException(404 if 'not found' in str(refusal) else 409, messages.quote_refusal(refusal))
if c.execute('SELECT 1 FROM dtf_local.orders WHERE quote_id=%s', (body.quote_id,)).fetchone():
raise HTTPException(409, 'Este pedido já foi pago.')
# A coupon's limits are spent at payment (app/coupons.py): one used up,
# paused or ended since the cart was made no longer gives its discount.
coupon = quote['approved'].get('coupon')
if coupon:
try:
coupons.check(c, coupon['code'], (quote['approved'].get('customer') or {}).get('cnpj'),
quote['approved']['items'])
except HTTPException as refusal:
raise HTTPException(409, f'{refusal.detail} Monte o carrinho de novo, sem o cupom, para pagar.')
# Never charge for files that are gone: an unpaid cart's files are
# removed after a while. A payment under way keeps them a day longer,
# time enough for the provider's notice to become the order.
@@ -113,7 +122,8 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
if live != len(set(uploads)):
raise HTTPException(410, 'Os arquivos deste pedido expiraram porque ele não foi pago a tempo. '
'Monte o pedido de novo para pagar.')
payments.hold_uploads(c, uploads, '1 day')
# A card may sit in review for days (payments.CARD_REVIEW_HOURS).
payments.hold_uploads(c, uploads, f'{payments.CARD_REVIEW_HOURS} hours' if body.method.type == 'card' else '1 day')
# Never a second charge: an approved payment is waiting for its
# notification to become the order, and a card in review may still be.
# A card waiting for the bank's confirmation (3-D Secure) blocks only

View File

@@ -13,7 +13,7 @@ from ..core import db
from ..core.auth import owner
from ..core.models import QuoteRequest
from .. import quote_review
from ..grade_check import Files, mismatch, resolution_issue, source_dpi
from ..grade_check import Files, mismatch, proportion_issue, resolution_issue, source_dpi
from ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
from ..scanning import require_clean
@@ -79,7 +79,7 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
dpis.append(dpi)
if dpis:
draft_item['source_dpi'] = round(min(dpis))
issue = resolution_issue(files, draft['items'], rows)
issue = proportion_issue(files, draft['items'], rows) or resolution_issue(files, draft['items'], rows)
if issue:
raise HTTPException(422, issue)
note = mismatch(files, draft['items'], rows) if reason is None else None

View File

@@ -269,11 +269,14 @@ def list_machines(user=Depends(can('view'))):
def create_machine(body: MachineIn, user=Depends(can('users'))):
mid = uuid4()
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone():
raise HTTPException(409, 'Já existe uma máquina com este nome.')
c.execute('''INSERT INTO dtf_local.machines(id,name,products,active,limit_metres,places)
VALUES(%s,%s,%s,%s,%s,%s)''', (mid, body.name.strip(), sorted(set(body.products)), body.active,
body.limit_metres, body.places or machines.DEFAULT_PLACES))
# A machine's hot folder is its first name, for good: no other machine
# may be called that, or two would share one folder.
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) OR lower(folder)=lower(%s)',
(body.name.strip(), body.name.strip())).fetchone():
raise HTTPException(409, 'Já existe uma máquina, ou a pasta de uma máquina, com este nome.')
c.execute('''INSERT INTO dtf_local.machines(id,name,folder,products,active,limit_metres,places)
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (mid, body.name.strip(), body.name.strip(), sorted(set(body.products)),
body.active, body.limit_metres, body.places or machines.DEFAULT_PLACES))
audit('machine_created', operator=user, machine=body.name)
return {'id': str(mid)}
@@ -281,9 +284,9 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
@router.post('/api/operator/machines/{mid}')
def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s',
(body.name.strip(), mid)).fetchone():
raise HTTPException(409, 'Já existe uma máquina com este nome.')
if c.execute('''SELECT 1 FROM dtf_local.machines WHERE (lower(name)=lower(%s) OR lower(folder)=lower(%s))
AND id<>%s''', (body.name.strip(), body.name.strip(), mid)).fetchone():
raise HTTPException(409, 'Já existe uma máquina, ou a pasta de uma máquina, com este nome.')
if not c.execute('''UPDATE dtf_local.machines SET name=%s,products=%s,active=%s,limit_metres=%s,
places=COALESCE(%s,places) WHERE id=%s RETURNING id''',
(body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres,

View File

@@ -74,6 +74,20 @@ def submit_files(c, order, body, identity, kind, actor):
current = {(row['upload_id'], row['item_index']) for row in c.execute(
"SELECT upload_id,item_index FROM dtf_local.order_files WHERE order_id=%s AND kind='final' AND active",
(order['id'],)).fetchall()} if kind == 'final' else set()
# A film in parts is approved whole: with only some of its parts, the
# others never reach the folders or the machine (#114, #128, #130).
if kind == 'final':
sent = {}
for ref in body.files:
sent.setdefault(ref.item_index, set()).add(str(ref.upload_id))
for row in c.execute('''SELECT item_index, array_agg(upload_id::text ORDER BY part) AS uploads,
array_agg(part ORDER BY part) AS numbers FROM dtf_local.print_parts WHERE order_id=%s
GROUP BY item_index HAVING count(*) > 1''', (order['id'],)).fetchall():
mine = sent.get(row['item_index'], set())
missing = [n for n, u in zip(row['numbers'], row['uploads']) if u not in mine]
if mine & set(row['uploads']) and missing:
raise HTTPException(422, f"O filme do item {row['item_index'] + 1} tem {len(row['uploads'])} partes: "
f"envie todas (faltam {', '.join('p' + str(n) for n in missing)}).")
kept = {ref.upload_id for ref in body.files if (ref.upload_id, ref.item_index) in current}
if kept and len(kept) == len(body.files):
raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.')

View File

@@ -291,6 +291,17 @@ class Item(StrictModel):
raise ValueError('Finished sheets must retain their original orientation')
if placed != expected:
raise ValueError('Production layout does not cover every source copy')
# No piece on top of another: stacked pieces bill less film than they
# print on, and print over each other. Swept down the film, so only
# the pieces still open at each row are compared.
boxes = sorted((p.y_cm, p.y_cm + p.length_cm, p.x_cm, p.x_cm + p.width_cm)
for p in self.production.placements)
open_boxes = []
for top, bottom, left, right in boxes:
open_boxes = [b for b in open_boxes if b[0] > top + tolerance]
if any(l < right - tolerance and left < r - tolerance for _, l, r in open_boxes):
raise ValueError('Duas peças da montagem ficaram uma sobre a outra. Monte o pedido de novo.')
open_boxes.append((bottom, left, right))
if self.quality_status == 'warning' and not self.quality_acknowledged:
raise ValueError('Resolution warning must be acknowledged')
return self

View File

@@ -8,6 +8,19 @@ import os
import re
from decimal import Decimal, ROUND_CEILING
# Billed in steps of 10 cm, with 8 mm of grace for the customer (Marcus,
# 2026-11-27): a length that passes a step by up to 8 mm is billed at that
# step, by more at the next one. The Site rounds the same (web/site-config.js).
STEP_GRACE_M = Decimal('0.008')
def billed_length(length):
"""The metres billed for `length` metres, before any minimum; never 0 for
a sheet that has a length."""
steps = ((Decimal(str(length)) - STEP_GRACE_M) * 10).to_integral_value(rounding=ROUND_CEILING)
return max(Decimal('0.1'), steps / 10)
PRICES = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990, 'premium': 3990}
# A finished sheet the Site cannot open (CDR, AI, PSD, TIFF) is opened by a
@@ -55,7 +68,7 @@ def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Dec
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(minimum, (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10)
billed = max(minimum, billed_length(length))
if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
raise ValueError('Invalid extra charge')
unit = (PRICES[mode] if unit_cents is None else unit_cents) + extra_cents

View File

@@ -227,6 +227,35 @@ def resolution_issue(files, items, rows):
return None
def proportion_issue(files, items, rows):
"""Why a cart's layout cannot be priced, or None: a raster file laid out
at proportions it does not have (a 5 m sheet sent as 10 cm, say). The
print file refuses the same thing (app/printfile.py check_layout), but
only after payment; here it is refused before. A PDF, or a file whose
size the first bytes do not tell, is left to that later check."""
from .printfile import ASPECT_TOLERANCE
for index, item in enumerate(items, 1):
for number, source in enumerate(item['production']['sources'], 1):
row = rows.get(str(source['upload_id']))
if not row or row['name'].lower().endswith('.pdf'):
continue
size = image_size(files.head(row))
if not size or not all(size):
continue
width_px, height_px = size
if source.get('rotation_degrees') in (90, 270):
width_px, height_px = height_px, width_px
# A ready sheet's empty strips were cut from its length: the file
# is the length plus both strips (app/core/models.py).
length = (float(source['length_cm']) + float(source.get('trim_top_cm') or 0)
+ float(source.get('trim_bottom_cm') or 0))
drift = abs((width_px / height_px) / (float(source['width_cm']) / length) - 1)
if drift > ASPECT_TOLERANCE:
return (f'Item {index}: o arquivo {number} foi montado com {source["width_cm"]} × '
f'{source["length_cm"]} cm, que não são as proporções dele. Monte o pedido de novo.')
return None
def mismatch(files, items, rows):
"""Why a cart's grades cannot be approved at checkout, or None."""
for item in items:

View File

@@ -119,12 +119,12 @@ def claim(c, user):
they entered it, until the machine has its places' worth in its folder."""
c.execute('''UPDATE dtf_local.hot_parts SET state='queued', claimed_at=NULL, claimed_by=NULL
WHERE state='claimed' AND claimed_at < now() - %s''', (CLAIM_TIMEOUT,))
rows = c.execute('''SELECT h.*, o.machine_id, o.contraction, o.snapshot, m.name AS machine_name, m.places,
rows = c.execute('''SELECT h.*, o.machine_id, o.contraction, o.snapshot, COALESCE(m.folder, m.name) AS machine_folder, m.places,
(SELECT max(v.id) FROM dtf_local.movements v WHERE v.order_id=o.id AND v.to_state='imp') AS entered
FROM dtf_local.hot_parts h JOIN dtf_local.orders o ON o.id=h.order_id
JOIN dtf_local.machines m ON m.id=o.machine_id
WHERE h.state IN ('queued','claimed','written') AND o.state='imp' AND o.cancelled_at IS NULL
ORDER BY m.name, entered, h.order_id, h.seq FOR UPDATE OF h''').fetchall()
ORDER BY m.created_at, m.id, entered, h.order_id, h.seq FOR UPDATE OF h''').fetchall()
due, busy, blocked = [], {}, set()
for row in rows:
machine = row['machine_id']
@@ -139,7 +139,9 @@ def claim(c, user):
if busy.get(machine, 0) >= row['places'] or not cls:
blocked.add(order)
continue
folder = f"{row['machine_name']}/{cls}"
# The machine's folder, fixed at its creation: a renamed machine keeps
# the path FlexiPRINT watches.
folder = f"{row['machine_folder']}/{cls}"
c.execute('''UPDATE dtf_local.hot_parts SET state='claimed', claimed_at=now(), claimed_by=%s, folder=%s
WHERE id=%s''', (user, folder, row['id']))
busy[machine] = busy.get(machine, 0) + 1

View File

@@ -39,7 +39,8 @@ def loads(c):
def rows(c, with_operators=False):
"""Every machine with its load, for the Kanban."""
machines = c.execute('''SELECT id, name, products, active, limit_metres, places FROM dtf_local.machines
machines = c.execute('''SELECT id, name, COALESCE(folder, name) AS folder, products, active, limit_metres, places
FROM dtf_local.machines
ORDER BY created_at, name''').fetchall()
load = loads(c)
operators = {}
@@ -55,7 +56,7 @@ def rows(c, with_operators=False):
for m in machines:
key = str(m['id'])
used = load.get(key, {'metres': Decimal(0), 'orders': 0, 'states': {}})
row = {'id': key, 'name': m['name'], 'products': m['products'], 'active': m['active'],
row = {'id': key, 'name': m['name'], 'folder': m['folder'], 'products': m['products'], 'active': m['active'],
'limit_metres': float(m['limit_metres']) if m['limit_metres'] is not None else None,
'places': m['places'],
'open_metres': float(used['metres']), 'open_orders': used['orders'], 'states': used['states'],

View File

@@ -0,0 +1,5 @@
-- Each machine's hot folder (3. Imprimindo/<folder>/C1..) is fixed when the
-- machine is created: FlexiPRINT watches that path, so renaming the machine
-- must not send its files to a folder nobody watches (2026-11-27).
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS folder text;
UPDATE dtf_local.machines SET folder=name WHERE folder IS NULL;

View File

@@ -24,14 +24,20 @@ from .runtime import PUBLIC_ORIGIN, enqueue, upload_row
from .scanning import require_clean
QUOTE_VALID_HOURS = 24
# A card the provider holds "em análise" may be approved hours or days later:
# its quote stays open, its files kept and the provider asked this long.
CARD_REVIEW_HOURS = 72
class PaymentRefused(Exception):
"""The payment cannot become an order, with a reason worth recording."""
def approved_quote(c, quote_id, owner=None):
"""The reviewed quote behind a payment, or a refusal explaining why not."""
def approved_quote(c, quote_id, owner=None, payment_id=None):
"""The reviewed quote behind a payment, or a refusal explaining why not.
`payment_id`, from a provider's notice: a payment started while the quote
was valid is honoured whenever its approval arrives (a PIX paid in its
last minutes, a card approved after review)."""
sql = 'SELECT * FROM dtf_local.quotes WHERE id=%s' + (' AND owner=%s' if owner else '')
row = c.execute(sql + ' FOR UPDATE', (quote_id, owner) if owner else (quote_id,)).fetchone()
if not row:
@@ -42,8 +48,13 @@ def approved_quote(c, quote_id, owner=None):
raise PaymentRefused('quote was discarded')
if any(item.get('production', {}).get('version') not in PRODUCTION_VERSIONS for item in row['approved']['items']):
raise PaymentRefused('quote uses an obsolete production layout; request a new quote')
if row['approved_at'] < datetime.now(timezone.utc) - timedelta(hours=QUOTE_VALID_HOURS):
raise PaymentRefused('quote expired before payment')
deadline = row['approved_at'] + timedelta(hours=QUOTE_VALID_HOURS)
if deadline < datetime.now(timezone.utc):
started = payment_id and c.execute('''SELECT 1 FROM dtf_local.payment_intents
WHERE quote_id=%s AND provider_payment_id=%s AND created_at <= %s''',
(quote_id, str(payment_id), deadline)).fetchone()
if not started:
raise PaymentRefused('quote expired before payment')
return row
@@ -240,7 +251,7 @@ def apply(c, event):
return 'refused: reference is not a quote id'
try:
quote = approved_quote(c, quote_id)
quote = approved_quote(c, quote_id, payment_id=provider_id)
except PaymentRefused as refusal:
return f'refused: {refusal}'
@@ -255,7 +266,16 @@ def apply(c, event):
return f'refused: paid {event.amount_cents} but quote total is {expected}'
order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw}, 'site')
return f"order {order['number']}" + ('' if created else ' (already existed)')
if created:
return f"order {order['number']}"
# The order exists, paid by another payment (a PIX and a card for the same
# cart, or paid outside the site too): the customer paid twice. Listed on
# the Kanban until someone refunds one, like a reversal.
first = str((order.get('payment') or {}).get('payment_id') or '')
if provider_id and str(provider_id) != first:
audit('payment_duplicate', order=order['number'], payment=str(provider_id), c=c)
return f"attention: second payment {provider_id} for order {order['number']}; refund one"
return f"order {order['number']} (already existed)"
def reconcile(connect, provider, quote_id=None, limit=20):
@@ -273,7 +293,7 @@ def reconcile(connect, provider, quote_id=None, limit=20):
WHERE o.id IS NULL AND i.provider=%s AND i.status IN ('pending','approved')
AND i.created_at > now() - make_interval(hours => %s)''' +
(' AND i.quote_id=%s' if quote_id else '') + ' ORDER BY i.created_at DESC LIMIT %s',
(provider.name, QUOTE_VALID_HOURS + 1, *([quote_id] if quote_id else []), limit)).fetchall()
(provider.name, CARD_REVIEW_HOURS + 1, *([quote_id] if quote_id else []), limit)).fetchall()
outcomes = []
for row in rows:
# Asked outside any transaction: no lock is held while the provider answers.

View File

@@ -27,6 +27,7 @@ from decimal import Decimal
from PIL import Image, ImageOps
from .core.models import PRODUCTION_VERSIONS
from .core.pricing import STEP_GRACE_M
PT_PER_CM = 72 / 2.54
# Acrobat's page limit, 200 inches (5,08 m). A longer sheet is written at its
@@ -387,7 +388,8 @@ def check_layout(item, sizes, vector=(), proof=False):
production = item['production']
height = Decimal(str(production['height_cm']))
billed = Decimal(str(item['billed_metres'])) * 100
if not proof and height > billed + HEIGHT_TOLERANCE_CM:
# Up to 8 mm past the billed length is the customer's grace (app/core/pricing.py).
if not proof and height > billed + STEP_GRACE_M * 100 + HEIGHT_TOLERANCE_CM:
raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados')
lowest = None
for placement in production['placements']:

View File

@@ -48,6 +48,8 @@ PART_CM = Decimal(os.environ.get('PRINT_PART_CM', '1000'))
# A cut through artwork only when no gap between pieces is this close to the limit.
CUT_SEARCH_CM = Decimal('200')
BAND_ROWS = 512
# A pixel above this alpha takes ink (web/site-sheet.js ALFA_TINTA).
INK_ALPHA = 10
# Above this a source is read band by band instead of decoded whole.
STREAM_ABOVE_PIXELS = 40_000_000
FOOTER_TEXT_CM = 1.1
@@ -268,9 +270,44 @@ class Source:
top, bottom = round(height * top_cm / full_cm), round(height * bottom_cm / full_cm)
if top + bottom >= height:
raise Unsupported(f'"{self.name}": o corte das faixas vazias tiraria o arquivo inteiro')
self._require_clear(top, bottom)
self.cut = (top, bottom)
self.size = (width, height - top - bottom)
def _require_clear(self, top, bottom):
"""The strips the Site measured as empty must be: cut on a measure the
file does not bear out, artwork would leave the print unseen. A pixel
takes ink above INK_ALPHA, as the Site counts it. Not clear, or too
big to read here: the item goes to hand preparation, with the reason."""
width, height = self.size
where = lambda first: 'do começo' if first else 'do fim'
def check(band, offset):
for start, stop, first in ((0, top, True), (height - bottom, height, False)):
a, b = max(start, offset), min(stop, offset + band.height)
if a < b and rgba(band.crop((0, a - offset, band.width, b - offset))).getchannel('A').getextrema()[1] > INK_ALPHA:
raise Unsupported(f'"{self.name}": a faixa que o site cortou {where(first)} do arquivo tem arte. '
'Confira o arquivo e prepare a folha à mão')
if self.streamable:
reader = PngRows(self.path)
try:
done = 0
# Read in order to the end of the bottom strip (or of the top one).
while done < (height if bottom else top):
band = reader.band(BAND_ROWS)
if done < top or done + band.height > height - bottom:
check(band, done)
done += band.height
finally:
reader.close()
return
if width * height > MAX_DECODED_PIXELS:
raise Unsupported(f'"{self.name}" é grande demais para conferir as faixas cortadas; prepare a folha à mão')
with Image.open(self.path) as image:
image = ImageOps.exif_transpose(image) if self.orientation != 1 else image
check(image, 0)
def decoded(self, width, height):
"""The whole file at (width, height) px, upright, RGBA."""
if self.pdf:

View File

@@ -13,7 +13,7 @@ abandonment rate.
from datetime import datetime, timedelta, timezone
from . import mail, payments
from .payments import QUOTE_VALID_HOURS
from .payments import CARD_REVIEW_HOURS, QUOTE_VALID_HOURS
# An intent in one of these no longer waits for money: approved (it became an
# order), rejected, cancelled, expired or refunded (app/payments.py).
@@ -34,11 +34,12 @@ def expire(c, origin):
AND i.id = (SELECT i2.id FROM dtf_local.payment_intents i2
WHERE i2.quote_id=q.id ORDER BY i2.created_at DESC LIMIT 1)
AND i.status <> ALL(%s)
AND i.created_at > now() - make_interval(hours => %s)
-- a card in review may be approved days later (payments.CARD_REVIEW_HOURS)
AND i.created_at > now() - make_interval(hours => CASE WHEN i.method='card' THEN %s ELSE %s END)
AND (i.response->>'expires_at' IS NULL
OR (i.response->>'expires_at')::timestamptz > now()))
ORDER BY q.approved_at LIMIT 50 FOR UPDATE OF q SKIP LOCKED''',
(QUOTE_VALID_HOURS, list(FINAL_INTENT), QUOTE_VALID_HOURS + 1)).fetchall()
(QUOTE_VALID_HOURS, list(FINAL_INTENT), CARD_REVIEW_HOURS, QUOTE_VALID_HOURS + 1)).fetchall()
for row in rows:
c.execute('UPDATE dtf_local.quotes SET expired_at=now() WHERE id=%s', (row['id'],))
# expired_at is set first: release_files must no longer see this quote

View File

@@ -17,12 +17,37 @@ from .scanning import ClamAV, scan_loop
load_secret_files()
require_runtime()
adapters = {'tiny': FakeTiny()}
# Not yet confirmed against the client's account; see app/tiny.py.
if os.environ.get('TINY_ADAPTER') == 'tiny':
from .tiny import TinyOrders
from .cnpj import company
adapters['tiny'] = TinyOrders(names=company)
# Production without the real Tiny (TINY_ADAPTER missing from the stack):
# the sends wait and Sentry is told, instead of the simulator marking real
# orders delivered with made-up receipts that had to be queued again by hand.
HELD = 'Tiny desligado em produção (TINY_ADAPTER não é tiny): o envio espera'
class HeldTiny:
def deliver(self, event_key, payload):
raise RuntimeError(HELD)
def tiny_adapter(adapter=None, environment=None):
"""The Tiny the outbox delivers to: the real one when configured; in
production otherwise none (HeldTiny); elsewhere the simulator."""
adapter = os.environ.get('TINY_ADAPTER') if adapter is None else adapter
environment = os.environ.get('APP_ENV', 'local') if environment is None else environment
if adapter == 'tiny':
from .tiny import TinyOrders
from .cnpj import company
return TinyOrders(names=company)
return HeldTiny() if environment == 'production' else FakeTiny()
adapters = {'tiny': tiny_adapter()}
def release_held(c):
"""With the real Tiny back, the sends held meanwhile go at once instead
of after their back-off."""
return c.execute('''UPDATE dtf_local.outbox SET available_at=now() WHERE provider='tiny'
AND delivered_at IS NULL AND last_error=%s''', (HELD,)).rowcount
last_tick = 0.0
last_cleanup = 0.0
last_reconcile = 0.0
@@ -199,6 +224,14 @@ class Health(BaseHTTPRequestHandler):
if __name__ == '__main__':
observability.init('worker')
if isinstance(adapters['tiny'], HeldTiny):
logging.error('Worker started in production without the real Tiny: Tiny sends are held')
elif not isinstance(adapters['tiny'], FakeTiny):
try:
with connect() as c:
release_held(c)
except Exception:
logging.exception('Could not release the Tiny sends held while Tiny was off')
scan_thread = threading.Thread(target=scan_loop,args=(storage,),daemon=True)
scan_thread.start()
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)

View File

@@ -41,9 +41,9 @@ SOURCE_BLOCKERS = {
'app/runtime.py': (
'payment = FakePayment()',
),
'app/worker.py': (
"adapters = {'tiny': FakeTiny()}",
),
# app/worker.py's "adapters = {'tiny': FakeTiny()}" left on 2026-11-27: in
# production the worker uses the real Tiny or holds the sends (HeldTiny),
# never the simulator.
}

View File

@@ -122,7 +122,6 @@ class ProductionPreflightTests(unittest.TestCase):
def test_fake_checkout_is_explicitly_blocked(self):
errors = source_errors()
self.assertTrue(any('app/runtime.py remains local-only' in error for error in errors))
self.assertTrue(any('app/worker.py remains local-only' in error for error in errors))
def test_secret_reuse_and_incoherent_limits_are_rejected(self):
values = valid_config()

View File

@@ -33,15 +33,16 @@ def run():
manager = manager.operator_client
coupon_id = None
quote_id = None
early_id = None
order_id = None
upload_id = None
try:
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-COUPON-{tag}.png')
sheet = {**item_spec('uvfile', '1', 0, upload_id),
sheet = {**item_spec('uvfile', '1', 0, upload_id, aspect=2),
'quality_status': 'warning', 'quality_acknowledged': True}
# The sheet is the customer's own file, not one someone opens by hand.
sheet['production']['sources'][0]['measurement'] = 'file'
art = {**item_spec('uv', '1', 0, upload_id),
art = {**item_spec('uv', '1', 0, upload_id, aspect=2),
'quality_status': 'warning', 'quality_acknowledged': True}
items = [sheet, art]
@@ -61,6 +62,9 @@ def run():
assert [line['total_cents'] for line in approved['items']] == [7990, 8990], approved
assert approved['total_cents'] == 16081, approved
# A second cart with the coupon, made while it still had uses.
early_id = quote(client, items, code, mail)['id']
# One paid order spends a use (a fake payment, no print job).
order_id = uuid4()
with db.connect() as c:
@@ -110,6 +114,10 @@ def run():
manager.call('/operator/site/coupons/' + coupon_id, {'max_uses': 1})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Este cupom já foi usado o máximo de vezes.', refused
# The limit is spent at payment: the cart made before it ran out no
# longer pays with its discount.
refused = client.call('/payments/intent', {'quote_id': early_id, 'method': {'type': 'pix'}}, expected=409)
assert 'máximo de vezes' in refused['detail'] and 'sem o cupom' in refused['detail'], refused
manager.call('/operator/site/coupons/' + coupon_id,
{'max_uses': None, 'max_uses_per_customer': 1})
refused = quote(client, items, code, mail, expected=422)
@@ -135,13 +143,16 @@ def run():
stats = manager.call('/operator/stats?days=30')
assert any(entry['id'] == coupon_id for entry in stats['coupons']), stats['coupons']
print('PASS: a coupon discounts one product, refuses paused/expired/not-started/'
'minimum/product/use states, reaches Tiny data and Números, and soft delete keeps history')
'minimum/product/use states, also at payment, reaches Tiny data and Números, and soft delete keeps history')
finally:
with db.connect() as c:
if order_id:
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,))
if quote_id:
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote_id,))
if early_id:
c.execute('DELETE FROM dtf_local.payment_intents WHERE quote_id=%s', (early_id,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (early_id,))
if coupon_id:
c.execute('DELETE FROM dtf_local.coupons WHERE id=%s', (coupon_id,))
if upload_id:

View File

@@ -44,7 +44,7 @@ def run():
assert rules['treatment_offered'] is True, rules
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-GRADE-{tag}.png')
item = {**item_spec('uv', '1', 50, upload_id),
item = {**item_spec('uv', '1', 50, upload_id, aspect=2),
'quality_status': 'warning', 'quality_acknowledged': True}
refused = client.call('/quotes', quote_body(item, False, mail), expected=422)

View File

@@ -109,6 +109,10 @@ def run():
client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True)
with db.connect() as c:
assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (paid_order,)).fetchone()
# Its cancellation still goes to Tiny: deleted at once, or with Tiny
# down, it must not be lost with the order.
assert c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s',
(f'{paid_order}:cancelled:tiny',)).fetchone(), 'the Tiny cancellation was lost'
# Deleted: no state at all, so the folder removes its files too.
assert client.call('/operator/queue/folder', {'held': [str(paid_order)]}, operator=True)['states'] == {}
with db.connect() as c:
@@ -156,7 +160,7 @@ def run():
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([gone_quote, other_quote, test2_quote],))
c.execute('DELETE FROM dtf_local.uploads WHERE id=ANY(%s)', (list(files.values()),))
print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel, then delete '
print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel, then delete, keeping the Tiny cancellation, '
'and free their files')
finally:
with db.connect() as c:

View File

@@ -121,7 +121,12 @@ def run():
later = deliver({**payload, 'event_id': 'retry-' + uuid4().hex})
assert 'already existed' in later.get('outcome', ''), later
assert customer.call('/quotes/' + quote_id)['order']['id'] == order['id'], 'a second order appeared'
print('PASS: one order from a repeated and re-sent approval')
# Another payment of the same cart (a PIX and a card): the customer paid
# twice, and it is listed for a refund, not taken for a re-sent approval.
second = deliver({**payload, 'event_id': 'second-' + uuid4().hex, 'payment_id': 'second-' + uuid4().hex[:8]})
assert second.get('outcome', '').startswith('attention: second payment'), second
assert customer.call('/quotes/' + quote_id)['order']['id'] == order['id'], 'a second order appeared'
print('PASS: one order from a repeated and re-sent approval; a second payment is listed for a refund')
assert customer.call('/orders/dev-paid', {'quote_id': quote_id})['id'] == order['id']
other = Client()

View File

@@ -155,6 +155,9 @@ def run():
mine = [f for f in early['files'] if f['order'] == oid]
assert [(f['upload_id'], f['state']) for f in mine] == [(str(row['upload_id']), 'rec')], early['files']
assert mine[0]['name'].startswith('DTF-%d-item-1' % order['number']) and early['states'] == {oid: 'rec'}
# The folders download a whole list one file after another: an hour's link,
# not the 5 minutes that ran out before the last ones began.
assert 'X-Amz-Expires=3600' in mine[0]['url'], mine[0]['url']
late = client.call('/operator/queue/folder', {'early': False, 'held': []}, operator=True)
assert not [f for f in late['files'] if f['order'] == oid] and late['states'] == {}
client.call('/operator/queue/folder', {'early': True, 'held': []}, expected=401)
@@ -251,6 +254,13 @@ def run():
# No class measured or chosen: the part waits for one.
assert not [p for p in client.call('/operator/queue/hot', {}, operator=True)['write'] if p['order'] == oid]
client.call('/operator/orders/' + oid + '/contraction', {'item_index': 0, 'value': 'C2'}, operator=True)
# Renamed, the machine keeps its folder, the path FlexiPRINT watches;
# no other machine may then take that folder's name.
client.call('/operator/machines/' + machine, {'name': f'Hot {tag} renomeada', 'products': ['textil']},
operator=True)
listed = next(m for m in client.call('/operator/machines', operator=True)['machines'] if m['id'] == machine)
assert listed['name'] == f'Hot {tag} renomeada' and listed['folder'] == f'Hot {tag}', listed
client.call('/operator/machines', {'name': f'Hot {tag}', 'products': ['textil']}, operator=True, expected=409)
hot = client.call('/operator/queue/hot', {}, operator=True)
due = [p for p in hot['write'] if p['order'] == oid]
assert hot['folder'] == '3. Imprimindo' and [(p['folder'], p['name']) for p in due] == \
@@ -269,7 +279,8 @@ def run():
assert board['hot'] == {'parts': 1, 'taken': 1, 'waiting': 0}, board['hot']
# Which items go again is chosen before Imprimindo, not while printing (#105).
client.call('/operator/orders/' + oid + '/print-items', {'items': [0]}, operator=True, expected=409)
print('PASS: the printing file goes once into its machine\'s hot folder for its class')
print('PASS: the printing file goes once into its machine\'s hot folder for its class, '
'and a renamed machine keeps its folder')
finally:
client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False},
operator=True)
@@ -444,6 +455,36 @@ def run():
(f"{parent['id']}:production_started:tiny",)).fetchone()
print('PASS: a file finished after Prova OK becomes the final, queues the order and tells Tiny')
# Cancelled, an order takes its proof card not yet answered with it: left
# on the board, the card could still be pulled and printed.
readable = upload_bytes(client, artwork(), name='LOCAL-PROOF-CANCEL.png')
parent = paid_order(client, loose_item(readable, copies=1))
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{proof}','true') WHERE id=%s",
(parent['id'],))
card = client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True)
client.call('/operator/orders/' + parent['id'] + '/cancel', {'note': 'cliente desistiu'}, operator=True)
with db.connect() as c:
gone = c.execute('SELECT cancelled_at, cancel_reason FROM dtf_local.orders WHERE id=%s', (card['id'],)).fetchone()
assert gone['cancelled_at'] and 'cliente desistiu' in gone['cancel_reason'], gone
print('PASS: cancelling an order cancels its open proof card')
# A film in parts is approved whole: only some of its parts are refused,
# or the others never reach the machine (#114, #128, #130).
whole = upload_bytes(client, artwork(), name='LOCAL-PARTS.png')
film = paid_order(client, loose_item(whole, copies=1))
_, film_row = wait_print(client, film['id'], 'ready')
second = upload_bytes(client, artwork(), name='LOCAL-PARTS-P2.png')
with db.connect() as c:
c.execute('INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id) VALUES(%s,0,2,%s)',
(film['id'], second))
refused = client.call('/operator/orders/' + film['id'] + '/final-files',
{'version': version_of(film['id']), 'note': 'só a primeira',
'files': [{'item_index': 0, 'upload_id': str(film_row['upload_id'])}]},
operator=True, expected=422)
assert 'faltam p2' in refused['detail'], refused
print('PASS: a film in parts is approved with all its parts or not at all')
# Reprinting some items (Marcus, 2026-11-26, #105): an order the machine
# already printed, back in the queue after one item's final changed, sends
# only that item; the pass to Revisão keeps it for the machine's metres and

View File

@@ -27,6 +27,7 @@ def run():
quote, payment_id = uuid4(), str(900_000_000 + uuid4().int % 99_999_999)
approved = {'customer': {'mail': 'reconcile@example.test'}, 'items': [], 'total_cents': 1490}
order_id = None
extra = []
try:
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
@@ -55,7 +56,36 @@ def run():
asked = paid.asked
assert payments.reconcile(db.connect, paid, quote_id=quote) == [] and paid.asked == asked
print('PASS: an approved payment is found by asking the provider; a short one is refused; each applies once')
# Approved after the quote's 24 h: a payment started in time (a PIX paid
# in its last minutes, a card approved after review) is the order; one
# started after the deadline is refused.
for started, expected in (("now()-interval '3 hours'", 'order '), ("now()-interval '1 hour'", 'refused: quote expired')):
late, late_payment = uuid4(), str(800_000_000 + uuid4().int % 99_999_999)
extra.append((late, late_payment))
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'reconcile-fixture',%s,%s,now()-interval '26 hours')''',
(late, uuid4(), uuid4(), Jsonb({'customer': approved['customer'], 'items': []}), Jsonb(approved)))
c.execute(f'''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,status,
amount_cents,response,created_at) VALUES(%s,%s,'mercadopago',%s,'card','pending',1490,'{{}}',{started})''',
(uuid4(), late, late_payment))
provider = Provider({'id': late_payment, 'status': 'approved', 'currency_id': 'BRL',
'transaction_amount': 14.9, 'external_reference': str(late)})
outcomes = payments.reconcile(db.connect, provider, quote_id=late)
assert len(outcomes) == 1 and outcomes[0].startswith(expected), (started, outcomes)
print('PASS: a payment started within the 24 h is the order whenever approved; one started later is refused')
finally:
for late, late_payment in extra:
with db.connect() as c:
for row in c.execute('SELECT id FROM dtf_local.orders WHERE quote_id=%s', (late,)).fetchall():
c.execute("DELETE FROM dtf_local.outbox WHERE event_key LIKE %s", (f"{row['id']}:%",))
c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (row['id'],))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (row['id'],))
c.execute("DELETE FROM dtf_local.payment_events WHERE provider='mercadopago' AND event_id LIKE %s",
(f'{late_payment}:%',))
c.execute('DELETE FROM dtf_local.payment_intents WHERE quote_id=%s', (late,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (late,))
with db.connect() as c:
if order_id:
c.execute("DELETE FROM dtf_local.outbox WHERE event_key LIKE %s", (f'{order_id}:%',))

View File

@@ -40,12 +40,13 @@ def quote(client, item, mail, expected=200):
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,
"""One loose-art item with `arts` sources of 10 x 5 cm (artwork() is 2:1),
one every 10 cm."""
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 5,
'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}
'width_cm': 10, 'length_cm': 5, '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,
@@ -76,7 +77,7 @@ def run():
assert premium_entry['title'] == 'Têxtil Premium · 8 passadas', premium_entry
assert client.call('/session')['products'][PREMIUM]['enabled'] is False
premium_item = {**item_spec(PREMIUM, '1', 0, upload_bytes(
client, premium_sheet(), name='LOCAL-SITE-PREMIUM.png')),
client, premium_sheet(), name='LOCAL-SITE-PREMIUM.png'), aspect=3),
'quality_status': 'warning', 'quality_acknowledged': True}
refused = quote(client, premium_item, mail, expected=422)
assert refused['detail'] == 'Este produto não está à venda agora.', refused
@@ -188,7 +189,7 @@ def run():
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}
item = {**item_spec('uv', '1', 0, uid, aspect=2), 'quality_status': 'warning', 'quality_acknowledged': True}
before = client.call('/session')['products'][UV]['unit_cents']
# Switched off: the Site sees it off and the server refuses a new quote.

View File

@@ -140,11 +140,15 @@ def review_photo(client, order_id):
wait_scan(client,uid,operator=True)
return client.call('/operator/orders/'+order_id+'/reviews',{'upload_id':uid},operator=True)
def item_spec(mode, metres, grade, uid):
def item_spec(mode, metres, grade, uid, aspect=None):
"""One file across the film, `metres` long. `aspect` (width / length) for
a real image: the piece then keeps the file's proportions, as the server
checks, inside the same billed length."""
film_width=27 if mode in ('uvfile','uv') else 57
length_cm=float(metres)*100
height_cm=float(metres)*100
length_cm=round(film_width/aspect,4) if aspect else height_cm
return {'mode':mode,'metres':str(metres),'grade':grade,'uploads':[uid],
'production':{'version':2,'film_width_cm':film_width,'height_cm':length_cm,
'production':{'version':2,'film_width_cm':film_width,'height_cm':height_cm,
'sources':[{'upload_id':uid,
'kind':'sheet' if mode in ('file','uvfile','premium') else 'artwork',
'width_cm':film_width,'length_cm':length_cm,'copies':1,
@@ -249,10 +253,11 @@ def run():
# A cart the Site priced is approved at once and can be paid straight away,
# at the server's own prices; no operator can then change it.
# The server works the grade out from the file: this PNG is 6059 px across
# 57 cm, 270 DPI, which is grade 100 under the 200 DPI clean threshold.
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
# 57 cm, 270 DPI, which is grade 100 under the 200 DPI clean threshold;
# 29232 px long, the 275 cm it is laid out at (the server checks it).
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(29232).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
graded=upload_bytes(client,png,name='arte-270dpi.png')
low_png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(3366).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
low_png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(3366).to_bytes(4,'big')+(16240).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
low=upload_bytes(client,low_png,name='arte-150dpi.png')
small={**draft,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,graded)]}
auto=client.call('/quotes',small)
@@ -283,7 +288,11 @@ def run():
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}}
# Each sheet's own file, 6059 px across 57 cm, as long as the sheet.
header=lambda rows:b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+rows.to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
sheet_files={'0.3':upload_bytes(client,header(3189),name='folha-30.png'),
'0.15':upload_bytes(client,header(1594),name='folha-15.png')}
part=lambda metres,n,mode='avulsa':{**item_spec(mode,metres,90,sheet_files[metres]),'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)

View File

@@ -165,8 +165,10 @@ class CartPricingCharacterizationTest(unittest.TestCase):
split = priced('split-under-one-metre')
self.assertEqual([(p['billed_metres'], p['total_cents']) for p in split],
[('0.8', 1752), ('0.2', 438)])
# A float's noise past 2,80 m is inside the 8 mm grace (Marcus,
# 2026-11-27): billed 2,80 m at the band from 2,8 m, no longer 2,90 m.
floating = priced('band-floating-metres')[0]
self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.9', 24650))
self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.8', 23800))
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

View File

@@ -158,5 +158,33 @@ class GradeCheckTests(unittest.TestCase):
self.assertIn('confirme a ressalva', issue(199.4))
class ProportionTests(unittest.TestCase):
"""A file laid out at proportions it does not have is refused before
payment, not found at print time (a 5 m sheet sent as 10 cm)."""
def cart(self, length, rotation=0, top=0, bottom=0, name='sheet.png'):
source = {'upload_id': name, 'kind': 'sheet', 'width_cm': 57, 'length_cm': length,
'rotation_degrees': rotation, 'trim_top_cm': top, 'trim_bottom_cm': bottom}
return [{'production': {'sources': [source]}}], {name: {'name': name}}
def test_the_files_own_proportions_pass(self):
files = FakeFiles({'sheet.png': encoded('PNG', (570, 1000)), 'turned.png': encoded('PNG', (1000, 570))})
for args in ((100,), (90, 0, 4, 6)):
items, rows = self.cart(*args)
self.assertIsNone(grade_check.proportion_issue(files, items, rows), args)
items, rows = self.cart(100, 90, name='turned.png')
self.assertIsNone(grade_check.proportion_issue(files, items, rows))
def test_other_proportions_are_refused(self):
files = FakeFiles({'sheet.png': encoded('PNG', (570, 50000))})
items, rows = self.cart(10)
self.assertIn('não são as proporções', grade_check.proportion_issue(files, items, rows))
def test_a_pdf_is_left_to_the_print_file(self):
files = FakeFiles({})
items, rows = self.cart(10, name='sheet.pdf')
self.assertIsNone(grade_check.proportion_issue(files, items, rows))
if __name__ == '__main__':
unittest.main()

View File

@@ -16,9 +16,14 @@ class PricingTests(unittest.TestCase):
source = Path('web/site-config.js').read_text()
prices = source.split('const PRECO=')[1].split(';',1)[0]
calculator = source.split('const cobrar=')[1].split(';',1)[0]
js = f'const PRECO={prices};const MINIMO_M=1;const cobrar={calculator};'
# Every 10 cm with 8 mm of grace (Marcus, 2026-11-27): the Site's own rounding.
grace = source.split('const TOLERANCIA_M=')[1].split(';',1)[0]
rounding = source.split('const arredonda10=')[1].split(';',1)[0]
js = (f'const PRECO={prices};const MINIMO_M=1;const TOLERANCIA_M={grace};'
f'const arredonda10={rounding};const cobrar={calculator};')
js += '''const results=[];for(const mode of Object.keys(PRECO))
for(const metres of [0.01,0.99,1,1.01,1.1,2.75,2.8,2.8000000000000003,19.99,60,12000]){
for(const metres of [0.01,0.99,1,1.01,1.1,2.75,2.8,2.8000000000000003,19.99,60,12000,
1.008,1.0081,4.452,6.001,6.008,6.0081,6.009,5.992]){
const unit=PRECO[mode];
results.push([mode,String(metres),cobrar(metres),Math.round(unit*100),Math.round(cobrar(metres)*unit*100)]);
}process.stdout.write(JSON.stringify(results));'''
@@ -32,6 +37,18 @@ class PricingTests(unittest.TestCase):
self.assertEqual(result['unit_cents'],unit)
self.assertEqual(result['total_cents'],total)
def test_every_10_cm_with_8_mm_in_the_customers_favour(self):
# Marcus, 2026-11-27: up to 8 mm past a step stays in it, more goes on.
from app.core.pricing import billed_length
for metres, billed in (('6.001', '6'), ('6.008', '6'), ('6.0081', '6.1'), ('6.009', '6.1'),
('4.452', '4.5'), ('4.42', '4.5'), ('2.75', '2.8'), ('0.005', '0.1')):
with self.subTest(metres=metres):
self.assertEqual(billed_length(metres), Decimal(billed))
# Marcus's two examples: 3 copies of ~199,5 cm with 8 mm between them,
# and 5 copies of 88,4 cm.
self.assertEqual(price('file', '6.001', 100)['billed_metres'], '6')
self.assertEqual(price('file', '4.452', 100)['billed_metres'], '4.5')
def test_one_price_per_product(self):
# Dropstar, 2026-10-23: textile R$ 19,90 ready sheet and R$ 21,90 loose
# art; UV R$ 79,90 and R$ 89,90. Premium R$ 39,90 (2026-11-10).

View File

@@ -39,6 +39,36 @@ class SheetGapTests(unittest.TestCase):
self.assertEqual(str(caught.exception), SHEET_GAP_CHANGED)
def loose(xs_ys):
upload = str(uuid4())
placements = [{'source_index': 0, 'copy_index': i, 'x_cm': x, 'y_cm': y, 'width_cm': 20, 'length_cm': 10,
'rotation_degrees': 0, 'mirrored': False} for i, (x, y) in enumerate(xs_ys)]
height = max(y for _, y in xs_ys) + 10
return {'mode': 'avulsa', 'metres': str(height / 100), 'grade': 100, 'uploads': [upload],
'quality_status': 'ok', 'quality_acknowledged': False,
'production': {'version': 3, 'film_width_cm': 57, 'height_cm': height,
'sources': [{'upload_id': upload, 'kind': 'artwork', 'width_cm': 20, 'length_cm': 10,
'copies': len(xs_ys), 'measurement': 'file'}],
'placements': placements}}
class OverlapTests(unittest.TestCase):
"""Pieces stacked on each other bill less film than they print on: the
server refuses them, whatever the browser sent."""
def test_pieces_apart_or_touching_pass(self):
Item.model_validate(loose([(0, 0), (20.5, 0), (0, 10.5), (20.5, 10.5)]))
Item.model_validate(loose([(0, 0), (20, 0), (0, 10)]))
def test_pieces_on_each_other_are_refused(self):
for layout in ([(0, 0), (0, 0)], [(0, 0), (10, 5)], [(0, 0), (19.9, 9.9)],
[(0, 0)] * 100):
with self.assertRaises(ValueError) as caught:
Item.model_validate(loose(layout))
self.assertIn('uma sobre a outra', str(caught.exception))
with self.assertRaises(ValueError):
sheet(gap=-5)
class ClosePiecesTests(unittest.TestCase):
"""The Site's count of pieces under 5 mm travels with the item to the
Kanban card (Marcus, 2026-11-26, #81)."""

View File

@@ -46,5 +46,44 @@ class SheetTrimTests(unittest.TestCase):
Item.model_validate(sheet_item(top=-1))
class CutStripsAreEmptyTests(unittest.TestCase):
"""The print file cuts the strips only when they hold no ink: on a measure
the file does not bear out, artwork would leave the print unseen."""
def source(self, ink_row=None, alpha=255, fmt='PNG'):
import os
import tempfile
from PIL import Image
from app.printpng import Source
folder = tempfile.mkdtemp()
image = Image.new('RGBA', (60, 1200), (0, 0, 0, 0))
image.paste((200, 30, 30, 255), (0, 300, 60, 900)) # the art, rows 300-899
if ink_row is not None:
image.putpixel((30, ink_row), (0, 0, 0, alpha))
path = os.path.join(folder, 'folha.' + fmt.lower())
image.save(path, fmt)
return Source(path, 'folha.' + fmt.lower())
# 1200 rows for 120 cm: 20 cm (200 rows) cut at each end.
spec = {'length_cm': 80, 'trim_top_cm': 20, 'trim_bottom_cm': 20}
def test_clear_strips_are_cut(self):
for fmt in ('PNG', 'TIFF'):
source = self.source(fmt=fmt)
source.trim(self.spec)
self.assertEqual(source.cut, (200, 200), fmt)
# A residue the Site does not count as ink does not hold the cut either.
self.source(ink_row=50, alpha=10, fmt=fmt).trim(self.spec)
def test_ink_in_a_cut_strip_goes_to_hand_preparation(self):
from app.printfile import Unsupported
for fmt in ('PNG', 'TIFF'):
for row, where in ((150, 'do começo'), (1100, 'do fim')):
with self.assertRaises(Unsupported) as caught:
self.source(ink_row=row, fmt=fmt).trim(self.spec)
self.assertIn(where, str(caught.exception), (fmt, row))
if __name__ == '__main__':
unittest.main()

View File

@@ -53,5 +53,29 @@ class RefusedDeliveryTest(unittest.TestCase):
self.assertEqual(self.tick_with(9, limit).call_count, 1)
class HeldTinyTest(unittest.TestCase):
"""Production without the real Tiny holds the sends and tells Sentry; the
simulator marked real orders delivered with made-up receipts."""
def test_production_without_the_real_tiny_holds(self):
self.assertIsInstance(worker.tiny_adapter('fake', 'production'), worker.HeldTiny)
self.assertIsInstance(worker.tiny_adapter(None, 'production'), worker.HeldTiny)
self.assertIsInstance(worker.tiny_adapter('fake', 'local'), worker.FakeTiny)
def test_a_held_send_stays_undelivered_and_is_reported(self):
job = {'id': 1, 'provider': 'tiny', 'event_key': 'o:paid:tiny', 'payload': {}, 'attempts': 0}
conn = mock.MagicMock()
conn.execute.return_value.fetchone.return_value = job
connect = mock.MagicMock()
connect.return_value.__enter__.return_value = conn
with mock.patch.object(worker, 'connect', connect), \
mock.patch.dict(worker.adapters, {'tiny': worker.HeldTiny()}), \
mock.patch.object(worker.logging, 'error') as error:
worker.tick()
updates = [call.args[0] for call in conn.execute.call_args_list[1:]]
self.assertTrue(updates and 'delivered_at=now()' not in updates[0] and 'last_error' in updates[0], updates)
self.assertEqual(conn.execute.call_args_list[1].args[1][0], worker.HELD)
self.assertEqual(error.call_count, 1)
if __name__ == '__main__':
unittest.main()

View File

@@ -58,6 +58,21 @@ def run():
assert quote_id in {q['id'] for q in page['quotes']}
print('PASS: a live payment attempt keeps an approved quote and its files')
# A card in review (Mercado Pago "em análise") tried 30 h ago is still
# live: it may be approved days later (payments.CARD_REVIEW_HOURS).
with db.connect() as c:
c.execute('''UPDATE dtf_local.payment_intents SET status='expired', created_at=now()-interval '31 hours'
WHERE quote_id=%s''', (quote_id,))
c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,status,
amount_cents,response,created_at) VALUES(%s,%s,'fake',%s,'card','pending',%s,'{}',now()-interval '30 hours')''',
(uuid4(), quote_id, 'unpaid-card-' + uuid4().hex, approved['total_cents']))
c.execute("UPDATE dtf_local.quotes SET approved_at=now()-interval '31 hours' WHERE id=%s", (quote_id,))
with db.connect() as c:
unpaid.expire(c, ORIGIN)
assert c.execute('SELECT expired_at FROM dtf_local.quotes WHERE id=%s',
(quote_id,)).fetchone()['expired_at'] is None
print('PASS: a card in review keeps its quote and files past the 24 h')
# The attempt is final now: the quote expires, its files are freed and the
# customer is told once.
with db.connect() as c:

View File

@@ -154,7 +154,8 @@ function montarQuoteFigures(lines){
});
const catalog=MONTAR.catalog?.avulsa;
if(!catalog)throw new Error('Preço de tabela indisponível agora.');
const billed=heights.map(metres=>Math.max(1,Math.ceil(metres*10)/10));
// Every 10 cm, 8 mm in the customer's favour (app/core/pricing.py billed_length).
const billed=heights.map(metres=>Math.max(1,Math.ceil(+((metres-0.008)*10).toFixed(6))/10));
const total=+billed.reduce((sum,metres)=>sum+metres,0).toFixed(2);
let unit=catalog.unit_cents,best=null;
for(const band of catalog.bands||[]){

View File

@@ -330,7 +330,7 @@ function nextBox(order){
const manual=(order.print_files||[]).some(r=>r.status==='manual');
note(finalDone(order)?'Abra o PNG gerado pelo Prumo e confirme a contração.':manual
?'O original exige preparo manual. Abra o pedido pai, envie o PNG completo e depois gere a prova de novo.'
:'O Prumo prepara até 15 cm por classe e aprova o PNG final automaticamente.');
:'O Prumo prepara até 30 cm por classe e aprova o PNG final automaticamente.');
if(manual&&may('produce'))more.push(button('Abrir pedido pai',()=>openPanel(order.proof_parent.id),'btn lg'));
if(finalDone(order)&&may('produce'))main.push(checkButton(order,'btn pri lg'));
if((order.print_files||[]).some(r=>r.status==='failed'||r.status==='manual'||r.timed_out)&&may('produce'))

View File

@@ -323,7 +323,10 @@ function machineForm(m){
left.push(remove);
}
const d=formDialog(m?'Editar máquina':'Nova máquina',{width:520,left,
fields:[field('Nome',name),group('Imprime',products),
// The hot folder is the machine's first name, for good (FlexiPRINT watches
// that path): renaming the machine does not move it.
fields:[field('Nome',name,m?'Pasta no FlexiPRINT: 3. Imprimindo/'+(m.folder||m.name)+'. Trocar o nome não muda a pasta.':undefined),
group('Imprime',products),
field('Limite de metros em aberto',unit(limit,'metros'),'Pedidos novos vão para a máquina do produto com menos metros em aberto, dentro do limite.'),
field('Vagas em Imprimindo',places,PLACES_NOTE),
checkbox('Ativa: recebe pedidos',active)],

View File

@@ -27,6 +27,8 @@ function outcomeText(outcome){
[/^refused: quote was never reviewed/,()=>'a cotação ainda não tinha sido revisada'],
[/^refused: quote uses an obsolete/,()=>'a cotação usa uma montagem antiga'],
[/^attention: payment (\w+) for order (\d+)/,m=>'pagamento '+(m[1]==='refunded'?'estornado':'cancelado')+' depois do pedido #'+m[2]],
// The customer paid the same cart twice (a PIX and a card): one is refunded.
[/^attention: second payment (\S+) for order (\d+)/,m=>'segundo pagamento ('+m[1]+') do pedido #'+m[2]+': o cliente pagou duas vezes, estorne um no Mercado Pago'],
];
for(const [pattern,text] of rules){const m=outcome.match(pattern);if(m)return text(m);}
return outcome;
@@ -566,6 +568,9 @@ async function fetchFile(url,options){
}
async function fetchInto(dir,file,watched=false){
const r=await fetchFile(file.url,{referrerPolicy:'no-referrer'});
// A link that ran out while the files before it were downloading: the next
// pass asks for a new one, as for a network that dropped.
if(r.status===403){const e=new Error('o link de '+file.name+' venceu antes do download.');e.unreachable=true;throw e;}
if(!r.ok||!r.body)throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').');
await writeWhole(dir,file.name,r,watched);
}
@@ -624,7 +629,14 @@ async function syncFolder(force=false){
FOLDER.busy=true;
try{
if(stages)await makeStageFolders();
const held=stages?[...new Set([...FOLDER.saved.values()].filter(r=>!r.review).map(r=>r.order).filter(Boolean))].slice(-1000):[];
// The server answers for up to 1000 orders a pass: the ones still in the
// flow first, then those in Finalizado. A file whose order was not asked
// this time stays as it is; only an order the server says is gone,
// cancelled or moved changes its files.
const records=[...FOLDER.saved.values()].filter(r=>!r.review&&r.order);
const held=stages?[...new Set([...records.filter(r=>r.folder!==STAGE_FOLDERS.fin),...records.filter(r=>r.folder===STAGE_FOLDERS.fin)]
.map(r=>r.order))].slice(0,1000):[];
const asked=new Set(held);
const {files,states,receipts=[],reviews=[]}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null});
// By file: an item longer than a part (10 m) is several parts (item 13), each its own file.
const wanted=new Map(files.map(f=>[f.upload_id,f]));
@@ -640,7 +652,7 @@ async function syncFolder(force=false){
...(folder===STAGE_FOLDERS.fin?{at:file.at||Date.now()}:{})});
FOLDER.last=new Date();await keepSaved();};
if(stages)for(const [uid,rec] of [...FOLDER.saved])await step(rec.name,async()=>{
if(!rec.order||!rec.folder)return;
if(!rec.order||!rec.folder||!asked.has(rec.order))return;
const state=states[rec.order], target=STAGE_FOLDERS[state];
const now=wanted.get(uid);
const replaced=(state==='rec'||state==='tra')&&(!now||now.order!==rec.order);

View File

@@ -12,13 +12,24 @@
$('cMetroLbl').textContent = it.extra ? 'Metro · com '+rs(it.extra)+' de arquivo manual' : 'Metro';
$('cMetro').textContent=rs(it.unit);
$('cMetragem').textContent=fmtM(it.cob)+' m';
const partes=ehFolha(it.modo) ? Math.ceil(it.metros/20) : 1;
$('cPartes').textContent = partes>1 ? ' Sai em '+partes+' partes de até 20 m.' : '';
// Partes de até 10 m (Marcus, 18/11/2026): o FlexiPRINT não abre mais que isso.
const partes=ehFolha(it.modo) ? Math.ceil(it.metros/10) : 1;
$('cPartes').textContent = partes>1 ? ' Sai em '+partes+' partes de até 10 m.' : '';
const sobraCm=Math.round((it.cob-it.metros)*100);
// A metragem cobrada explicada como vantagem (Marcus, 27/11/2026): a cada
// 10 cm, e até 8 mm a mais ficam por nossa conta.
const exata=n1(it.metros*100)+' cm';
const aMais=Math.round((it.metros-it.cob)*1000);
$('cObs').textContent =
it.cob===MINIMO_M && it.metros<MINIMO_M
? (ehFolha(it.modo) ? 'Pedido mínimo de 1 m.'
: 'Pedido mínimo de 1 m: ainda cabem '+sobraCm+' cm de artes sem custo.')
: it.cob<it.metros-1e-6
? 'A folha tem '+exata+': cobramos a cada 10 cm e '+
(aMais>1?'os '+aMais+' mm a mais ficam':aMais===1?'o 1 mm a mais fica':'o que passou fica')+' por nossa conta.'
: it.cob>it.metros+1e-6
? 'A folha tem '+exata+'. Cobramos a cada 10 cm, então fica '+fmtM(it.cob)+' m. '+
'Se passar até 8 mm de uma faixa, esse pedaço fica por nossa conta.'
: '';
$('cTotal').textContent=rs(it.total);
}

View File

@@ -206,11 +206,16 @@ function faltaLeitura(l){
return s<10 ? 'faltam '+Math.max(1,Math.ceil(s))+' s' : s<60 ? 'faltam cerca de '+Math.ceil(s/5)*5+' s' : 'faltam cerca de '+duracao(s);
}
const larguraFilme=()=>MODOS[modo].larg;
// cobrança proporcional: arredonda para cima em 10 cm · 2,75 m vira 2,80 m
const cobrar=m=>Math.max(MINIMO_M, Math.ceil(m*10)/10);
// Cobrança a cada 10 cm, com 8 mm a favor do cliente (Marcus, 27/11/2026):
// passou até 8 mm de um múltiplo de 10 cm, fica nele; passou mais, vai para o
// próximo. 2,75 m vira 2,80 m; 6,005 m fica 6,00 m. A mesma regra do servidor
// (app/core/pricing.py billed_length).
const TOLERANCIA_M=0.008;
const arredonda10=m=>Math.max(0.1, Math.ceil(+((m-TOLERANCIA_M)*10).toFixed(6))/10);
const cobrar=m=>Math.max(MINIMO_M, arredonda10(m));
// Com as artes em folhas separadas por traço (item 17), cada folha arredonda
// a 10 cm e o mínimo de 1 m vale para a soma: o cliente não escolheu separar.
const cobrarFolhas=fs=>Math.max(MINIMO_M, +fs.reduce((t,f)=>t+Math.ceil(+(f.alturaCm/100).toFixed(4)*10)/10,0).toFixed(1));
const cobrarFolhas=fs=>Math.max(MINIMO_M, +fs.reduce((t,f)=>t+arredonda10(+(f.alturaCm/100).toFixed(4)),0).toFixed(1));
const cobrarMontagem=()=>!ehFolha() && montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(metros);
const fmtM=m=>m.toFixed(2).replace('.',',');
const cls=n=>n>=85?'ok':n>=50?'av':'er';

View File

@@ -257,7 +257,7 @@ function montaFolhasDeTraco(grupos,W){
figura.append(legenda,desenho); painel.append(figura);
desenhaMontagem(desenho, lista, 0, W, uso, r=>{
if(area.montagemVersao!==versao) return; // a montagem mudou nesse meio-tempo
legenda.textContent='Folha '+(i+1)+' · '+NOMES_TRACO[i]+' · '+fmtM(Math.ceil(+(r.alturaCm/100).toFixed(4)*10)/10)+' m';
legenda.textContent='Folha '+(i+1)+' · '+NOMES_TRACO[i]+' · '+fmtM(arredonda10(+(r.alturaCm/100).toFixed(4)))+' m';
feitas[i]={nome:NOMES_TRACO[i], artes:lista, alturaCm:r.alturaCm, folgaCm:r.folgaCm ?? MARGEM_CM,
layout:r.placements ? {height_cm:+r.alturaCm.toFixed(4), placements:r.placements} : null};
if(feitas.filter(Boolean).length<grupos.length) return;

View File

@@ -620,7 +620,12 @@ function pintaFolha(){
'<span class="passo"><button type="button" data-passo="-1" data-i="'+i+'" aria-label="Menos uma cópia">−</button>'+
'<input type="number" id="repf'+i+'" min="1" max="200" data-repf="'+i+'" value="'+x.rep+'">'+
'<button type="button" data-passo="1" data-i="'+i+'" aria-label="Mais uma cópia">+</button></span></div>'+
'<div class="conta">'+(x.rep>1? x.rep+' × '+fmtM(x.m)+' m = ' : '')+'<b>'+fmtM(sub)+' m</b></div>' : '')+
// A conta inteira, como é cobrada: o comprimento exato do arquivo e os
// 8 mm entre as cópias (Marcus, 27/11/2026: "falta explicar melhor").
'<div class="conta">'+(x.rep>1
? x.rep+' × '+n1(x.m*100)+' cm + '+(x.rep-1)+(x.rep>2?' espaços':' espaço')+' de 8 mm = <b>'+
n1(sub*100+(x.rep-1)*MARGEM_FOLHA_CM)+' cm</b>'
: '<b>'+n1(x.m*100)+' cm</b>')+'</div>' : '')+
'</div>' : '';
return '<div class="rep" data-folha="'+i+'">'+
'<div class="repTopo"><div class="miniF">'+mini+'</div><div class="repInfo">'+