Compare commits

..

13 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
Cauê Faleiros
ba85168c09 fix: parts of 10 m are the code's default too, not only the stack's
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 7m58s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m21s
A stack without PRINT_PART_CM (the local one and CI) cut films in 15 m parts,
4,8 GB decoded, which FlexiPRINT refuses (Marcus, 2026-11-18). The comments
that still said 15 m now say a part.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:03:36 -03:00
Cauê Faleiros
b64947eb76 fix: a proof sheet counts its real length in the machine's metres, in metres, not 15 m
PROOF_SHEET_CM (15) was added to a total in metres, so every proof counted
15 m of film: one proof was enough for the 10 m cleaning alert, and Números
overstated production. A proof now counts the film it took, the finest
stroke's window and the colour samples with the clear film between them (up
to 30 cm, Marcus, 2026-11-26), read from its print file; 15 cm for a sheet
made before the samples. One function serves the machine log and Números.
The Kanban's proof rule says 30 cm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:03:36 -03:00
Cauê Faleiros
f35a347a28 fix: a reprint keeps an all-items choice, an undone pass to Revisão prints nothing again, and Prova OK tells Tiny (#105)
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 7m56s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m26s
- Every item ticked was saved as NULL, which also means "not chosen", so the
  pass to the queue replaced it with the suggestion and only the changed
  item went to the machine; the panel showed the suggestion again. The
  choice is now the whole list.
- Undoing a pass to Revisão (back to Imprimindo) started a new round with
  every file, so FlexiPRINT printed the order again. It now writes back only
  what Flexi had not taken, and the reprint choice of that pass returns. A
  pass undone this way no longer counts its film twice in the machine's
  metres (machine log and Números).
- An order entering the queue by Prova OK never sent Tiny's "Preparando
  envio". The stage's Tiny event is now one function, used by the move and
  by the Prova OK.

Integration test follows the real moves: suggestion, all items kept, pull
onto a machine, two undone passes to Revisão, metres counted once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:48:34 -03:00
Cauê Faleiros
194797c412 fix: an unavailable Tiny (5xx) retries the whole delivery instead of sending the order without its seller
The seller cannot be set after the order is made (order 151250), so a server
error while reading the contact now waits for the outbox's next try, as a
429 already did. A reading Tiny refuses for good still lets the order go,
and now reaches Sentry instead of a warning no one sees.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:48:34 -03:00
53 changed files with 850 additions and 193 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 part_url(self, key: str, upload_id: str, part: int, size: int) -> str: ...
def complete(self, key: str, upload_id: str, parts: list): ... def complete(self, key: str, upload_id: str, parts: list): ...
def size(self, key: str) -> int: ... 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 fetch(self, key: str, path: str): ...
def store(self, key: str, path: str, content_type: str): ... def store(self, key: str, path: str, content_type: str): ...
def health(self): ... def health(self): ...
@@ -299,12 +299,12 @@ class LocalS3Storage:
"""Upload a file the service generated itself, such as a print file.""" """Upload a file the service generated itself, such as a print file."""
self.patient.upload_file(path, self.bucket, key, ExtraArgs={'ContentType': content_type}) 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 from urllib.parse import quote
return self.public.generate_presigned_url('get_object', Params={ return self.public.generate_presigned_url('get_object', Params={
'Bucket': self.bucket, 'Key': key, 'Bucket': self.bucket, 'Key': key,
'ResponseContentDisposition': "attachment; filename*=UTF-8''" + quote(name, safe=''), '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): def view(self, key, content_type, expires=3600):
"""A link to show an object in the page, not download it: the Kanban's """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 from .common import FINAL_OK
router = APIRouter() 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): def named_files(rows):
"""Each file named after its order and item, so a folder of them stays """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) names.add(name)
files.append({'order': str(row['order_id']), 'state': row['state'], 'number': row['number'], 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']), '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 return files
@@ -163,7 +167,7 @@ def queue_hot(user=Depends(can('print'))):
watched = hotfolder.watched(c) watched = hotfolder.watched(c)
return {'folder': hotfolder.PRINTING_FOLDER, return {'folder': hotfolder.PRINTING_FOLDER,
'write': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name'], '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']} 'watch': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']}
for r in watched if r['state'] == 'written'], for r in watched if r['state'] == 'written'],
'withdraw': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']} '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()] 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'): 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(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,)) c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (uid,))
if not test: 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', 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: if not row:
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.') raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
hotfolder.stop(c, uid) 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): if payments.in_tiny(row):
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL", sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
(f'{uid}:paid:tiny',)).fetchone() (f'{uid}:paid:tiny',)).fetchone()
@@ -524,12 +536,20 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
# again from what changed since. # again from what changed since.
if printed_items is not None or (body.state == 'fin' and not back): if printed_items is not None or (body.state == 'fin' and not back):
c.execute('UPDATE dtf_local.orders SET print_items=NULL WHERE id=%s', (uid,)) c.execute('UPDATE dtf_local.orders SET print_items=NULL WHERE id=%s', (uid,))
# Back to Imprimindo from Revisão (a mistaken move undone): the items
# that pass printed are the choice again, and only what Flexi had not
# taken goes back to the folder, never the whole order.
if body.state == 'imp' and back:
undone = c.execute('''SELECT items FROM dtf_local.movements WHERE order_id=%s
AND from_state='imp' AND to_state='rev' AND NOT back ORDER BY id DESC LIMIT 1''', (uid,)).fetchone()
if undone and undone['items'] is not None:
c.execute('UPDATE dtf_local.orders SET print_items=%s WHERE id=%s', (undone['items'], uid))
# Pulled to Imprimindo, its files go to its machine's hot folder; out # Pulled to Imprimindo, its files go to its machine's hot folder; out
# of it, what Flexi did not take leaves (item 10). # of it, what Flexi did not take leaves (item 10).
if row['state'] == 'imp': if row['state'] == 'imp':
hotfolder.stop(c, uid) hotfolder.stop(c, uid)
if body.state == 'imp': if body.state == 'imp':
hotfolder.start(c, uid) (hotfolder.resume if back else hotfolder.start)(c, uid)
# A pickup reaching Finalizado has its receipt due (item 14), once. # A pickup reaching Finalizado has its receipt due (item 14), once.
due = body.state == 'fin' and not back and receipt.is_pickup(row['snapshot']) due = body.state == 'fin' and not back and receipt.is_pickup(row['snapshot'])
changed = c.execute('''UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), changed = c.execute('''UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(),
@@ -538,21 +558,8 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
WHERE id=%s RETURNING *''', (body.state, body.state, due, uid)).fetchone() WHERE id=%s RETURNING *''', (body.state, body.state, due, uid)).fetchone()
# Entering the queue (Arte conferida) is Tiny's "Preparando envio"; # Entering the queue (Arte conferida) is Tiny's "Preparando envio";
# Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23). # Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23).
events = {'tra':'production_started','cor':'correction_needed','fin':'ready'} if not back:
if body.state in events and not back and payments.in_tiny(row): payments.stage_event(c, row, body.state, body.reason, changed['version'])
# "Production started" and "ready" reach the customer once per order,
# even if a mistaken move is undone and made again. Each correction
# is a new request, so it keeps one message per movement.
once = body.state in ('tra','fin')
event = {'order_id':str(uid), 'number':row['number'], 'event':events[body.state], 'reason':body.reason,
'customer_path': f'/portal.html?order={uid}'}
# Tiny needs the order (customer, pickup or delivery) and, once the
# sale reached it, its id, to set the situação without a search.
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
(f'{uid}:paid:tiny',)).fetchone()
tiny = {**event, 'order': row['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')}
key = f'{uid}:{events[body.state]}:tiny' if once else f'{uid}:{changed["version"]}:tiny'
enqueue(c, key, 'tiny', tiny)
return changed return changed
class PrintItems(StrictModel): class PrintItems(StrictModel):
@@ -574,7 +581,9 @@ def choose_print_items(uid: UUID, body: PrintItems, user=Depends(can('produce'))
items = sorted(set(body.items)) items = sorted(set(body.items))
if any(i < 0 or i >= count for i in items): if any(i < 0 or i >= count for i in items):
raise HTTPException(422, 'Item do pedido inválido.') raise HTTPException(422, 'Item do pedido inválido.')
chosen = None if len(items) == count else items # Every item is kept as the whole list, not NULL: NULL is "not chosen
# yet", which the pass to the queue would replace with the suggestion.
chosen = items
c.execute('UPDATE dtf_local.orders SET print_items=%s, version=version+1, updated_at=now() WHERE id=%s', c.execute('UPDATE dtf_local.orders SET print_items=%s, version=version+1, updated_at=now() WHERE id=%s',
(chosen, uid)) (chosen, uid))
audit('order_print_items', order=row['number'], items=','.join(str(i + 1) for i in items), operator=user) audit('order_print_items', order=row['number'], items=','.join(str(i + 1) for i in items), operator=user)

View File

@@ -11,7 +11,7 @@ import httpx
from fastapi import APIRouter, Depends, HTTPException, Request from fastapi import APIRouter, Depends, HTTPException, Request
from psycopg.types.json import Jsonb 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 import db
from ..core.auth import audit, client_ip, owner, rate_limit from ..core.auth import audit, client_ip, owner, rate_limit
from ..core.models import PaymentIntent 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)) 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(): 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.') 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 # 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, # removed after a while. A payment under way keeps them a day longer,
# time enough for the provider's notice to become the order. # 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)): if live != len(set(uploads)):
raise HTTPException(410, 'Os arquivos deste pedido expiraram porque ele não foi pago a tempo. ' raise HTTPException(410, 'Os arquivos deste pedido expiraram porque ele não foi pago a tempo. '
'Monte o pedido de novo para pagar.') '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 # Never a second charge: an approved payment is waiting for its
# notification to become the order, and a card in review may still be. # 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 # 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.auth import owner
from ..core.models import QuoteRequest from ..core.models import QuoteRequest
from .. import quote_review 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 ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
from ..scanning import require_clean from ..scanning import require_clean
@@ -79,7 +79,7 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
dpis.append(dpi) dpis.append(dpi)
if dpis: if dpis:
draft_item['source_dpi'] = round(min(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: if issue:
raise HTTPException(422, issue) raise HTTPException(422, issue)
note = mismatch(files, draft['items'], rows) if reason is None else None 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'))): def create_machine(body: MachineIn, user=Depends(can('users'))):
mid = uuid4() mid = uuid4()
with db.connect() as c: with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone(): # A machine's hot folder is its first name, for good: no other machine
raise HTTPException(409, 'Já existe uma máquina com este nome.') # may be called that, or two would share one folder.
c.execute('''INSERT INTO dtf_local.machines(id,name,products,active,limit_metres,places) if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) OR lower(folder)=lower(%s)',
VALUES(%s,%s,%s,%s,%s,%s)''', (mid, body.name.strip(), sorted(set(body.products)), body.active, (body.name.strip(), body.name.strip())).fetchone():
body.limit_metres, body.places or machines.DEFAULT_PLACES)) 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) audit('machine_created', operator=user, machine=body.name)
return {'id': str(mid)} return {'id': str(mid)}
@@ -281,9 +284,9 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
@router.post('/api/operator/machines/{mid}') @router.post('/api/operator/machines/{mid}')
def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))): def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
with db.connect() as c: with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s', if c.execute('''SELECT 1 FROM dtf_local.machines WHERE (lower(name)=lower(%s) OR lower(folder)=lower(%s))
(body.name.strip(), mid)).fetchone(): AND id<>%s''', (body.name.strip(), body.name.strip(), mid)).fetchone():
raise HTTPException(409, 'Já existe uma máquina com este nome.') 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, 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''', places=COALESCE(%s,places) WHERE id=%s RETURNING id''',
(body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres, (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( 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", "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() (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} 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): if kept and len(kept) == len(body.files):
raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.') 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') raise ValueError('Finished sheets must retain their original orientation')
if placed != expected: if placed != expected:
raise ValueError('Production layout does not cover every source copy') 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: if self.quality_status == 'warning' and not self.quality_acknowledged:
raise ValueError('Resolution warning must be acknowledged') raise ValueError('Resolution warning must be acknowledged')
return self return self

View File

@@ -8,6 +8,19 @@ import os
import re import re
from decimal import Decimal, ROUND_CEILING 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} 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 # 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') raise ValueError('Invalid product or length')
if isinstance(grade, bool) or not isinstance(grade, int) or not 0 <= grade <= 100: 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') 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: if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
raise ValueError('Invalid extra charge') raise ValueError('Invalid extra charge')
unit = (PRICES[mode] if unit_cents is None else unit_cents) + extra_cents 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 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): def mismatch(files, items, rows):
"""Why a cart's grades cannot be approved at checkout, or None.""" """Why a cart's grades cannot be approved at checkout, or None."""
for item in items: for item in items:

View File

@@ -4,8 +4,8 @@ FlexiPRINT watches 3. Imprimindo/<máquina>/<C1|C2|C3|PREMIUM>/ and takes a
file out of it when it rips. When the operator pulls a card to Imprimindo, its file out of it when it rips. When the operator pulls a card to Imprimindo, its
files go, as a copy, into its machine's folder for the item's contraction files go, as a copy, into its machine's folder for the item's contraction
class; a premium item always goes to PREMIUM, whichever class it carries; class; a premium item always goes to PREMIUM, whichever class it carries;
the order's own file stays in its stage folder. A film over 15 m is several the order's own file stays in its stage folder. A film longer than a part
parts (item 13): all on the same machine, in order. A machine's folder holds (10 m) is several parts (item 13): all on the same machine, in order. A machine's folder holds
as many files at once as it has places in Imprimindo (machines.places, three as many files at once as it has places in Imprimindo (machines.places, three
since 2026-11-17); the next is written when Flexi takes one. since 2026-11-17); the next is written when Flexi takes one.
@@ -15,7 +15,8 @@ the same file and Flexi never prints it twice. A claim that did not finish
goes back to the queue. A written part that is gone from its folder was goes back to the queue. A written part that is gone from its folder was
taken by Flexi, and is never written again. A card that leaves Imprimindo taken by Flexi, and is never written again. A card that leaves Imprimindo
(Revisão, Correção, a step back, a cancellation) withdraws what Flexi has not (Revisão, Correção, a step back, a cancellation) withdraws what Flexi has not
taken yet, and its computer deletes it. taken yet, and its computer deletes it. A step back from Revisão to
Imprimindo writes again only what Flexi had not taken (resume()).
Each part's life is one row of dtf_local.hot_parts: Each part's life is one row of dtf_local.hot_parts:
queued -> claimed -> written -> consumed, or withdraw -> gone. queued -> claimed -> written -> consumed, or withdraw -> gone.
@@ -70,6 +71,19 @@ def start(c, order_id):
VALUES(%s,%s,%s,%s,%s,%s)''', (order_id, round_, seq, row['item_index'], row['upload_id'], row['name'])) VALUES(%s,%s,%s,%s,%s,%s)''', (order_id, round_, seq, row['item_index'], row['upload_id'], row['name']))
def resume(c, order_id):
"""A step back from Revisão to Imprimindo, undoing a move made by
mistake: the parts of the last round Flexi had not taken go back to the
folder, in their order; what it took was printed and is never written
again (start() would send the whole order to the machine once more)."""
last = c.execute('SELECT max(round) AS r FROM dtf_local.hot_parts WHERE order_id=%s', (order_id,)).fetchone()['r']
if last is None:
return
c.execute('''INSERT INTO dtf_local.hot_parts(order_id,round,seq,item_index,upload_id,name)
SELECT order_id, round + 1, row_number() OVER (ORDER BY seq), item_index, upload_id, name
FROM dtf_local.hot_parts WHERE order_id=%s AND round=%s AND state<>'consumed' ''', (order_id, last))
def printed(c, order_ids): def printed(c, order_ids):
"""The files each order's machine has already taken, {order id: {upload """The files each order's machine has already taken, {order id: {upload
ids}}: an order in it was printed before.""" ids}}: an order in it was printed before."""
@@ -105,12 +119,12 @@ def claim(c, user):
they entered it, until the machine has its places' worth in its folder.""" 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 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,)) 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 (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 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 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 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() due, busy, blocked = [], {}, set()
for row in rows: for row in rows:
machine = row['machine_id'] machine = row['machine_id']
@@ -125,7 +139,9 @@ def claim(c, user):
if busy.get(machine, 0) >= row['places'] or not cls: if busy.get(machine, 0) >= row['places'] or not cls:
blocked.add(order) blocked.add(order)
continue 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 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'])) WHERE id=%s''', (user, folder, row['id']))
busy[machine] = busy.get(machine, 0) + 1 busy[machine] = busy.get(machine, 0) + 1

View File

@@ -28,7 +28,8 @@ entry. Fewer than two entries, no estimate.
"Printed" is what left Imprimindo for Revisão on the machine (orders.machine_id, "Printed" is what left Imprimindo for Revisão on the machine (orders.machine_id,
the movement imp -> rev not back): the film metres of the items the movement imp -> rev not back): the film metres of the items
(COALESCE(metres, billed_metres)), and PROOF_SHEET_CM per item for a proof card. (COALESCE(metres, billed_metres)), and for a proof card the length of each
proof sheet (film_metres).
""" """
from datetime import datetime, timezone from datetime import datetime, timezone
from decimal import Decimal from decimal import Decimal
@@ -58,30 +59,56 @@ def one_decimal(value):
return f'{Decimal(str(value)):.1f}'.replace('.', ',') return f'{Decimal(str(value)):.1f}'.replace('.', ',')
# A pass to Revisão undone at once (a mistaken move, back to Imprimindo):
# the pass after the undo counts the film, so this one must not, or the
# machine's metres count it twice. `m` is the pass in dtf_local.movements.
NOT_UNDONE = """NOT EXISTS (SELECT 1 FROM dtf_local.movements u WHERE u.order_id=m.order_id AND u.back
AND u.from_state='rev' AND u.to_state='imp'
AND u.id=(SELECT min(n.id) FROM dtf_local.movements n WHERE n.order_id=m.order_id AND n.id>m.id))"""
# Each proof sheet's stretches of film, {item index: [[top, bottom], ...]},
# from its print file (app/printpng.py); `o` is the order.
PROOF_WINDOWS = """(SELECT jsonb_object_agg(p.item_index::text, p.detail->'proof_windows')
FROM dtf_local.print_files p WHERE p.order_id=o.id AND p.detail ? 'proof_windows') AS windows"""
def film_metres(snapshot, items=None, windows=None):
"""The film one pass to Revisão printed, in metres, as Decimal: each
item's metres, on a reprint only the `items` that went again (#105). A
proof card's item is its sheet: the finest stroke's window and the colour
samples with the clear film between them, up to 30 cm (Marcus,
2026-11-26), from `windows` ({item index: [[top, bottom], ...]} in cm);
PROOF_SHEET_CM for a sheet made before the samples."""
from .printpng import PROOF_GAP_CM
from .proof import PROOF_SHEET_CM
snapshot = snapshot or {}
proof = bool(snapshot.get('proof_of'))
total = Decimal(0)
for index, item in enumerate(snapshot.get('items') or []):
if items is not None and index not in items:
continue
if proof:
stretches = (windows or {}).get(str(index)) or []
cm = (sum((Decimal(str(b)) - Decimal(str(a)) for a, b in stretches), Decimal(0))
+ PROOF_GAP_CM * (len(stretches) - 1)) if stretches else PROOF_SHEET_CM
total += cm / 100
else:
value = item.get('metres')
if value is None:
value = item.get('billed_metres')
total += Decimal(str(value or 0))
return total
def printed_since(c, machine_id, since): def printed_since(c, machine_id, since):
"""Film metres the machine printed after `since` (None: ever), as Decimal.""" """Film metres the machine printed after `since` (None: ever), as Decimal."""
from .proof import PROOF_SHEET_CM rows = c.execute(f'''SELECT o.snapshot, m.items, {PROOF_WINDOWS} FROM dtf_local.movements m
rows = c.execute('''SELECT o.snapshot, m.items FROM dtf_local.movements m
JOIN dtf_local.orders o ON o.id=m.order_id JOIN dtf_local.orders o ON o.id=m.order_id
WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back AND {NOT_UNDONE}
AND (%s::timestamptz IS NULL OR m.created_at > %s::timestamptz)''', AND (%s::timestamptz IS NULL OR m.created_at > %s::timestamptz)''',
(machine_id, since, since)).fetchall() (machine_id, since, since)).fetchall()
total = Decimal(0) return sum((film_metres(row['snapshot'], row.get('items'), row.get('windows')) for row in rows), Decimal(0))
for row in rows:
snapshot = row['snapshot'] or {}
proof = bool(snapshot.get('proof_of'))
for index, item in enumerate(snapshot.get('items') or []):
# A reprint counts only the items that went again (#105).
if row.get('items') is not None and index not in row['items']:
continue
if proof:
total += PROOF_SHEET_CM
else:
value = item.get('metres')
if value is None:
value = item.get('billed_metres')
total += Decimal(str(value or 0))
return total
def _last_entry(c, machine_id, kind, item): def _last_entry(c, machine_id, kind, item):

View File

@@ -5,7 +5,7 @@ what the board already knows it printed, per machine and calendar month
(America/Sao_Paulo): (America/Sao_Paulo):
Produção printed metres (machine_log rule: imp -> rev, film metres, Produção printed metres (machine_log rule: imp -> rev, film metres,
PROOF_SHEET_CM per proof item); hours running = the union of the a proof sheet its real length); hours running = the union of the
time its orders spent in Imprimindo, clipped to the month (two time its orders spent in Imprimindo, clipped to the month (two
orders printing together count once); metres per hour = printed orders printing together count once); metres per hour = printed
/ hours running; hours stopped = the "stop" events' minutes, in / hours running; hours stopped = the "stop" events' minutes, in
@@ -33,7 +33,7 @@ from datetime import datetime, time
from decimal import Decimal, ROUND_HALF_UP from decimal import Decimal, ROUND_HALF_UP
from zoneinfo import ZoneInfo from zoneinfo import ZoneInfo
from .machine_log import SUPPLIES from .machine_log import NOT_UNDONE, PROOF_WINDOWS, SUPPLIES, film_metres
SAO_PAULO = ZoneInfo('America/Sao_Paulo') SAO_PAULO = ZoneInfo('America/Sao_Paulo')
# The five inks Números lists, in the order the sheet knows them. # The five inks Números lists, in the order the sheet knows them.
@@ -119,30 +119,15 @@ def ratios(printed, hours_running=None, supplies_cents=0, parts_cents=0, rolls=N
def _printed_orders(c, machine_id, start, end): def _printed_orders(c, machine_id, start, end):
"""The orders that left Imprimindo for Revisão on the machine in the """The orders that left Imprimindo for Revisão on the machine in the
period, with what is needed to count film and what they sold.""" period, with what is needed to count film and what they sold."""
return c.execute('''SELECT o.id, o.snapshot, o.parent_id, o.cancelled_at, o.payment, m.items return c.execute(f'''SELECT o.id, o.snapshot, o.parent_id, o.cancelled_at, o.payment, m.items, {PROOF_WINDOWS}
FROM dtf_local.movements m JOIN dtf_local.orders o ON o.id=m.order_id FROM dtf_local.movements m JOIN dtf_local.orders o ON o.id=m.order_id
WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back AND {NOT_UNDONE}
AND m.created_at>=%s AND m.created_at<%s''', (machine_id, start, end)).fetchall() AND m.created_at>=%s AND m.created_at<%s''', (machine_id, start, end)).fetchall()
def _film(snapshot, items=None): def _film(row):
"""The film printed for one order (machine_log's rule), as Decimal; on a """The film one printed order took (machine_log's rule), as Decimal."""
reprint only the `items` that went again.""" return film_metres(row['snapshot'], row.get('items'), row.get('windows'))
from .proof import PROOF_SHEET_CM
snapshot = snapshot or {}
proof = bool(snapshot.get('proof_of'))
total = Decimal(0)
for index, item in enumerate(snapshot.get('items') or []):
if items is not None and index not in items:
continue
if proof:
total += PROOF_SHEET_CM
else:
value = item.get('metres')
if value is None:
value = item.get('billed_metres')
total += Decimal(str(value or 0))
return total
def _sold(row): def _sold(row):
@@ -157,7 +142,7 @@ def _sold(row):
def printed_between(c, machine_id, start, end): def printed_between(c, machine_id, start, end):
"""Film metres the machine printed in [start, end), as Decimal.""" """Film metres the machine printed in [start, end), as Decimal."""
return sum((_film(row['snapshot'], row.get('items')) for row in _printed_orders(c, machine_id, start, end)), return sum((_film(row) for row in _printed_orders(c, machine_id, start, end)),
Decimal(0)) Decimal(0))
@@ -189,7 +174,7 @@ def machine_month(c, machine, start, end):
'contribution_cents'}. `machine` is its row from dtf_local.machines.""" 'contribution_cents'}. `machine` is its row from dtf_local.machines."""
mid = machine['id'] mid = machine['id']
rows = _printed_orders(c, mid, start, end) rows = _printed_orders(c, mid, start, end)
printed = sum((_film(row['snapshot'], row.get('items')) for row in rows), Decimal(0)) printed = sum((_film(row) for row in rows), Decimal(0))
sold = sum((_sold(row) for row in rows), 0) sold = sum((_sold(row) for row in rows), 0)
ids = [row['id'] for row in rows] ids = [row['id'] for row in rows]
spans = c.execute('''WITH events AS ( spans = c.execute('''WITH events AS (
@@ -278,9 +263,9 @@ def report(c, month=None):
'''SELECT DISTINCT machine_id FROM dtf_local.machine_entries '''SELECT DISTINCT machine_id FROM dtf_local.machine_entries
WHERE created_at>=%s AND created_at<%s''', (start, end)).fetchall()} WHERE created_at>=%s AND created_at<%s''', (start, end)).fetchall()}
printed = {str(row['machine_id']) for row in c.execute( printed = {str(row['machine_id']) for row in c.execute(
'''SELECT DISTINCT o.machine_id FROM dtf_local.movements m f'''SELECT DISTINCT o.machine_id FROM dtf_local.movements m
JOIN dtf_local.orders o ON o.id=m.order_id JOIN dtf_local.orders o ON o.id=m.order_id
WHERE m.from_state='imp' AND m.to_state='rev' AND NOT m.back WHERE m.from_state='imp' AND m.to_state='rev' AND NOT m.back AND {NOT_UNDONE}
AND m.created_at>=%s AND m.created_at<%s''', (start, end)).fetchall()} AND m.created_at>=%s AND m.created_at<%s''', (start, end)).fetchall()}
result = [] result = []
for machine in machines: for machine in machines:

View File

@@ -39,7 +39,8 @@ def loads(c):
def rows(c, with_operators=False): def rows(c, with_operators=False):
"""Every machine with its load, for the Kanban.""" """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() ORDER BY created_at, name''').fetchall()
load = loads(c) load = loads(c)
operators = {} operators = {}
@@ -55,7 +56,7 @@ def rows(c, with_operators=False):
for m in machines: for m in machines:
key = str(m['id']) key = str(m['id'])
used = load.get(key, {'metres': Decimal(0), 'orders': 0, 'states': {}}) 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, 'limit_metres': float(m['limit_metres']) if m['limit_metres'] is not None else None,
'places': m['places'], 'places': m['places'],
'open_metres': float(used['metres']), 'open_orders': used['orders'], 'states': used['states'], '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 from .scanning import require_clean
QUOTE_VALID_HOURS = 24 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): class PaymentRefused(Exception):
"""The payment cannot become an order, with a reason worth recording.""" """The payment cannot become an order, with a reason worth recording."""
def approved_quote(c, quote_id, owner=None): def approved_quote(c, quote_id, owner=None, payment_id=None):
"""The reviewed quote behind a payment, or a refusal explaining why not.""" """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 '') 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() row = c.execute(sql + ' FOR UPDATE', (quote_id, owner) if owner else (quote_id,)).fetchone()
if not row: if not row:
@@ -42,8 +48,13 @@ def approved_quote(c, quote_id, owner=None):
raise PaymentRefused('quote was discarded') raise PaymentRefused('quote was discarded')
if any(item.get('production', {}).get('version') not in PRODUCTION_VERSIONS for item in row['approved']['items']): 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') 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): deadline = row['approved_at'] + timedelta(hours=QUOTE_VALID_HOURS)
raise PaymentRefused('quote expired before payment') 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 return row
@@ -77,6 +88,34 @@ def in_tiny(order):
return not is_test(order) and not order.get('parent_id') return not is_test(order) and not order.get('parent_id')
# What a stage tells Tiny: entering the queue (Arte conferida) is its
# "Preparando envio", Finalizado its "Pronto para envio" (Dropstar's flow,
# 2026-10-23); a correction has no situação and is only recorded.
STAGE_EVENTS = {'tra': 'production_started', 'cor': 'correction_needed', 'fin': 'ready'}
def stage_event(c, order, state, reason, version):
"""Queue Tiny's event for an order that entered `state` (not by a step
back), whoever moved it: a card dragged, or the Prova OK that puts the
order in the queue (app/proof.py). `order` is its row before the move,
`version` its version after."""
if state not in STAGE_EVENTS or not in_tiny(order):
return
# "Production started" and "ready" reach the customer once per order,
# even if a mistaken move is undone and made again. Each correction is a
# new request, so it keeps one message per movement.
once = state in ('tra', 'fin')
event = {'order_id': str(order['id']), 'number': order['number'], 'event': STAGE_EVENTS[state],
'reason': reason, 'customer_path': f"/portal.html?order={order['id']}"}
# Tiny needs the order (customer, pickup or delivery) and, once the sale
# reached it, its id, to set the situação without a search.
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
(f"{order['id']}:paid:tiny",)).fetchone()
tiny = {**event, 'order': order['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')}
key = f"{order['id']}:{STAGE_EVENTS[state]}:tiny" if once else f"{order['id']}:{version}:tiny"
enqueue(c, key, 'tiny', tiny)
# How long a file is kept while nothing has been paid for it. A cart's files # How long a file is kept while nothing has been paid for it. A cart's files
# are uploaded before payment, so the price and the security check are done on # are uploaded before payment, so the price and the security check are done on
# the file itself; a cart that is never paid must not keep them for 30 days. # the file itself; a cart that is never paid must not keep them for 30 days.
@@ -212,7 +251,7 @@ def apply(c, event):
return 'refused: reference is not a quote id' return 'refused: reference is not a quote id'
try: try:
quote = approved_quote(c, quote_id) quote = approved_quote(c, quote_id, payment_id=provider_id)
except PaymentRefused as refusal: except PaymentRefused as refusal:
return f'refused: {refusal}' return f'refused: {refusal}'
@@ -227,7 +266,16 @@ def apply(c, event):
return f'refused: paid {event.amount_cents} but quote total is {expected}' 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') 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): def reconcile(connect, provider, quote_id=None, limit=20):
@@ -245,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') 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.created_at > now() - make_interval(hours => %s)''' +
(' AND i.quote_id=%s' if quote_id else '') + ' ORDER BY i.created_at DESC LIMIT %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 = [] outcomes = []
for row in rows: for row in rows:
# Asked outside any transaction: no lock is held while the provider answers. # 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 PIL import Image, ImageOps
from .core.models import PRODUCTION_VERSIONS from .core.models import PRODUCTION_VERSIONS
from .core.pricing import STEP_GRACE_M
PT_PER_CM = 72 / 2.54 PT_PER_CM = 72 / 2.54
# Acrobat's page limit, 200 inches (5,08 m). A longer sheet is written at its # 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'] production = item['production']
height = Decimal(str(production['height_cm'])) height = Decimal(str(production['height_cm']))
billed = Decimal(str(item['billed_metres'])) * 100 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') raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados')
lowest = None lowest = None
for placement in production['placements']: for placement in production['placements']:

View File

@@ -7,7 +7,7 @@ plus a margin; CLAIM_TIMEOUT for a claim made before deadlines existed) is
assumed to belong to a worker that died and is taken again. assumed to belong to a worker that died and is taken again.
The result is a 300 DPI PNG (item 13, app/printpng.py), or its parts for a The result is a 300 DPI PNG (item 13, app/printpng.py), or its parts for a
film over 15 m: ordinary upload rows owned by an identity derived from the film longer than a part (10 m): ordinary upload rows owned by an identity derived from the
order, already marked clean, since their only inputs are artwork that passed order, already marked clean, since their only inputs are artwork that passed
the malware scan and the bytes are written here. dtf_local.print_parts lists the malware scan and the bytes are written here. dtf_local.print_parts lists
them in order. The operator still decides whether they become the final them in order. The operator still decides whether they become the final

View File

@@ -19,8 +19,9 @@ holds a whole sheet: the film is composed and written in bands of rows.
- Loose artwork is small: each file is decoded, turned and scaled to its place - Loose artwork is small: each file is decoded, turned and scaled to its place
once, and copied into every band it crosses. once, and copied into every band it crosses.
A layout longer than 15 m leaves as parts of up to 15 m (Dropstar, A layout longer than a part leaves as parts of up to PART_CM, 10 m since
2026-10-30), DTF-7-item-1-p3.png, each with its footer saying which part it Marcus's 18/11 answer (Flexi opens up to 4 GB per image; Dropstar,
2026-10-30, was 15 m), DTF-7-item-1-p3.png, each with its footer saying which part it
is. Loose artwork is cut where no piece crosses; a finished sheet between is. Loose artwork is cut where no piece crosses; a finished sheet between
copies, or else in a clear band of its own pixels, and through the artwork copies, or else in a clear band of its own pixels, and through the artwork
only when it has none (#136). only when it has none (#136).
@@ -41,11 +42,14 @@ from .printtiles import Pyramid
DPI = 300 DPI = 300
PX_PER_CM = DPI / 2.54 PX_PER_CM = DPI / 2.54
# Parts of up to 15 m, 6732 x 177165 px (Dropstar, 2026-10-30). # Parts of up to 10 m (Marcus, 2026-11-18): a 15 m part, 6732 x 177165 px, is
PART_CM = Decimal(os.environ.get('PRINT_PART_CM', '1500')) # 4,8 GB decoded and FlexiPRINT refuses it. PRINT_PART_CM overrides it.
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. # A cut through artwork only when no gap between pieces is this close to the limit.
CUT_SEARCH_CM = Decimal('200') CUT_SEARCH_CM = Decimal('200')
BAND_ROWS = 512 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. # Above this a source is read band by band instead of decoded whole.
STREAM_ABOVE_PIXELS = 40_000_000 STREAM_ABOVE_PIXELS = 40_000_000
FOOTER_TEXT_CM = 1.1 FOOTER_TEXT_CM = 1.1
@@ -266,9 +270,44 @@ class Source:
top, bottom = round(height * top_cm / full_cm), round(height * bottom_cm / full_cm) top, bottom = round(height * top_cm / full_cm), round(height * bottom_cm / full_cm)
if top + bottom >= height: if top + bottom >= height:
raise Unsupported(f'"{self.name}": o corte das faixas vazias tiraria o arquivo inteiro') raise Unsupported(f'"{self.name}": o corte das faixas vazias tiraria o arquivo inteiro')
self._require_clear(top, bottom)
self.cut = (top, bottom) self.cut = (top, bottom)
self.size = (width, height - 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): def decoded(self, width, height):
"""The whole file at (width, height) px, upright, RGBA.""" """The whole file at (width, height) px, upright, RGBA."""
if self.pdf: if self.pdf:

View File

@@ -1,8 +1,9 @@
"""The print proof (Dropstar, 2026-10-21). """The print proof (Dropstar, 2026-10-21).
An order above 10 m prints a proof before the rest, checked by the print room An order above 10 m prints a proof before the rest, checked by the print room
without stopping the order. Dropstar's current rule: up to 15 cm, from without stopping the order. Dropstar's current rule: 15 cm from the part
the part with the thinnest lines, a piece of each different artwork, at most with the thinnest lines plus samples of the file's main colours, up to 30 cm
in all (Marcus, 2026-11-26), a piece of each different artwork, at most
three proofs per order, never billed. On an order above 10 m the customer three proofs per order, never billed. On an order above 10 m the customer
may also ask for a proof at checkout (below 10 m there is none, Dropstar may also ask for a proof at checkout (below 10 m there is none, Dropstar
2026-10-28): that order waits for them, marked "Aguardando contato", until 2026-10-28): that order waits for them, marked "Aguardando contato", until
@@ -37,12 +38,14 @@ def needs_proof(snapshot):
# #
# An order with a proof becomes a parent and a child. The child, the card # An order with a proof becomes a parent and a child. The child, the card
# "Prova", is an order of its own (orders.parent_id) with a pre-built proof # "Prova", is an order of its own (orders.parent_id) with a pre-built proof
# sheet of up to 15 cm per contraction class, and follows the normal flow up # sheet of up to 30 cm per contraction class, and follows the normal flow up
# to Revisão. The parent waits outside the queue, "Aguardando prova". On the # to Revisão. The parent waits outside the queue, "Aguardando prova". On the
# child, the Vendedor (Gestão and the Administrador too) marks Prova OK, and # child, the Vendedor (Gestão and the Administrador too) marks Prova OK, and
# the parent enters the queue; or Prova reprovada, with its reason, and the # the parent enters the queue; or Prova reprovada, with its reason, and the
# parent goes back to Arte recebida and the child closes. The child is no # parent goes back to Arte recebida and the child closes. The child is no
# sale: it is not in Tiny, Números, the customer's account or their e-mails. # sale: it is not in Tiny, Números, the customer's account or their e-mails.
# The finest stroke's window; with the colour samples the sheet reaches
# app/printpng.py PROOF_MAX_CM.
PROOF_SHEET_CM = Decimal('15') PROOF_SHEET_CM = Decimal('15')
# Three proofs at most per order, one per item (Dropstar, 2026-10-23). # Three proofs at most per order, one per item (Dropstar, 2026-10-23).
MAX_PROOFS = 3 MAX_PROOFS = 3
@@ -149,8 +152,12 @@ def approve_parent(c, parent, operator):
WHERE f.order_id=%s AND f.item_index=%s AND {FINAL_OK} {treatment_clause} LIMIT 1''', WHERE f.order_id=%s AND f.item_index=%s AND {FINAL_OK} {treatment_clause} LIMIT 1''',
(parent['id'], i)).fetchone() for i in range(len(parent['snapshot']['items']))) (parent['id'], i)).fetchone() for i in range(len(parent['snapshot']['items'])))
if ready: if ready:
c.execute('''UPDATE dtf_local.orders SET state='tra', version=version+1, updated_at=now() version = c.execute('''UPDATE dtf_local.orders SET state='tra', version=version+1, updated_at=now()
WHERE id=%s''', (parent['id'],)) WHERE id=%s RETURNING version''', (parent['id'],)).fetchone()['version']
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
VALUES(%s,'rec','tra',%s,'Prova OK')''', (parent['id'], operator)) VALUES(%s,'rec','tra',%s,'Prova OK')''', (parent['id'], operator))
# Entering the queue this way is Tiny's "Preparando envio" too, as a
# card moved by hand: orders with a proof skipped it.
from .payments import stage_event
stage_event(c, parent, 'tra', 'Prova OK', version)
return ready return ready

View File

@@ -195,6 +195,11 @@ class TinyRateLimit(TinyError):
transient = True transient = True
class TinyUnavailable(TinyError):
"""Tiny answered with a server error (5xx): down for a moment, so what
depends on the answer waits for the outbox's next try."""
class TinyNotConnected(TinyError): class TinyNotConnected(TinyError):
"""No authorised connection yet: an operator must click "Conectar Tiny".""" """No authorised connection yet: an operator must click "Conectar Tiny"."""
@@ -822,6 +827,8 @@ class TinyOrders:
response = self.http.request(method, path, headers=headers, **kwargs) response = self.http.request(method, path, headers=headers, **kwargs)
if response.status_code == 429: if response.status_code == 429:
raise TinyRateLimit('Tiny rate limit reached; the outbox will retry') raise TinyRateLimit('Tiny rate limit reached; the outbox will retry')
if response.status_code >= 500:
raise TinyUnavailable(f'{method} {path}: {response.status_code} {response.text[:300]}')
if response.status_code >= 400: if response.status_code >= 400:
raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}') raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}')
return response.json() if response.content else {} return response.json() if response.content else {}
@@ -870,14 +877,17 @@ class TinyOrders:
def contact_seller(self, contact_id): def contact_seller(self, contact_id):
"""The seller (vendedor) in a contact's registration, or None. A """The seller (vendedor) in a contact's registration, or None. A
failed reading leaves the order without one: it must still go.""" reading Tiny refuses leaves the order without one: it must still go.
The seller cannot be set after the order is made, so a busy or
unavailable Tiny (429, 5xx, no answer) tries the whole delivery again."""
try: try:
seller = (self.request('GET', f'/contatos/{contact_id}').get('vendedor') or {}).get('id') seller = (self.request('GET', f'/contatos/{contact_id}').get('vendedor') or {}).get('id')
except TinyRateLimit: except (TinyRateLimit, TinyUnavailable):
# Busy for a moment: the whole delivery is tried again, the seller with it.
raise raise
except TinyError as exc: except TinyError as exc:
logging.warning('Tiny: could not read the seller of contact %s: %s', contact_id, exc) # The order goes without its seller, for good: Sentry hears of it.
logging.error('Tiny: could not read the seller of contact %s; the order goes without one: %s',
contact_id, exc)
return None return None
return int(seller) if str(seller or '').isdigit() and int(seller) > 0 else None return int(seller) if str(seller or '').isdigit() and int(seller) > 0 else None

View File

@@ -13,7 +13,7 @@ abandonment rate.
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from . import mail, payments 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 # An intent in one of these no longer waits for money: approved (it became an
# order), rejected, cancelled, expired or refunded (app/payments.py). # 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 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) WHERE i2.quote_id=q.id ORDER BY i2.created_at DESC LIMIT 1)
AND i.status <> ALL(%s) 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 AND (i.response->>'expires_at' IS NULL
OR (i.response->>'expires_at')::timestamptz > now())) OR (i.response->>'expires_at')::timestamptz > now()))
ORDER BY q.approved_at LIMIT 50 FOR UPDATE OF q SKIP LOCKED''', 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: for row in rows:
c.execute('UPDATE dtf_local.quotes SET expired_at=now() WHERE id=%s', (row['id'],)) 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 # 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() load_secret_files()
require_runtime() require_runtime()
adapters = {'tiny': FakeTiny()} # Production without the real Tiny (TINY_ADAPTER missing from the stack):
# Not yet confirmed against the client's account; see app/tiny.py. # the sends wait and Sentry is told, instead of the simulator marking real
if os.environ.get('TINY_ADAPTER') == 'tiny': # orders delivered with made-up receipts that had to be queued again by hand.
from .tiny import TinyOrders HELD = 'Tiny desligado em produção (TINY_ADAPTER não é tiny): o envio espera'
from .cnpj import company
adapters['tiny'] = TinyOrders(names=company)
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_tick = 0.0
last_cleanup = 0.0 last_cleanup = 0.0
last_reconcile = 0.0 last_reconcile = 0.0
@@ -199,6 +224,14 @@ class Health(BaseHTTPRequestHandler):
if __name__ == '__main__': if __name__ == '__main__':
observability.init('worker') 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 = threading.Thread(target=scan_loop,args=(storage,),daemon=True)
scan_thread.start() scan_thread.start()
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True) render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)

View File

@@ -41,9 +41,9 @@ SOURCE_BLOCKERS = {
'app/runtime.py': ( 'app/runtime.py': (
'payment = FakePayment()', 'payment = FakePayment()',
), ),
'app/worker.py': ( # app/worker.py's "adapters = {'tiny': FakeTiny()}" left on 2026-11-27: in
"adapters = {'tiny': FakeTiny()}", # 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): def test_fake_checkout_is_explicitly_blocked(self):
errors = source_errors() errors = source_errors()
self.assertTrue(any('app/runtime.py remains local-only' in error for error in 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): def test_secret_reuse_and_incoherent_limits_are_rejected(self):
values = valid_config() values = valid_config()

View File

@@ -33,15 +33,16 @@ def run():
manager = manager.operator_client manager = manager.operator_client
coupon_id = None coupon_id = None
quote_id = None quote_id = None
early_id = None
order_id = None order_id = None
upload_id = None upload_id = None
try: try:
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-COUPON-{tag}.png') 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} 'quality_status': 'warning', 'quality_acknowledged': True}
# The sheet is the customer's own file, not one someone opens by hand. # The sheet is the customer's own file, not one someone opens by hand.
sheet['production']['sources'][0]['measurement'] = 'file' 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} 'quality_status': 'warning', 'quality_acknowledged': True}
items = [sheet, art] items = [sheet, art]
@@ -61,6 +62,9 @@ def run():
assert [line['total_cents'] for line in approved['items']] == [7990, 8990], approved assert [line['total_cents'] for line in approved['items']] == [7990, 8990], approved
assert approved['total_cents'] == 16081, 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). # One paid order spends a use (a fake payment, no print job).
order_id = uuid4() order_id = uuid4()
with db.connect() as c: with db.connect() as c:
@@ -110,6 +114,10 @@ def run():
manager.call('/operator/site/coupons/' + coupon_id, {'max_uses': 1}) manager.call('/operator/site/coupons/' + coupon_id, {'max_uses': 1})
refused = quote(client, items, code, mail, expected=422) refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Este cupom já foi usado o máximo de vezes.', refused 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, manager.call('/operator/site/coupons/' + coupon_id,
{'max_uses': None, 'max_uses_per_customer': 1}) {'max_uses': None, 'max_uses_per_customer': 1})
refused = quote(client, items, code, mail, expected=422) refused = quote(client, items, code, mail, expected=422)
@@ -135,13 +143,16 @@ def run():
stats = manager.call('/operator/stats?days=30') stats = manager.call('/operator/stats?days=30')
assert any(entry['id'] == coupon_id for entry in stats['coupons']), stats['coupons'] 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/' 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: finally:
with db.connect() as c: with db.connect() as c:
if order_id: if order_id:
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,)) c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,))
if quote_id: if quote_id:
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (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: if coupon_id:
c.execute('DELETE FROM dtf_local.coupons WHERE id=%s', (coupon_id,)) c.execute('DELETE FROM dtf_local.coupons WHERE id=%s', (coupon_id,))
if upload_id: if upload_id:

View File

@@ -44,7 +44,7 @@ def run():
assert rules['treatment_offered'] is True, rules assert rules['treatment_offered'] is True, rules
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-GRADE-{tag}.png') 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} 'quality_status': 'warning', 'quality_acknowledged': True}
refused = client.call('/quotes', quote_body(item, False, mail), expected=422) 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) client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True)
with db.connect() as c: with db.connect() as c:
assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (paid_order,)).fetchone() 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. # 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'] == {} assert client.call('/operator/queue/folder', {'held': [str(paid_order)]}, operator=True)['states'] == {}
with db.connect() as c: 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.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.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()),)) 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') 'and free their files')
finally: finally:
with db.connect() as c: with db.connect() as c:

View File

@@ -121,7 +121,12 @@ def run():
later = deliver({**payload, 'event_id': 'retry-' + uuid4().hex}) later = deliver({**payload, 'event_id': 'retry-' + uuid4().hex})
assert 'already existed' in later.get('outcome', ''), later assert 'already existed' in later.get('outcome', ''), later
assert customer.call('/quotes/' + quote_id)['order']['id'] == order['id'], 'a second order appeared' 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'] assert customer.call('/orders/dev-paid', {'quote_id': quote_id})['id'] == order['id']
other = Client() other = Client()

View File

@@ -155,6 +155,9 @@ def run():
mine = [f for f in early['files'] if f['order'] == oid] 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 [(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'} 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) 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'] == {} 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) 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. # 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] 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) 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) hot = client.call('/operator/queue/hot', {}, operator=True)
due = [p for p in hot['write'] if p['order'] == oid] 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] == \ 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'] assert board['hot'] == {'parts': 1, 'taken': 1, 'waiting': 0}, board['hot']
# Which items go again is chosen before Imprimindo, not while printing (#105). # 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) 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: finally:
client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False}, client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False},
operator=True) operator=True)
@@ -398,7 +409,13 @@ def run():
final = c.execute('''SELECT note,created_by FROM dtf_local.order_files final = c.execute('''SELECT note,created_by FROM dtf_local.order_files
WHERE order_id=%s AND kind='final' AND active''', (parent['id'],)).fetchone() WHERE order_id=%s AND kind='final' AND active''', (parent['id'],)).fetchone()
assert final['created_by'] == 'Prumo' and 'prova' in final['note'].lower(), final assert final['created_by'] == 'Prumo' and 'prova' in final['note'].lower(), final
print('PASS: Prova OK turns Prumo\'s full file into the parent final and queues it') # Entering the queue by Prova OK is Tiny's "Preparando envio", as a card
# moved by hand (orders with a proof skipped it).
with db.connect() as c:
started = c.execute("SELECT payload FROM dtf_local.outbox WHERE event_key=%s",
(f"{parent['id']}:production_started:tiny",)).fetchone()
assert started and started['payload']['event'] == 'production_started', started
print('PASS: Prova OK turns Prumo\'s full file into the parent final, queues it and tells Tiny')
# Prova OK while the parent's file is still being generated (#81, 91,5 m, # Prova OK while the parent's file is still being generated (#81, 91,5 m,
# 2026-11-24): the parent waits in Arte recebida and enters the queue on # 2026-11-24): the parent waits in Arte recebida and enters the queue on
@@ -433,7 +450,40 @@ def run():
moved = c.execute('''SELECT operator,reason FROM dtf_local.movements moved = c.execute('''SELECT operator,reason FROM dtf_local.movements
WHERE order_id=%s AND to_state='tra' ORDER BY id DESC LIMIT 1''', (parent['id'],)).fetchone() WHERE order_id=%s AND to_state='tra' ORDER BY id DESC LIMIT 1''', (parent['id'],)).fetchone()
assert (moved['operator'], moved['reason']) == ('Prumo', 'Prova OK'), moved assert (moved['operator'], moved['reason']) == ('Prumo', 'Prova OK'), moved
print('PASS: a file finished after Prova OK becomes the final and queues the order') with db.connect() as c:
assert c.execute("SELECT 1 FROM dtf_local.outbox WHERE event_key=%s",
(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 # 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 # already printed, back in the queue after one item's final changed, sends
@@ -472,30 +522,69 @@ def run():
{'item_index': 1, 'upload_id': corrected}]}, operator=True)['version'] {'item_index': 1, 'upload_id': corrected}]}, operator=True)['version']
board_order = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == rid) board_order = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == rid)
assert board_order['printed_before'] and board_order['print_suggested'] == [1], board_order.get('print_suggested') assert board_order['printed_before'] and board_order['print_suggested'] == [1], board_order.get('print_suggested')
client.call('/operator/orders/' + rid + '/move', {'state': 'tra', 'version': v}, operator=True) v = client.call('/operator/orders/' + rid + '/move', {'state': 'tra', 'version': v}, operator=True)['version']
from app import hotfolder
def print_items():
with db.connect() as c:
return c.execute('SELECT print_items FROM dtf_local.orders WHERE id=%s', (rid,)).fetchone()['print_items']
def version():
return next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == rid)['version']
assert print_items() == [1], print_items()
# Every item ticked by hand in Arte recebida is a choice too: entering the
# queue keeps it, the suggestion does not take its place.
client.call('/operator/orders/' + rid + '/move', {'state': 'rec', 'version': v, 'reason': 'teste'}, operator=True)
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [0, 1]}, operator=True)['print_items'] == [0, 1]
client.call('/operator/orders/' + rid + '/move', {'state': 'tra', 'version': version()}, operator=True)
assert print_items() == [0, 1], print_items()
# Back to only the corrected item, then pulled onto a machine for real.
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [1]}, operator=True)['print_items'] == [1]
machine = client.call('/operator/machines', {'name': f'Reprint {uuid4().hex[:6]}', 'products': ['textil']},
operator=True)['id']
v = client.call('/operator/orders/' + rid + '/move', {'state': 'imp', 'version': version(), 'machine_id': machine},
operator=True)['version']
with db.connect() as c: with db.connect() as c:
assert c.execute('SELECT print_items FROM dtf_local.orders WHERE id=%s', (rid,)).fetchone()['print_items'] == [1]
hotfolder.start(c, rid)
queued = c.execute('SELECT item_index,upload_id FROM dtf_local.hot_parts WHERE order_id=%s AND round=2', queued = c.execute('SELECT item_index,upload_id FROM dtf_local.hot_parts WHERE order_id=%s AND round=2',
(rid,)).fetchall() (rid,)).fetchall()
assert [(q['item_index'], str(q['upload_id'])) for q in queued] == [(1, corrected)], queued assert [(q['item_index'], str(q['upload_id'])) for q in queued] == [(1, corrected)], queued
c.execute("UPDATE dtf_local.hot_parts SET state='consumed' WHERE order_id=%s AND round=2", (rid,)) # Sent to Revisão by mistake before Flexi took the file, and undone: the
c.execute("UPDATE dtf_local.orders SET state='imp' WHERE id=%s", (rid,)) # file goes back to the folder, alone, and the choice is the same.
v = c.execute('SELECT version FROM dtf_local.orders WHERE id=%s', (rid,)).fetchone()['version'] v = client.call('/operator/orders/' + rid + '/move', {'state': 'rev', 'version': v}, operator=True)['version']
client.call('/operator/orders/' + rid + '/move', {'state': 'rev', 'version': v}, operator=True) assert print_items() is None
v = client.call('/operator/orders/' + rid + '/move', {'state': 'imp', 'version': v, 'reason': 'engano'},
operator=True)['version']
assert print_items() == [1], print_items()
with db.connect() as c: with db.connect() as c:
moved = c.execute('''SELECT items FROM dtf_local.movements WHERE order_id=%s AND to_state='rev' again = c.execute('SELECT item_index,upload_id,state FROM dtf_local.hot_parts WHERE order_id=%s AND round=3',
ORDER BY id DESC LIMIT 1''', (rid,)).fetchone() (rid,)).fetchall()
left = c.execute('SELECT print_items FROM dtf_local.orders WHERE id=%s', (rid,)).fetchone()['print_items'] assert [(r['item_index'], str(r['upload_id']), r['state']) for r in again] == [(1, corrected, 'queued')], again
assert moved['items'] == [1] and left is None, (moved, left) c.execute("UPDATE dtf_local.hot_parts SET state='consumed' WHERE order_id=%s AND round=3", (rid,))
# Chosen by hand: every item means all, as on a first print. # Flexi took it: undoing a later pass to Revisão writes nothing again.
v = client.call('/operator/orders/' + rid + '/move', {'state': 'rev', 'version': v}, operator=True)['version']
v = client.call('/operator/orders/' + rid + '/move', {'state': 'imp', 'version': v, 'reason': 'engano'},
operator=True)['version']
with db.connect() as c:
assert not c.execute('SELECT 1 FROM dtf_local.hot_parts WHERE order_id=%s AND round>3', (rid,)).fetchone()
client.call('/operator/orders/' + rid + '/move', {'state': 'rev', 'version': v}, operator=True)
from app import machine_log
with db.connect() as c:
moved = c.execute("SELECT items FROM dtf_local.movements WHERE order_id=%s AND to_state='rev' "
"ORDER BY id DESC LIMIT 1", (rid,)).fetchone()
item = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (rid,)).fetchone()['snapshot']['items'][1]
metres = machine_log.printed_since(c, machine, None)
assert moved['items'] == [1] and print_items() is None, moved
# Three passes to Revisão, two of them undone: item 2's film, once.
expected = Decimal(str(item['metres'] if item.get('metres') is not None else item.get('billed_metres') or 0))
assert metres == expected, (metres, expected)
# Chosen by hand: every item, or some; never an item the order lacks.
with db.connect() as c: with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='rec' WHERE id=%s", (rid,)) c.execute("UPDATE dtf_local.orders SET state='rec' WHERE id=%s", (rid,))
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [0, 1]}, operator=True)['print_items'] is None assert client.call('/operator/orders/' + rid + '/print-items', {'items': [1, 0, 1]}, operator=True)['print_items'] == [0, 1]
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [0]}, operator=True)['print_items'] == [0] assert client.call('/operator/orders/' + rid + '/print-items', {'items': [0]}, operator=True)['print_items'] == [0]
client.call('/operator/orders/' + rid + '/print-items', {'items': [5]}, operator=True, expected=422) client.call('/operator/orders/' + rid + '/print-items', {'items': [5]}, operator=True, expected=422)
print('PASS: a reprint sends only the item whose final changed, and the choice ends with the print') print('PASS: a reprint sends only the items chosen, keeps an all-items choice, and an undone pass to Revisão '
'neither writes again what Flexi took nor counts the film twice')
# A CDR cannot be decoded by the worker. The designer prepares the full # A CDR cannot be decoded by the worker. The designer prepares the full
# parent PNG, then the worker automatically cuts the child's proof from it. # parent PNG, then the worker automatically cuts the child's proof from it.

View File

@@ -27,6 +27,7 @@ def run():
quote, payment_id = uuid4(), str(900_000_000 + uuid4().int % 99_999_999) quote, payment_id = uuid4(), str(900_000_000 + uuid4().int % 99_999_999)
approved = {'customer': {'mail': 'reconcile@example.test'}, 'items': [], 'total_cents': 1490} approved = {'customer': {'mail': 'reconcile@example.test'}, 'items': [], 'total_cents': 1490}
order_id = None order_id = None
extra = []
try: try:
with db.connect() as c: with db.connect() as c:
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) 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 asked = paid.asked
assert payments.reconcile(db.connect, paid, quote_id=quote) == [] and paid.asked == 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') 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: 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: with db.connect() as c:
if order_id: if order_id:
c.execute("DELETE FROM dtf_local.outbox WHERE event_key LIKE %s", (f'{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): def arts_item(upload_id, arts):
"""One loose-art item with `arts` sources of 10 x 10 cm, one metre long.""" """One loose-art item with `arts` sources of 10 x 5 cm (artwork() is 2:1),
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 10, one every 10 cm."""
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 5,
'copies': 1, 'rotation_degrees': 0, 'mirrored': False, 'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
'measurement': 'customer'} for _ in range(arts)] 'measurement': 'customer'} for _ in range(arts)]
placements = [{'source_index': index, 'copy_index': 0, 'x_cm': 0, 'y_cm': index * 10, 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)] for index in range(arts)]
return {'mode': 'avulsa', 'metres': '1', 'grade': 90, 'uploads': [upload_id] * arts, return {'mode': 'avulsa', 'metres': '1', 'grade': 90, 'uploads': [upload_id] * arts,
'production': {'version': 3, 'film_width_cm': 57, 'height_cm': arts * 10, '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 premium_entry['title'] == 'Têxtil Premium · 8 passadas', premium_entry
assert client.call('/session')['products'][PREMIUM]['enabled'] is False assert client.call('/session')['products'][PREMIUM]['enabled'] is False
premium_item = {**item_spec(PREMIUM, '1', 0, upload_bytes( 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} 'quality_status': 'warning', 'quality_acknowledged': True}
refused = quote(client, premium_item, mail, expected=422) refused = quote(client, premium_item, mail, expected=422)
assert refused['detail'] == 'Este produto não está à venda agora.', refused 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}) manager.call(f'/operator/site/products/{UV}', {'enabled': True})
uid = upload_bytes(client, artwork(), name='LOCAL-SITE-ADMIN.png') 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'] before = client.call('/session')['products'][UV]['unit_cents']
# Switched off: the Site sees it off and the server refuses a new quote. # 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) wait_scan(client,uid,operator=True)
return client.call('/operator/orders/'+order_id+'/reviews',{'upload_id':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 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], 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, 'sources':[{'upload_id':uid,
'kind':'sheet' if mode in ('file','uvfile','premium') else 'artwork', 'kind':'sheet' if mode in ('file','uvfile','premium') else 'artwork',
'width_cm':film_width,'length_cm':length_cm,'copies':1, '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, # 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. # 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 # 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. # 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 # 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') 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') low=upload_bytes(client,low_png,name='arte-150dpi.png')
small={**draft,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,graded)]} small={**draft,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,graded)]}
auto=client.call('/quotes',small) auto=client.call('/quotes',small)
@@ -283,7 +288,11 @@ def run():
assert mixed_item['stroke_choice']=='client_c3', mixed_item assert mixed_item['stroke_choice']=='client_c3', mixed_item
# Loose art split by stroke (item 17): each sheet is an item, and the pair # Loose art split by stroke (item 17): each sheet is an item, and the pair
# has one 1 m minimum, on its first sheet. # 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)]} 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':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),part('0.15',1)]},expected=422)

View File

@@ -165,8 +165,10 @@ class CartPricingCharacterizationTest(unittest.TestCase):
split = priced('split-under-one-metre') split = priced('split-under-one-metre')
self.assertEqual([(p['billed_metres'], p['total_cents']) for p in split], self.assertEqual([(p['billed_metres'], p['total_cents']) for p in split],
[('0.8', 1752), ('0.2', 438)]) [('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] 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): 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 # 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)) 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__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@@ -16,9 +16,14 @@ class PricingTests(unittest.TestCase):
source = Path('web/site-config.js').read_text() source = Path('web/site-config.js').read_text()
prices = source.split('const PRECO=')[1].split(';',1)[0] prices = source.split('const PRECO=')[1].split(';',1)[0]
calculator = source.split('const cobrar=')[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)) 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]; const unit=PRECO[mode];
results.push([mode,String(metres),cobrar(metres),Math.round(unit*100),Math.round(cobrar(metres)*unit*100)]); results.push([mode,String(metres),cobrar(metres),Math.round(unit*100),Math.round(cobrar(metres)*unit*100)]);
}process.stdout.write(JSON.stringify(results));''' }process.stdout.write(JSON.stringify(results));'''
@@ -32,6 +37,18 @@ class PricingTests(unittest.TestCase):
self.assertEqual(result['unit_cents'],unit) self.assertEqual(result['unit_cents'],unit)
self.assertEqual(result['total_cents'],total) 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): def test_one_price_per_product(self):
# Dropstar, 2026-10-23: textile R$ 19,90 ready sheet and R$ 21,90 loose # 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). # art; UV R$ 79,90 and R$ 89,90. Premium R$ 39,90 (2026-11-10).

View File

@@ -48,9 +48,10 @@ class RenderLimitTests(unittest.TestCase):
return {'production': {'height_cm': height, 'placements': [ return {'production': {'height_cm': height, 'placements': [
{'y_cm': 0, 'length_cm': height, 'source_index': 0}]}} {'y_cm': 0, 'length_cm': height, 'source_index': 0}]}}
self.assertEqual(render_seconds(film(800)), RENDER_SECONDS) self.assertEqual(render_seconds(film(800)), RENDER_SECONDS)
# A film in parts gets one part more: a cut moved to a clear band (#136). # Parts of 10 m (Marcus, 2026-11-18), and a film in parts gets one
self.assertEqual(render_seconds(film(2359.2)), 3 * RENDER_SECONDS) # part more: a cut moved to a clear band (#136).
self.assertEqual(render_seconds(film(4600)), 5 * RENDER_SECONDS) self.assertEqual(render_seconds(film(2359.2)), 4 * RENDER_SECONDS)
self.assertEqual(render_seconds(film(4600)), 6 * RENDER_SECONDS)
self.assertEqual(render_seconds({'mode': 'file'}), RENDER_SECONDS) self.assertEqual(render_seconds({'mode': 'file'}), RENDER_SECONDS)

View File

@@ -23,7 +23,7 @@ class Database:
"""Just the reads and writes approve_parent makes.""" """Just the reads and writes approve_parent makes."""
def __init__(self, parts, active): def __init__(self, parts, active):
self.parts, self.active, self.inserted = parts, active, [] self.parts, self.active, self.inserted, self.outbox = parts, active, [], []
def execute(self, sql, params=()): def execute(self, sql, params=()):
text = ' '.join(sql.split()) text = ' '.join(sql.split())
@@ -37,10 +37,17 @@ class Database:
return Rows([{'upload_id': u} for u in self.active]) return Rows([{'upload_id': u} for u in self.active])
if text.startswith('INSERT INTO dtf_local.order_files'): if text.startswith('INSERT INTO dtf_local.order_files'):
self.inserted.append(params[2]) self.inserted.append(params[2])
if text.startswith('UPDATE dtf_local.orders SET state'):
return Rows([{'version': 2}])
if 'FROM dtf_local.outbox' in text:
return Rows([])
if text.startswith('INSERT INTO dtf_local.outbox'):
self.outbox.append((params[0], params[2].obj['event']))
return Rows([{'ok': 1}]) return Rows([{'ok': 1}])
ORDER = {'id': 'o', 'state': 'rec', 'cancelled_at': None, 'snapshot': {'items': [{'mode': 'file'}]}} ORDER = {'id': 'o', 'number': 131, 'state': 'rec', 'cancelled_at': None, 'payment': {'provider': 'mercadopago'},
'snapshot': {'items': [{'mode': 'file'}]}}
class ProofPartsTests(unittest.TestCase): class ProofPartsTests(unittest.TestCase):
@@ -54,6 +61,13 @@ class ProofPartsTests(unittest.TestCase):
approve_parent(db, ORDER, 'Prumo') approve_parent(db, ORDER, 'Prumo')
self.assertEqual(db.inserted, ['p2']) self.assertEqual(db.inserted, ['p2'])
def test_entering_the_queue_by_prova_ok_tells_tiny(self):
# Tiny's "Preparando envio", as for a card moved by hand: orders with
# a proof skipped it.
db = Database(['p1'], set())
self.assertTrue(approve_parent(db, ORDER, 'Prumo'))
self.assertEqual(db.outbox, [('o:production_started:tiny', 'production_started')])
def test_a_final_someone_prepared_stays(self): def test_a_final_someone_prepared_stays(self):
db = Database(['p1', 'p2'], {'treated'}) db = Database(['p1', 'p2'], {'treated'})
approve_parent(db, ORDER, 'Prumo') approve_parent(db, ORDER, 'Prumo')

View File

@@ -7,7 +7,7 @@ import unittest
from decimal import Decimal from decimal import Decimal
from app.hotfolder import reprint_default from app.hotfolder import reprint_default
from app.machine_stats import _film from app.machine_log import film_metres
class ReprintTests(unittest.TestCase): class ReprintTests(unittest.TestCase):
@@ -27,8 +27,24 @@ class ReprintTests(unittest.TestCase):
def test_the_machine_counts_only_the_items_printed_again(self): def test_the_machine_counts_only_the_items_printed_again(self):
snapshot = {'items': [{'billed_metres': '2.0'}, {'billed_metres': '3.5'}]} snapshot = {'items': [{'billed_metres': '2.0'}, {'billed_metres': '3.5'}]}
self.assertEqual(_film(snapshot), Decimal('5.5')) self.assertEqual(film_metres(snapshot), Decimal('5.5'))
self.assertEqual(_film(snapshot, [1]), Decimal('3.5')) self.assertEqual(film_metres(snapshot, [1]), Decimal('3.5'))
class ProofFilmTests(unittest.TestCase):
# A proof sheet is centimetres of film, counted in metres: it once counted
# 15 m per proof, enough for the machine's 10 m cleaning alert.
proof = {'proof_of': 81, 'items': [{'billed_metres': '0'}, {'billed_metres': '0'}]}
def test_a_proof_with_colour_samples_counts_its_real_length(self):
# Marcus, 2026-11-26: the finest stroke's 15 cm and two 5 cm samples,
# 1 cm of clear film between them: 27 cm.
windows = {'0': [['10', '25'], ['40', '45'], ['80', '85']]}
self.assertEqual(film_metres(self.proof, [0], windows), Decimal('0.27'))
def test_a_proof_made_before_the_samples_counts_15_cm(self):
self.assertEqual(film_metres(self.proof), Decimal('0.30'))
self.assertEqual(film_metres(self.proof, None, {'1': [['0', '15']]}), Decimal('0.30'))
if __name__ == '__main__': if __name__ == '__main__':

View File

@@ -39,6 +39,36 @@ class SheetGapTests(unittest.TestCase):
self.assertEqual(str(caught.exception), SHEET_GAP_CHANGED) 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): class ClosePiecesTests(unittest.TestCase):
"""The Site's count of pieces under 5 mm travels with the item to the """The Site's count of pieces under 5 mm travels with the item to the
Kanban card (Marcus, 2026-11-26, #81).""" Kanban card (Marcus, 2026-11-26, #81)."""

View File

@@ -46,5 +46,44 @@ class SheetTrimTests(unittest.TestCase):
Item.model_validate(sheet_item(top=-1)) 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__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@@ -77,7 +77,7 @@ class FakeTinyCase(unittest.TestCase):
if request.method == 'GET' and path.startswith('/contatos/'): if request.method == 'GET' and path.startswith('/contatos/'):
wanted = int(path.rsplit('/', 1)[-1]) wanted = int(path.rsplit('/', 1)[-1])
if self.refuse_contact: if self.refuse_contact:
return httpx.Response(429 if self.refuse_contact == 429 else 503, text='indisponível') return httpx.Response(self.refuse_contact, text='indisponível')
return httpx.Response(200, json=next(c for c in self.contacts if c['id'] == wanted)) return httpx.Response(200, json=next(c for c in self.contacts if c['id'] == wanted))
if request.method == 'POST' and path == '/contatos': if request.method == 'POST' and path == '/contatos':
contact = {**json.loads(request.content), 'id': 500 + len(self.contacts)} contact = {**json.loads(request.content), 'id': 500 + len(self.contacts)}
@@ -267,11 +267,26 @@ class TinyTests(FakeTinyCase):
self.tiny.deliver('k2', {**PAID, 'number': 43}) self.tiny.deliver('k2', {**PAID, 'number': 43})
self.assertNotIn('vendedor', self.orders[1]) self.assertNotIn('vendedor', self.orders[1])
def test_a_failed_seller_reading_does_not_hold_the_order(self): def test_a_refused_seller_reading_does_not_hold_the_order_and_reaches_sentry(self):
self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477}}) self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477}})
self.refuse_contact = True self.refuse_contact = 400
self.assertEqual(self.tiny.deliver('k1', PAID)['status'], 'created') with self.assertLogs(level='ERROR') as logged:
self.assertEqual(self.tiny.deliver('k1', PAID)['status'], 'created')
self.assertNotIn('vendedor', self.orders[0]) self.assertNotIn('vendedor', self.orders[0])
self.assertIn('without one', logged.output[0])
def test_an_unavailable_tiny_retries_the_delivery_instead_of_dropping_the_seller(self):
# The seller cannot be set after the order is made (order 151250): a
# 5xx while reading it tries the whole delivery again.
from app.tiny import TinyUnavailable
self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477}})
self.refuse_contact = 503
with self.assertRaises(TinyUnavailable):
self.tiny.deliver('k1', PAID)
self.assertEqual(self.orders, [])
self.refuse_contact = None
self.tiny.deliver('k1', PAID)
self.assertEqual(self.orders[0]['vendedor'], {'id': 977231477})
def test_a_busy_tiny_retries_the_delivery_instead_of_dropping_the_seller(self): def test_a_busy_tiny_retries_the_delivery_instead_of_dropping_the_seller(self):
from app.tiny import TinyRateLimit from app.tiny import TinyRateLimit

View File

@@ -53,5 +53,29 @@ class RefusedDeliveryTest(unittest.TestCase):
self.assertEqual(self.tick_with(9, limit).call_count, 1) 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__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@@ -58,6 +58,21 @@ def run():
assert quote_id in {q['id'] for q in page['quotes']} assert quote_id in {q['id'] for q in page['quotes']}
print('PASS: a live payment attempt keeps an approved quote and its files') 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 # The attempt is final now: the quote expires, its files are freed and the
# customer is told once. # customer is told once.
with db.connect() as c: with db.connect() as c:

View File

@@ -30,7 +30,7 @@ const contactWho=order=>(order.contact_by||'')+' em '+when(order.contact_since);
// The print proof (app/proof.py): asked for at checkout, or an order above 10 m. // The print proof (app/proof.py): asked for at checkout, or an order above 10 m.
// The room marks "Prova OK" once it is checked; without it, no Finalizado. // The room marks "Prova OK" once it is checked; without it, no Finalizado.
const PROOF_ABOVE_METRES=10; const PROOF_ABOVE_METRES=10;
const PROOF_RULE='Até 15 cm por classe, do trecho de traço mais fino; no máximo 3 provas por pedido, sem cobrança.'; const PROOF_RULE='Até 30 cm por classe: o trecho de traço mais fino e amostras das cores principais; no máximo 3 provas por pedido, sem cobrança.';
const needsProof=order=>!!order.snapshot.proof||order.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0)>PROOF_ABOVE_METRES; const needsProof=order=>!!order.snapshot.proof||order.snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0)>PROOF_ABOVE_METRES;
const proofPending=order=>needsProof(order)&&!order.proof_ok_at&&order.state!=='fin'&&!order.cancelled_at&&!order.proof_parent; const proofPending=order=>needsProof(order)&&!order.proof_ok_at&&order.state!=='fin'&&!order.cancelled_at&&!order.proof_parent;
// The proof card (app/proof.py): the order's own card waits outside the queue // The proof card (app/proof.py): the order's own card waits outside the queue
@@ -427,7 +427,8 @@ function cardFlags(order){
const dots=s.items.reduce((t,i)=>t+(i.residue_accepted||0),0); const dots=s.items.reduce((t,i)=>t+(i.residue_accepted||0),0);
if(live&&dots)out.push(['warn','Resíduo','O cliente aceitou imprimir com '+residueNote({residue_accepted:dots})]); if(live&&dots)out.push(['warn','Resíduo','O cliente aceitou imprimir com '+residueNote({residue_accepted:dots})]);
// A reprint: only some items go to the machine again (#105). // A reprint: only some items go to the machine again (#105).
if(live&&order.print_items?.length)out.push(['warn','Reimpressão','Vão para a máquina só: '+order.print_items.map(i=>'item '+(i+1)).join(', ')]); // Every item ticked is a choice too, but no reprint of some: no flag.
if(live&&order.print_items?.length&&order.print_items.length<s.items.length)out.push(['warn','Reimpressão','Vão para a máquina só: '+order.print_items.map(i=>'item '+(i+1)).join(', ')]);
// A ready sheet with pieces closer than 5 mm (Marcus, 2026-11-26, #81). // A ready sheet with pieces closer than 5 mm (Marcus, 2026-11-26, #81).
const close=s.items.reduce((t,i)=>t+(i.close_pieces||0),0); const close=s.items.reduce((t,i)=>t+(i.close_pieces||0),0);
if(live&&close)out.push(['warn','Peças coladas',closeNote(close)]); if(live&&close)out.push(['warn','Peças coladas',closeNote(close)]);

View File

@@ -154,7 +154,8 @@ function montarQuoteFigures(lines){
}); });
const catalog=MONTAR.catalog?.avulsa; const catalog=MONTAR.catalog?.avulsa;
if(!catalog)throw new Error('Preço de tabela indisponível agora.'); 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); const total=+billed.reduce((sum,metres)=>sum+metres,0).toFixed(2);
let unit=catalog.unit_cents,best=null; let unit=catalog.unit_cents,best=null;
for(const band of catalog.bands||[]){ 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'); 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 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 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(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(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')) if((order.print_files||[]).some(r=>r.status==='failed'||r.status==='manual'||r.timed_out)&&may('produce'))
@@ -1144,7 +1144,10 @@ function reprintChoice(order){
const input=node('input');input.checked=chosen.has(index);input.disabled=!may('produce'); const input=node('input');input.checked=chosen.has(index);input.disabled=!may('produce');
box.append(checkbox('Item '+(index+1)+', '+productName(item),input));return input; box.append(checkbox('Item '+(index+1)+', '+productName(item),input));return input;
}); });
box.append(node('small',order.print_items?'Só os itens marcados vão para a máquina.' // A saved choice is the whole list when every item goes (never NULL, which
// is "not chosen yet" and would show the suggestion again).
const all=order.print_items?.length===order.snapshot.items.length;
box.append(node('small',order.print_items?(all?'Todos os itens vão para a máquina.':'Só os itens marcados vão para a máquina.')
:order.print_suggested?'Marcados os itens cujo arquivo mudou desde a última impressão.' :order.print_suggested?'Marcados os itens cujo arquivo mudou desde a última impressão.'
:'O pedido já foi impresso: marque só os itens que precisam sair de novo.')); :'O pedido já foi impresso: marque só os itens que precisam sair de novo.'));
if(may('produce')){ if(may('produce')){

View File

@@ -323,7 +323,10 @@ function machineForm(m){
left.push(remove); left.push(remove);
} }
const d=formDialog(m?'Editar máquina':'Nova máquina',{width:520,left, 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('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), field('Vagas em Imprimindo',places,PLACES_NOTE),
checkbox('Ativa: recebe pedidos',active)], 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 was never reviewed/,()=>'a cotação ainda não tinha sido revisada'],
[/^refused: quote uses an obsolete/,()=>'a cotação usa uma montagem antiga'], [/^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]], [/^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);} for(const [pattern,text] of rules){const m=outcome.match(pattern);if(m)return text(m);}
return outcome; return outcome;
@@ -566,6 +568,9 @@ async function fetchFile(url,options){
} }
async function fetchInto(dir,file,watched=false){ async function fetchInto(dir,file,watched=false){
const r=await fetchFile(file.url,{referrerPolicy:'no-referrer'}); 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+').'); 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); await writeWhole(dir,file.name,r,watched);
} }
@@ -624,9 +629,16 @@ async function syncFolder(force=false){
FOLDER.busy=true; FOLDER.busy=true;
try{ try{
if(stages)await makeStageFolders(); 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}); const {files,states,receipts=[],reviews=[]}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null});
// By file: an item over 15 m is several parts (item 13), each its own file. // 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])); const wanted=new Map(files.map(f=>[f.upload_id,f]));
const where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads'; const where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads';
let removed=0, moved=0, saved=0; let removed=0, moved=0, saved=0;
@@ -640,7 +652,7 @@ async function syncFolder(force=false){
...(folder===STAGE_FOLDERS.fin?{at:file.at||Date.now()}:{})}); ...(folder===STAGE_FOLDERS.fin?{at:file.at||Date.now()}:{})});
FOLDER.last=new Date();await keepSaved();}; FOLDER.last=new Date();await keepSaved();};
if(stages)for(const [uid,rec] of [...FOLDER.saved])await step(rec.name,async()=>{ 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 state=states[rec.order], target=STAGE_FOLDERS[state];
const now=wanted.get(uid); const now=wanted.get(uid);
const replaced=(state==='rec'||state==='tra')&&(!now||now.order!==rec.order); 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'; $('cMetroLbl').textContent = it.extra ? 'Metro · com '+rs(it.extra)+' de arquivo manual' : 'Metro';
$('cMetro').textContent=rs(it.unit); $('cMetro').textContent=rs(it.unit);
$('cMetragem').textContent=fmtM(it.cob)+' m'; $('cMetragem').textContent=fmtM(it.cob)+' m';
const partes=ehFolha(it.modo) ? Math.ceil(it.metros/20) : 1; // Partes de até 10 m (Marcus, 18/11/2026): o FlexiPRINT não abre mais que isso.
$('cPartes').textContent = partes>1 ? ' Sai em '+partes+' partes de até 20 m.' : ''; 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); 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 = $('cObs').textContent =
it.cob===MINIMO_M && it.metros<MINIMO_M it.cob===MINIMO_M && it.metros<MINIMO_M
? (ehFolha(it.modo) ? 'Pedido mínimo de 1 m.' ? (ehFolha(it.modo) ? 'Pedido mínimo de 1 m.'
: 'Pedido mínimo de 1 m: ainda cabem '+sobraCm+' cm de artes sem custo.') : '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); $('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); 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; const larguraFilme=()=>MODOS[modo].larg;
// cobrança proporcional: arredonda para cima em 10 cm · 2,75 m vira 2,80 m // Cobrança a cada 10 cm, com 8 mm a favor do cliente (Marcus, 27/11/2026):
const cobrar=m=>Math.max(MINIMO_M, Math.ceil(m*10)/10); // 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 // 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. // 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 cobrarMontagem=()=>!ehFolha() && montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(metros);
const fmtM=m=>m.toFixed(2).replace('.',','); const fmtM=m=>m.toFixed(2).replace('.',',');
const cls=n=>n>=85?'ok':n>=50?'av':'er'; 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); figura.append(legenda,desenho); painel.append(figura);
desenhaMontagem(desenho, lista, 0, W, uso, r=>{ desenhaMontagem(desenho, lista, 0, W, uso, r=>{
if(area.montagemVersao!==versao) return; // a montagem mudou nesse meio-tempo 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, 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}; layout:r.placements ? {height_cm:+r.alturaCm.toFixed(4), placements:r.placements} : null};
if(feitas.filter(Boolean).length<grupos.length) return; 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>'+ '<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+'">'+ '<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>'+ '<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>' : ''; '</div>' : '';
return '<div class="rep" data-folha="'+i+'">'+ return '<div class="rep" data-folha="'+i+'">'+
'<div class="repTopo"><div class="miniF">'+mini+'</div><div class="repInfo">'+ '<div class="repTopo"><div class="miniF">'+mini+'</div><div class="repInfo">'+