Compare commits

..

21 Commits

Author SHA1 Message Date
Cauê Faleiros
aeb43500a7 test: the pending-upload burst waits for the gateway's bucket to refill (CI run 393)
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 7m10s
Build and deploy / Secret scan and release gate (push) Successful in 4s
Build and deploy / Publish images (push) Successful in 53s
nginx allows 20 r/s with a burst of 100; after the upload starts before
it, a fast runner met nginx's 429 instead of the API's Retry-After 15.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:32:26 -03:00
Cauê Faleiros
857eea3379 feat: copies from the file name, the proof in the summaries, the grade off the customer's screen (Rodada 5, B3, B6, D6)
Some checks failed
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Integration suite on a real stack (push) Failing after 1m17s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Has been skipped
B6: "12x nome.png" enters with 12 copies, art or ready sheet (up to 200;
"1920x1080.png" is not read as copies). B3: the DPI refusal speaks per
art, the cart and payment summaries list "Prova antes de imprimir" when
chosen, and below 10 m the proof box stays, closed, saying the rule.
D6: the Ajuste Fino refusal no longer shows the grade number (Site and
server); the unused motivoNota helper is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:28:24 -03:00
Cauê Faleiros
f739c9d4e4 feat: the bobbin footer names the customer and counts the pieces, without price (Rodada 5, C3)
DROPSTAR · Pedido DTF-7 · <cliente> · Item 1/2 · data · metros · N peças
(loose arts) or N cópias (a ready sheet repeated). The name is tidied to
cp1252 and cut at 24 characters; the proof footer is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:14:04 -03:00
Cauê Faleiros
7fc091a1bd feat: a PNG that records 200 DPI or more offers its own size, Manter, and the Prumo says if it was kept (Rodada 5, A1)
The Site reads the pHYs chunk of a loose art; at 200 DPI or more the
size in the file is the default width and a Manter button sits before
the table sizes (also when the art is turned 90 degrees). The source
carries saved_width_cm and saved_dpi, used only by the Prumo report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:11:21 -03:00
Cauê Faleiros
7e33e6fb1d fix: a hostile PDF cannot hold the scanner: bounded DPI reading and a stuck scan is reported
All checks were successful
Build and deploy / Validate source (push) Successful in 8s
Build and deploy / Integration suite on a real stack (push) Successful in 8m38s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m19s
The DPI of a stored PDF is read in a subprocess killed after
PDF_MAX_SECONDS + 5; inside it, only image draws count toward
PDF_MAX_DRAWS (heavy vector art still reads), content streams are parsed
once per object, and the deadline is checked every 1000 operators. A scan
busy for more than SCAN_STUCK_SECONDS marks the scanner unhealthy and logs
one error to Sentry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:50:14 -03:00
Cauê Faleiros
37d747697a copy: e-mails and notes without "a gente", "é só" or em dashes
Order and account e-mails say who acts ("Conferimos a arte"), the test
e-mail is one sentence, the machine alerts and Prumo lines use a colon,
and the default video title matches the Site.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:50:14 -03:00
Cauê Faleiros
c4f8ba1b70 copy: the Kanban says what to do, not how the system does it
All checks were successful
Build and deploy / Validate source (push) Successful in 7s
Build and deploy / Integration suite on a real stack (push) Successful in 8m32s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m28s
Order card, folders, Montar and Integrations follow the copy guide: the
folders card says where each file stays instead of walking through every
move, the cancel, correction and regenerate dialogs are one fact and the
next step, no rhetorical questions ("Conferiu?", "A arte chegou boa?")
and no "Agora é só".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:36:48 -03:00
Cauê Faleiros
4283c93526 copy: the Site says the fact and the next step, in the redesign's words
All checks were successful
Build and deploy / Validate source (push) Successful in 12s
Build and deploy / Integration suite on a real stack (push) Successful in 10m50s
Build and deploy / Secret scan and release gate (push) Successful in 13s
Build and deploy / Publish images (push) Successful in 2m6s
Help, editor notices, cart, checkout and Minha conta rewritten by the
approved copy guide: no "a gente", no em dashes, no rhetorical questions,
who acts is clear, at most two sentences per notice. The proof text says
30 cm (was 15 cm) and the billed length no longer says it only rounds up
(8 mm grace). Buttons follow the redesign: "Imprimir assim mesmo",
"Subir em dois arquivos".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:28:26 -03:00
Cauê Faleiros
eb7a92bb89 fix: a refusal the server explains is a warning on the Kanban and is not sent from the Site
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 8m58s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m26s
Of about 60 Sentry issues in two weeks, five were bugs: the rest were the
system working (a rule, a check, a limit explained to the person) or a
network drop. A 4xx with a sentence for the person is now a warning on the
Kanban, tagged recusa, still counted per kind, since a refusal the team keeps
meeting says a screen confuses; the Site sends none, the customer reads it.
A 4xx with a list of fields (what the page sent was wrong) and a 5xx stay
errors, as do JavaScript errors and the red messages that do not come from a
refusal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:02:15 -03:00
Cauê Faleiros
9fc4d4e906 fix: a cancelled upload holds no reservation, an old ready sheet is flagged in the cart, the address check is guidance (DTF-WEB-14, 22, 24)
All checks were successful
Build and deploy / Validate source (push) Successful in 1m39s
Build and deploy / Integration suite on a real stack (push) Successful in 10m18s
Build and deploy / Secret scan and release gate (push) Successful in 16s
Build and deploy / Publish images (push) Successful in 2m33s
- 14: switching products cancelled the files being sent, but each one still
  waiting for a place opened its reservation when it got one, and none gave
  it back: 27 in ten seconds filled the cap of 30 (29/11). A cancelled upload
  now never starts, and one cancelled after starting gives its place back.
- 22: a ready sheet kept in the cart from before the 8 mm says so on its row
  and holds Pagar, instead of a refusal after the whole checkout.
- 24: "Preencha o endereço de entrega" is a warning, not an error.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-30 09:36:34 -03:00
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
81 changed files with 1327 additions and 431 deletions

View File

@@ -101,7 +101,7 @@ jobs:
# the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration.
- name: Print-file geometry and provider adapters
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_one_machine tests.test_profiles tests.test_sheet_gap tests.test_reprint tests.test_proof_parts tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage tests.test_health -v
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_one_machine tests.test_profiles tests.test_sheet_gap tests.test_reprint tests.test_proof_parts tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage tests.test_health tests.test_saved_size -v
- name: Runtime and retention regressions
run: |

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -16,7 +16,7 @@ router = APIRouter()
CATALOG = {
'subindo': 'Subindo a arte pelo celular',
'nota': 'O que é a nota da arte — e o que ela não é',
'nota': 'O que a nota da arte mostra',
'png': 'Por que PNG com fundo transparente',
'avulsas': 'Montando artes avulsas e vendo a folha ao vivo',
'retirada': 'Retirada em Franca em 24 h',

View File

@@ -269,11 +269,14 @@ def list_machines(user=Depends(can('view'))):
def create_machine(body: MachineIn, user=Depends(can('users'))):
mid = uuid4()
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone():
raise HTTPException(409, 'Já existe uma máquina com este nome.')
c.execute('''INSERT INTO dtf_local.machines(id,name,products,active,limit_metres,places)
VALUES(%s,%s,%s,%s,%s,%s)''', (mid, body.name.strip(), sorted(set(body.products)), body.active,
body.limit_metres, body.places or machines.DEFAULT_PLACES))
# A machine's hot folder is its first name, for good: no other machine
# may be called that, or two would share one folder.
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) OR lower(folder)=lower(%s)',
(body.name.strip(), body.name.strip())).fetchone():
raise HTTPException(409, 'Já existe uma máquina, ou a pasta de uma máquina, com este nome.')
c.execute('''INSERT INTO dtf_local.machines(id,name,folder,products,active,limit_metres,places)
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (mid, body.name.strip(), body.name.strip(), sorted(set(body.products)),
body.active, body.limit_metres, body.places or machines.DEFAULT_PLACES))
audit('machine_created', operator=user, machine=body.name)
return {'id': str(mid)}
@@ -281,9 +284,9 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
@router.post('/api/operator/machines/{mid}')
def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s',
(body.name.strip(), mid)).fetchone():
raise HTTPException(409, 'Já existe uma máquina com este nome.')
if c.execute('''SELECT 1 FROM dtf_local.machines WHERE (lower(name)=lower(%s) OR lower(folder)=lower(%s))
AND id<>%s''', (body.name.strip(), body.name.strip(), mid)).fetchone():
raise HTTPException(409, 'Já existe uma máquina, ou a pasta de uma máquina, com este nome.')
if not c.execute('''UPDATE dtf_local.machines SET name=%s,products=%s,active=%s,limit_metres=%s,
places=COALESCE(%s,places) WHERE id=%s RETURNING id''',
(body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres,
@@ -329,8 +332,8 @@ def test_mail(request: Request, user=Depends(can('integrations'))):
"""A message to whoever asked, to prove the mail server works."""
with db.connect() as c:
if not mail.queue(c, 'test', user, 'Teste de e-mail · Kanban DTF',
'Este é um teste do Kanban DTF. Se chegou, o envio de e-mails está funcionando: '
'os e-mails dos clientes.'):
'Este é um teste do Kanban DTF. Se chegou, o envio de e-mails aos clientes '
'está funcionando.'):
raise HTTPException(409, 'O envio de e-mails não está configurado no servidor.')
audit('mail_test_queued', operator=user)
return {'ok': True, 'to': user}

View File

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

View File

@@ -132,6 +132,10 @@ class ProductionSource(StrictModel):
# and printed; the file itself is length_cm plus both trims long.
trim_top_cm: Decimal = Field(default=Decimal(0), ge=0, le=6000)
trim_bottom_cm: Decimal = Field(default=Decimal(0), ge=0, le=6000)
# The size the PNG itself recorded (item A1, round 5), only for the Prumo
# report; nothing on the server prices or packs by it.
saved_width_cm: Decimal | None = Field(default=None, gt=0, le=10000)
saved_dpi: int | None = Field(default=None, ge=1, le=10000, strict=True)
class ProductionPlacement(StrictModel):
source_index: int = Field(ge=0, le=199, strict=True)
@@ -291,6 +295,17 @@ class Item(StrictModel):
raise ValueError('Finished sheets must retain their original orientation')
if placed != expected:
raise ValueError('Production layout does not cover every source copy')
# No piece on top of another: stacked pieces bill less film than they
# print on, and print over each other. Swept down the film, so only
# the pieces still open at each row are compared.
boxes = sorted((p.y_cm, p.y_cm + p.length_cm, p.x_cm, p.x_cm + p.width_cm)
for p in self.production.placements)
open_boxes = []
for top, bottom, left, right in boxes:
open_boxes = [b for b in open_boxes if b[0] > top + tolerance]
if any(l < right - tolerance and left < r - tolerance for _, l, r in open_boxes):
raise ValueError('Duas peças da montagem ficaram uma sobre a outra. Monte o pedido de novo.')
open_boxes.append((bottom, left, right))
if self.quality_status == 'warning' and not self.quality_acknowledged:
raise ValueError('Resolution warning must be acknowledged')
return self

View File

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

View File

@@ -32,6 +32,14 @@ PDF_VECTOR_DPI = 300
# grade them, so neither does this.
PDF_MAX_BYTES = 150 * 1048576
HEAD_BYTES = 1048576
# How much of a PDF's drawing is walked for its DPI: images and forms drawn
# (Do), however many paths a vector page has. A page whose forms draw other
# forms, ten times each, eight deep, is 10^8 draws in a 2 KB file: it
# held the scanner's one thread for hours and every upload behind it
# (security review, 2026-11-27). Past either limit the DPI is unknown, as for
# a format this cannot read, and the order is reviewed by a person.
PDF_MAX_DRAWS = 5000
PDF_MAX_SECONDS = 10
# Rounding in the browser and here can differ by a point on the same file.
TOLERANCE = 2
@@ -84,10 +92,27 @@ def _multiply(a, b):
a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]]
class _TooMuch(Exception):
"""The PDF's drawing is larger than PDF_MAX_DRAWS or PDF_MAX_SECONDS."""
def pdf_dpi(path):
"""The page's area-weighted image DPI, 300 for vectors only, None if the
file is not a one-page PDF this can read."""
file is not a one-page PDF this can read, or draws more than it is worth
walking (PDF_MAX_DRAWS, PDF_MAX_SECONDS)."""
import time
import pikepdf
deadline = time.monotonic() + PDF_MAX_SECONDS
steps = [0]
parsed = {}
def instructions_of(stream):
# A form drawn many times is read once.
key = stream.objgen if stream.objgen != (0, 0) else id(stream)
if key not in parsed:
parsed[key] = pikepdf.parse_content_stream(stream)
return parsed[key]
try:
with pikepdf.open(path) as pdf:
if len(pdf.pages) != 1:
@@ -99,7 +124,9 @@ def pdf_dpi(path):
def walk(resources, instructions, ctm, depth):
stack = []
xobjects = resources.get('/XObject', {}) if resources is not None else {}
for operands, operator in instructions:
for count, (operands, operator) in enumerate(instructions):
if count % 1000 == 0 and time.monotonic() > deadline:
raise _TooMuch
op = str(operator)
if op == 'q':
stack.append(ctm)
@@ -108,6 +135,9 @@ def pdf_dpi(path):
elif op == 'cm':
ctm = _multiply(ctm, [float(v) for v in operands])
elif op == 'Do' and operands:
steps[0] += 1
if steps[0] > PDF_MAX_DRAWS or time.monotonic() > deadline:
raise _TooMuch
xobject = xobjects.get(str(operands[0]))
if xobject is None:
continue
@@ -120,9 +150,14 @@ def pdf_dpi(path):
elif subtype == '/Form' and depth < 8:
matrix = [float(v) for v in xobject.get('/Matrix', [1, 0, 0, 1, 0, 0])]
walk(xobject.get('/Resources', resources),
pikepdf.parse_content_stream(xobject), _multiply(ctm, matrix), depth + 1)
instructions_of(xobject), _multiply(ctm, matrix), depth + 1)
walk(page.obj.get('/Resources'), pikepdf.parse_content_stream(page), [1, 0, 0, 1, 0, 0], 0)
except _TooMuch:
import logging
logging.warning('PDF %s draws more than %s images and forms, or takes over %s s: its DPI is left unknown',
os.path.basename(path), PDF_MAX_DRAWS, PDF_MAX_SECONDS)
return None
except Exception:
return None
found = [(dpi, area) for dpi, area in found if dpi > 0]
@@ -132,14 +167,47 @@ def pdf_dpi(path):
return js_round(sum(dpi * area for dpi, area in found) / total)
def _pdf_dpi_child(result, path):
result.put(pdf_dpi(path))
def bounded_pdf_dpi(path):
"""pdf_dpi in a process of its own, ended past PDF_MAX_SECONDS: the PDF
library itself can be held by a file (a huge compressed stream), where
pdf_dpi's own limits cannot reach. None when it did not finish."""
import multiprocessing
from queue import Empty
context = multiprocessing.get_context('spawn')
result = context.Queue()
process = context.Process(target=_pdf_dpi_child, args=(result, path))
process.start()
try:
process.join(PDF_MAX_SECONDS + 5)
if process.is_alive():
process.kill()
process.join()
import logging
logging.warning('PDF %s took over %s s to read: its DPI is left unknown',
os.path.basename(path), PDF_MAX_SECONDS + 5)
return None
try:
return result.get(timeout=5)
except Empty:
return None
finally:
result.close()
result.join_thread()
def stored_pdf_dpi(storage, row):
"""A stored PDF's DPI, read once; None when it is above PDF_MAX_BYTES."""
"""A stored PDF's DPI, read once; None when it is above PDF_MAX_BYTES or
takes too long to read (bounded_pdf_dpi)."""
if row['size'] > PDF_MAX_BYTES:
return None
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
storage.client.download_fileobj(storage.bucket, row['object_key'], handle)
handle.flush()
return pdf_dpi(handle.name)
return bounded_pdf_dpi(handle.name)
class Files:
@@ -227,6 +295,35 @@ def resolution_issue(files, items, rows):
return None
def proportion_issue(files, items, rows):
"""Why a cart's layout cannot be priced, or None: a raster file laid out
at proportions it does not have (a 5 m sheet sent as 10 cm, say). The
print file refuses the same thing (app/printfile.py check_layout), but
only after payment; here it is refused before. A PDF, or a file whose
size the first bytes do not tell, is left to that later check."""
from .printfile import ASPECT_TOLERANCE
for index, item in enumerate(items, 1):
for number, source in enumerate(item['production']['sources'], 1):
row = rows.get(str(source['upload_id']))
if not row or row['name'].lower().endswith('.pdf'):
continue
size = image_size(files.head(row))
if not size or not all(size):
continue
width_px, height_px = size
if source.get('rotation_degrees') in (90, 270):
width_px, height_px = height_px, width_px
# A ready sheet's empty strips were cut from its length: the file
# is the length plus both strips (app/core/models.py).
length = (float(source['length_cm']) + float(source.get('trim_top_cm') or 0)
+ float(source.get('trim_bottom_cm') or 0))
drift = abs((width_px / height_px) / (float(source['width_cm']) / length) - 1)
if drift > ASPECT_TOLERANCE:
return (f'Item {index}: o arquivo {number} foi montado com {source["width_cm"]} × '
f'{source["length_cm"]} cm, que não são as proporções dele. Monte o pedido de novo.')
return None
def mismatch(files, items, rows):
"""Why a cart's grades cannot be approved at checkout, or None."""
for item in items:

View File

@@ -29,6 +29,7 @@ def triggered(rules: dict, items, treatment_offered: bool) -> dict:
def treatment_message(grade: int) -> str:
"""The refusal the customer sees when Ajuste Fino is required."""
return (f'Sua arte tem nota {grade}: para imprimir com qualidade, o Ajuste Fino '
"""The refusal the customer sees when Ajuste Fino is required. The grade
stays on the Kanban: the customer never sees the number (Rodada 5, D6)."""
return ('Sua arte está abaixo da resolução mínima, então o Ajuste Fino '
'é obrigatório neste pedido.')

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
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;
the order's own file stays in its stage folder. A film over 15 m is several
parts (item 13): all on the same machine, in order. A machine's folder holds
the order's own file stays in its stage folder. A film longer than a part
(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
since 2026-11-17); the next is written when Flexi takes one.
@@ -119,12 +119,12 @@ def claim(c, user):
they entered it, until the machine has its places' worth in its folder."""
c.execute('''UPDATE dtf_local.hot_parts SET state='queued', claimed_at=NULL, claimed_by=NULL
WHERE state='claimed' AND claimed_at < now() - %s''', (CLAIM_TIMEOUT,))
rows = c.execute('''SELECT h.*, o.machine_id, o.contraction, o.snapshot, m.name AS machine_name, m.places,
rows = c.execute('''SELECT h.*, o.machine_id, o.contraction, o.snapshot, COALESCE(m.folder, m.name) AS machine_folder, m.places,
(SELECT max(v.id) FROM dtf_local.movements v WHERE v.order_id=o.id AND v.to_state='imp') AS entered
FROM dtf_local.hot_parts h JOIN dtf_local.orders o ON o.id=h.order_id
JOIN dtf_local.machines m ON m.id=o.machine_id
WHERE h.state IN ('queued','claimed','written') AND o.state='imp' AND o.cancelled_at IS NULL
ORDER BY m.name, entered, h.order_id, h.seq FOR UPDATE OF h''').fetchall()
ORDER BY m.created_at, m.id, entered, h.order_id, h.seq FOR UPDATE OF h''').fetchall()
due, busy, blocked = [], {}, set()
for row in rows:
machine = row['machine_id']
@@ -139,7 +139,9 @@ def claim(c, user):
if busy.get(machine, 0) >= row['places'] or not cls:
blocked.add(order)
continue
folder = f"{row['machine_name']}/{cls}"
# The machine's folder, fixed at its creation: a renamed machine keeps
# the path FlexiPRINT watches.
folder = f"{row['machine_folder']}/{cls}"
c.execute('''UPDATE dtf_local.hot_parts SET state='claimed', claimed_at=now(), claimed_by=%s, folder=%s
WHERE id=%s''', (user, folder, row['id']))
busy[machine] = busy.get(machine, 0) + 1

View File

@@ -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,
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 decimal import Decimal
@@ -66,30 +67,48 @@ NOT_UNDONE = """NOT EXISTS (SELECT 1 FROM dtf_local.movements u WHERE u.order_id
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):
"""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 FROM dtf_local.movements m
rows = c.execute(f'''SELECT o.snapshot, m.items, {PROOF_WINDOWS} 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 AND {NOT_UNDONE}
AND (%s::timestamptz IS NULL OR m.created_at > %s::timestamptz)''',
(machine_id, since, since)).fetchall()
total = 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
return sum((film_metres(row['snapshot'], row.get('items'), row.get('windows')) for row in rows), Decimal(0))
def _last_entry(c, machine_id, kind, item):
@@ -186,7 +205,7 @@ def alerts(c, machine_id):
'snoozable': bool, 'blocking': bool}. blocking is False when it was
postponed this cycle and no card was pulled on the machine since.
Texts, with metres in one decimal and a comma:
clean "<máquina>: 10,4 m desde a última limpeza — limpe antes do próximo arquivo"
clean "<máquina>: 10,4 m desde a última limpeza: limpe antes do próximo arquivo"
align "<máquina>: 19,8 m desde a troca de filme — alinhe a cabeça antes do próximo"
supply "<label minúsculo> da <máquina> deve acabar em ~3 m" (e.g. "tinta branca da máquina2 deve acabar em ~3,0 m")
"""
@@ -217,11 +236,11 @@ def alerts(c, machine_id):
if counts['clean']['metres'] >= CLEAN_EVERY_METRES:
due('clean', f"{name}: {one_decimal(counts['clean']['metres'])} m desde a última limpeza "
'— limpe antes do próximo arquivo', counts['clean']['since'])
': limpe antes do próximo arquivo', counts['clean']['since'])
if (counts['film']['since'] is not None and not counts['film']['aligned']
and counts['film']['metres'] >= ALIGN_AFTER_FILM_METRES):
due('align', f"{name}: {one_decimal(counts['film']['metres'])} m desde a troca de filme "
'— alinhe a cabeça antes do próximo', counts['film']['since'])
': alinhe a cabeça antes do próximo', counts['film']['since'])
for item, value in supplies.items():
if not supply_low(value):
continue

View File

@@ -5,7 +5,7 @@ what the board already knows it printed, per machine and calendar month
(America/Sao_Paulo):
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
orders printing together count once); metres per hour = printed
/ 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 zoneinfo import ZoneInfo
from .machine_log import NOT_UNDONE, SUPPLIES
from .machine_log import NOT_UNDONE, PROOF_WINDOWS, SUPPLIES, film_metres
SAO_PAULO = ZoneInfo('America/Sao_Paulo')
# 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):
"""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."""
return c.execute(f'''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
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()
def _film(snapshot, items=None):
"""The film printed for one order (machine_log's rule), as Decimal; on a
reprint only the `items` that went again."""
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 _film(row):
"""The film one printed order took (machine_log's rule), as Decimal."""
return film_metres(row['snapshot'], row.get('items'), row.get('windows'))
def _sold(row):
@@ -157,7 +142,7 @@ def _sold(row):
def printed_between(c, machine_id, start, end):
"""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))
@@ -189,7 +174,7 @@ def machine_month(c, machine, start, end):
'contribution_cents'}. `machine` is its row from dtf_local.machines."""
mid = machine['id']
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)
ids = [row['id'] for row in rows]
spans = c.execute('''WITH events AS (

View File

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

View File

@@ -84,10 +84,10 @@ def order_paid(c, order, origin):
number, link = order['number'], f"{origin}/conta/pedidos?order={order['id']}"
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
f'Seu pagamento foi aprovado e o pedido #{number} já está com a nossa equipe. '
'Agora a gente confere a arte e coloca na fila de impressão.', '',
'Conferimos a arte e colocamos na fila de impressão.', '',
*(f'{key}: {value}' for key, value in rows), '',
f'Acompanhe cada etapa em Minha conta: {link}', '',
'Ainda não tem conta? Crie com este e-mail e o mesmo CPF/CNPJ do pedido: ele aparece lá na hora.'])
'Se ainda não tem conta, crie com este e-mail e o mesmo CPF/CNPJ do pedido: ele aparece lá na hora.'])
return queue(c, 'order', customer['mail'], f'Recebemos seu pedido #{number} · DTF Dropstar', text,
mail_html.order_paid(customer.get('name'), number, rows, link))
@@ -108,14 +108,14 @@ def quote_expired(c, quote, origin):
link = f'{origin}/'
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
'Seu pedido não foi pago em 24 horas e expirou. Os arquivos que você enviou foram apagados.', '',
f'Quando quiser, é só montar de novo no site: {link}'])
f'Para pedir de novo, monte no site: {link}'])
html = mail_html.layout('Seu pedido não foi pago em 24 horas e expirou.', 'Seu pedido', [
mail_html.pill('Pedido expirado', 'info'),
mail_html.title('Seu pedido expirou'),
mail_html.para(f'{mail_html.greeting(customer.get("name"))} Seu pedido não foi pago em 24 horas e '
'expirou. Os arquivos que você enviou foram apagados.'),
mail_html.button('Montar de novo', link),
mail_html.small(f'Quando quiser, é só montar de novo no site: {link}'),
mail_html.small(f'Para pedir de novo, monte no site: {link}'),
])
return queue(c, 'notice', customer['mail'], 'Seu pedido expirou · DTF Dropstar', text, html)

View File

@@ -152,12 +152,11 @@ def reset(name, link, minutes):
hours = 'por 1 hora' if minutes == 60 else f'por {minutes} minutos'
return layout('Clique no botão para criar uma nova senha.', 'Sua conta', [
title('Crie uma nova senha'),
para(f'{greeting(name)} Recebemos um pedido para criar uma nova senha na sua conta. '
'É só clicar no botão abaixo.'),
para(f'{greeting(name)} Recebemos um pedido de nova senha para a sua conta.'),
button('Criar nova senha', link),
small(f'O link vale {hours} e funciona uma vez só. Se não foi você, ignore este e-mail: '
'sua senha continua a mesma.'),
small('O botão não abriu? Copie este endereço no navegador: ',
small('Se o botão não abrir, copie este endereço no navegador: ',
f'<br><a href="{escape(link, quote=True)}" style="color:{DARK_ORANGE};word-break:break-all">'
f'{escape(link)}</a>'),
])
@@ -167,7 +166,7 @@ def account_exists(name, login_link):
return layout('Este e-mail já tem conta no DTF Dropstar.', 'Sua conta', [
title('Este e-mail já tem uma conta'),
para(f'{greeting(name)} Alguém tentou criar uma conta no DTF Dropstar com este e-mail, mas ele já está '
'cadastrado. Para ver seus pedidos, é só entrar.'),
'cadastrado. Entre para ver seus pedidos.'),
button('Entrar na minha conta', login_link),
callout('Esqueceu a senha?', 'Na página de entrada, clique em “Esqueci minha senha” e enviamos um link '
'para criar outra.'),
@@ -180,7 +179,7 @@ def email_changed(name, old, new):
title('O e-mail da sua conta foi trocado'),
para(f'{greeting(name)} A partir de agora, sua conta no DTF Dropstar entra com outro e-mail:'),
facts([('Antes', old), ('Agora', new)]),
callout('Não foi você?', 'Fale com a Dropstar agora pelo WhatsApp: a gente ajuda a recuperar a conta.',
callout('Não foi você?', 'Fale com a Dropstar pelo WhatsApp para recuperar a conta.',
warn=True),
button('Falar no WhatsApp', WHATSAPP, dark=True),
])
@@ -190,14 +189,14 @@ def order_paid(name, number, rows, link):
return layout(f'Pagamento aprovado. O pedido #{number} já está com a nossa equipe.', 'Seu pedido', [
pill('Pagamento aprovado'),
title(f'Recebemos seu pedido #{number}'),
para(f'{greeting(name)} Seu pagamento foi aprovado e o pedido já está com a nossa equipe. Agora a gente '
'confere a arte e coloca na fila de impressão.'),
para(f'{greeting(name)} Seu pagamento foi aprovado e o pedido já está com a nossa equipe. '
'Conferimos a arte e colocamos na fila de impressão.'),
facts(rows),
steps([('Pagamento aprovado', 'Pedido recebido pela equipe', True),
('Arte conferida', 'A equipe confere se está tudo certo para imprimir', False),
('Impressão', 'Seu filme entra na máquina', False),
('Pronto', 'Você recebe o aviso pelo WhatsApp', False)]),
button('Ver meu pedido', link),
small('Acompanhe cada etapa em Minha conta. Ainda não tem conta? Crie com este e-mail e o mesmo CPF/CNPJ '
'do pedido: ele aparece lá na hora.'),
small('Acompanhe cada etapa em Minha conta. Se ainda não tem conta, crie com este e-mail e o mesmo '
'CPF/CNPJ do pedido: ele aparece lá na hora.'),
])

View File

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

View File

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

View File

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

View File

@@ -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.
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
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
@@ -336,11 +336,22 @@ def file_prefix(number, item_index, generation=1):
return f'DTF-{number}{version}-item-{item_index + 1}'
def _footer_name(name):
"""A customer name for the footer: tidy, printable in cp1252 and at most
24 characters, the last one an ellipsis when cut."""
cleaned = ' '.join(str(name or '').split())
cleaned = cleaned.encode('cp1252', 'ignore').decode('cp1252')
cleaned = ' '.join(cleaned.split())
if len(cleaned) > 24:
cleaned = cleaned[:23] + '…'
return cleaned
def footer(job, item):
"""The print file's footer line: DROPSTAR · Pedido DTF-123 · Item 1/2 ·
21/10/2026 · 0,90 m, and · ESPELHADO when the artwork is mirrored. The
order is named by its Kanban number, which Tiny keeps; the length is the
one billed."""
"""The print file's footer line: DROPSTAR · Pedido DTF-123 · <customer> ·
Item 1/2 · 21/10/2026 · 0,90 m · <pieces>, and · ESPELHADO when the
artwork is mirrored. The order is named by its Kanban number, which Tiny
keeps; the length is the one billed."""
count = len(job['snapshot']['items'])
day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y')
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',')
@@ -348,11 +359,25 @@ def footer(job, item):
if proof_of:
return ' · '.join(['DROPSTAR', f'PROVA do #{proof_of}',
f'Classe {item.get("stroke_class") or "C3"}', day])
fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}',
f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m']
fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}']
customer = _footer_name((job['snapshot'].get('customer') or {}).get('name'))
if customer:
fields.append(customer)
fields += [f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m']
production = item.get('production') or {}
sources = production.get('sources') or []
placements = production.get('placements') or []
if any(source.get('kind') == 'artwork' for source in sources):
pieces = len(placements)
if pieces:
fields.append(f'{pieces} peça' if pieces == 1 else f'{pieces} peças')
elif any(source.get('kind') == 'sheet' for source in sources):
copies = sum(source.get('copies') or 0 for source in sources)
if copies > 1:
fields.append(f'{copies} cópias')
# A mirrored artwork (UV only) is named on the sheet, for the room to see
# before printing (Dropstar, 2026-10-23).
if any(source.get('mirrored') for source in item['production']['sources']):
if any(source.get('mirrored') for source in sources):
fields.append('ESPELHADO')
return ' · '.join(fields)

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
once, and copied into every band it crosses.
A layout longer than 15 m leaves as parts of up to 15 m (Dropstar,
2026-10-30), DTF-7-item-1-p3.png, each with its footer saying which part it
A layout longer than a part leaves as parts of up to PART_CM, 10 m since
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
copies, or else in a clear band of its own pixels, and through the artwork
only when it has none (#136).
@@ -41,11 +42,14 @@ from .printtiles import Pyramid
DPI = 300
PX_PER_CM = DPI / 2.54
# Parts of up to 15 m, 6732 x 177165 px (Dropstar, 2026-10-30).
PART_CM = Decimal(os.environ.get('PRINT_PART_CM', '1500'))
# Parts of up to 10 m (Marcus, 2026-11-18): a 15 m part, 6732 x 177165 px, is
# 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.
CUT_SEARCH_CM = Decimal('200')
BAND_ROWS = 512
# A pixel above this alpha takes ink (web/site-sheet.js ALFA_TINTA).
INK_ALPHA = 10
# Above this a source is read band by band instead of decoded whole.
STREAM_ABOVE_PIXELS = 40_000_000
FOOTER_TEXT_CM = 1.1
@@ -266,9 +270,44 @@ class Source:
top, bottom = round(height * top_cm / full_cm), round(height * bottom_cm / full_cm)
if top + bottom >= height:
raise Unsupported(f'"{self.name}": o corte das faixas vazias tiraria o arquivo inteiro')
self._require_clear(top, bottom)
self.cut = (top, bottom)
self.size = (width, height - top - bottom)
def _require_clear(self, top, bottom):
"""The strips the Site measured as empty must be: cut on a measure the
file does not bear out, artwork would leave the print unseen. A pixel
takes ink above INK_ALPHA, as the Site counts it. Not clear, or too
big to read here: the item goes to hand preparation, with the reason."""
width, height = self.size
where = lambda first: 'do começo' if first else 'do fim'
def check(band, offset):
for start, stop, first in ((0, top, True), (height - bottom, height, False)):
a, b = max(start, offset), min(stop, offset + band.height)
if a < b and rgba(band.crop((0, a - offset, band.width, b - offset))).getchannel('A').getextrema()[1] > INK_ALPHA:
raise Unsupported(f'"{self.name}": a faixa que o site cortou {where(first)} do arquivo tem arte. '
'Confira o arquivo e prepare a folha à mão')
if self.streamable:
reader = PngRows(self.path)
try:
done = 0
# Read in order to the end of the bottom strip (or of the top one).
while done < (height if bottom else top):
band = reader.band(BAND_ROWS)
if done < top or done + band.height > height - bottom:
check(band, done)
done += band.height
finally:
reader.close()
return
if width * height > MAX_DECODED_PIXELS:
raise Unsupported(f'"{self.name}" é grande demais para conferir as faixas cortadas; prepare a folha à mão')
with Image.open(self.path) as image:
image = ImageOps.exif_transpose(image) if self.orientation != 1 else image
check(image, 0)
def decoded(self, width, height):
"""The whole file at (width, height) px, upright, RGBA."""
if self.pdf:

View File

@@ -1,8 +1,9 @@
"""The print proof (Dropstar, 2026-10-21).
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
the part with the thinnest lines, a piece of each different artwork, at most
without stopping the order. Dropstar's current rule: 15 cm from the part
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
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
@@ -37,12 +38,14 @@ def needs_proof(snapshot):
#
# 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
# 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
# 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
# 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.
# The finest stroke's window; with the colour samples the sheet reaches
# app/printpng.py PROOF_MAX_CM.
PROOF_SHEET_CM = Decimal('15')
# Three proofs at most per order, one per item (Dropstar, 2026-10-23).
MAX_PROOFS = 3

View File

@@ -103,6 +103,27 @@ def report(order, uploads):
lines.append(f'{lead}{len(placements)} arte{"s" if len(placements) != 1 else ""}, '
f'{rotated} girada{"s" if rotated != 1 else ""} (couberam melhor), '
f'altura {_cm(production.get("height_cm"))} cm')
# The size the PNG said it had (item A1, round 5): whether the
# customer kept it or changed it.
for k, source in enumerate(production.get('sources') or []):
saved = source.get('saved_width_cm')
if not saved:
continue
width = Decimal(str(source.get('width_cm')))
length = Decimal(str(source.get('length_cm')))
# Turned 90°, the art's own width runs along the film.
if source.get('rotation_degrees') == 90:
width, length = length, width
saved_w = Decimal(str(saved))
altura = saved_w * length / width if width else Decimal(0)
dpi = source.get('saved_dpi')
if abs(width - saved_w) < Decimal('0.05'):
lines.append(f'{lead}Arte {k + 1}: tamanho lido do arquivo '
f'{_cm(saved_w)} × {_cm(altura)} cm ({dpi} DPI), mantido')
else:
lines.append(f'{lead}Arte {k + 1}: tamanho lido do arquivo '
f'{_cm(saved_w)} × {_cm(altura)} cm ({dpi} DPI), '
f'alterado pelo cliente para {_cm(width)} cm')
# The empty strips the Site cut from a ready sheet (Marcus, 2026-11-18).
trimmed = sum(Decimal(str(s.get('trim_top_cm') or 0)) + Decimal(str(s.get('trim_bottom_cm') or 0))
for s in production.get('sources') or [])
@@ -114,9 +135,9 @@ def report(order, uploads):
if item.get('stroke_px') and item.get('stroke_class'):
lines.append(f'{lead}Menor traço {item["stroke_px"]} px → {item["stroke_class"]}')
if item.get('stroke_choice') == 'client_c3':
lines.append(f'{lead}Aviso de traço fino disparou — cliente escolheu proteger as áreas chapadas (C3)')
lines.append(f'{lead}Aviso de traço fino: cliente escolheu proteger as áreas chapadas (C3)')
elif item.get('stroke_choice') == 'measured':
lines.append(f'{lead}Aviso de traço fino disparou — cliente escolheu imprimir em C1')
lines.append(f'{lead}Aviso de traço fino: cliente escolheu imprimir em C1')
else:
lines.append(f'{lead}Aviso de traço fino não disparou')
if row:

View File

@@ -124,46 +124,64 @@ def check_large(head, row):
return 'rejected', 'O conteúdo do arquivo não corresponde ao formato do nome'
# When the scan of the file now in hand began (None between files): the
# worker's health reports a scan held on one file for longer than
# SCAN_STUCK_SECONDS, since every upload waits behind it.
busy_since=None
SCAN_STUCK_SECONDS=900
def stuck():
"""Whether the scan has been on the same file for SCAN_STUCK_SECONDS."""
return busy_since is not None and time.monotonic()-busy_since>SCAN_STUCK_SECONDS
def scan_one(storage, scanner=None):
global busy_since
scanner=scanner or ClamAV()
with connect() as c:
row=c.execute('''SELECT * FROM dtf_local.uploads WHERE complete AND purged_at IS NULL
AND expires_at>now() AND scan_state IN ('pending','error') AND scan_after<=now()
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1''').fetchone()
if not row:return False
name=row['name']
busy_since=time.monotonic()
try:
# Every later decision reads the stored name (the manual charge,
# the JPG refusal, the grade, the print file, the folders), so the
# name is made to say what the file is (D-13).
head=head_of(storage,row)
name=real_name(name,head)
if row['size'] > scan_limit_bytes():
state,reason=check_large(head,row)
else:
stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body']
try:state,reason=scanner.scan(stream,row['size'])
finally:stream.close()
except Exception:
state,reason='error','Malware scanner unavailable; file remains blocked'
# A PDF's resolution is worked out here, once, so checkout never reads
# it (Critical Corrections 2). A failure leaves it for the fallback.
checked,pdf_dpi_value=False,None
if state=='clean' and name.lower().endswith('.pdf'):
try:
pdf_dpi_value=stored_pdf_dpi(storage,row)
checked=True
except Exception:
logging.exception('Could not work out the PDF DPI of upload %s',row['id'])
c.execute("""UPDATE dtf_local.uploads SET name=%s,scan_state=%s,scan_reason=%s,scanned_at=now(),
scan_after=now()+interval '1 minute',
pdf_checked=CASE WHEN %s THEN true ELSE pdf_checked END,
pdf_dpi=CASE WHEN %s THEN %s ELSE pdf_dpi END,
expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END
WHERE id=%s""",(name,state,reason,checked,checked,pdf_dpi_value,state,row['id']))
audit('artwork_scan', upload=str(row['id']), result=state, c=c)
_scan_row(c, storage, scanner, row)
finally:
busy_since=None
return True
def _scan_row(c, storage, scanner, row):
name=row['name']
try:
# Every later decision reads the stored name (the manual charge,
# the JPG refusal, the grade, the print file, the folders), so the
# name is made to say what the file is (D-13).
head=head_of(storage,row)
name=real_name(name,head)
if row['size'] > scan_limit_bytes():
state,reason=check_large(head,row)
else:
stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body']
try:state,reason=scanner.scan(stream,row['size'])
finally:stream.close()
except Exception:
state,reason='error','Malware scanner unavailable; file remains blocked'
# A PDF's resolution is worked out here, once, so checkout never reads
# it (Critical Corrections 2). A failure leaves it for the fallback.
checked,pdf_dpi_value=False,None
if state=='clean' and name.lower().endswith('.pdf'):
try:
pdf_dpi_value=stored_pdf_dpi(storage,row)
checked=True
except Exception:
logging.exception('Could not work out the PDF DPI of upload %s',row['id'])
c.execute("""UPDATE dtf_local.uploads SET name=%s,scan_state=%s,scan_reason=%s,scanned_at=now(),
scan_after=now()+interval '1 minute',
pdf_checked=CASE WHEN %s THEN true ELSE pdf_checked END,
pdf_dpi=CASE WHEN %s THEN %s ELSE pdf_dpi END,
expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END
WHERE id=%s""",(name,state,reason,checked,checked,pdf_dpi_value,state,row['id']))
audit('artwork_scan', upload=str(row['id']), result=state, c=c)
def scan_loop(storage):
while True:
try:

View File

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

View File

@@ -8,7 +8,7 @@ from http.server import BaseHTTPRequestHandler, HTTPServer
import psycopg
from botocore.exceptions import ClientError
from psycopg.types.json import Jsonb
from . import mail, observability, unpaid
from . import mail, observability, scanning, unpaid
from .adapters import FakeTiny, LocalS3Storage, require_runtime
from .core.secrets import load as load_secret_files
from .core.db import connect
@@ -17,12 +17,37 @@ from .scanning import ClamAV, scan_loop
load_secret_files()
require_runtime()
adapters = {'tiny': FakeTiny()}
# Not yet confirmed against the client's account; see app/tiny.py.
if os.environ.get('TINY_ADAPTER') == 'tiny':
from .tiny import TinyOrders
from .cnpj import company
adapters['tiny'] = TinyOrders(names=company)
# Production without the real Tiny (TINY_ADAPTER missing from the stack):
# the sends wait and Sentry is told, instead of the simulator marking real
# orders delivered with made-up receipts that had to be queued again by hand.
HELD = 'Tiny desligado em produção (TINY_ADAPTER não é tiny): o envio espera'
class HeldTiny:
def deliver(self, event_key, payload):
raise RuntimeError(HELD)
def tiny_adapter(adapter=None, environment=None):
"""The Tiny the outbox delivers to: the real one when configured; in
production otherwise none (HeldTiny); elsewhere the simulator."""
adapter = os.environ.get('TINY_ADAPTER') if adapter is None else adapter
environment = os.environ.get('APP_ENV', 'local') if environment is None else environment
if adapter == 'tiny':
from .tiny import TinyOrders
from .cnpj import company
return TinyOrders(names=company)
return HeldTiny() if environment == 'production' else FakeTiny()
adapters = {'tiny': tiny_adapter()}
def release_held(c):
"""With the real Tiny back, the sends held meanwhile go at once instead
of after their back-off."""
return c.execute('''UPDATE dtf_local.outbox SET available_at=now() WHERE provider='tiny'
AND delivered_at IS NULL AND last_error=%s''', (HELD,)).rowcount
last_tick = 0.0
last_cleanup = 0.0
last_reconcile = 0.0
@@ -180,13 +205,25 @@ def loop():
delay = 1
time.sleep(1)
scan_stuck_reported = False
class Health(BaseHTTPRequestHandler):
def do_GET(self):
global scan_stuck_reported
scanner = False
try:
scanner = bool(scan_thread and scan_thread.is_alive() and ClamAV().ping())
except Exception:
pass
# Alive but held on one file: every upload waits behind it.
if scanning.stuck():
scanner = False
if not scan_stuck_reported:
scan_stuck_reported = True
logging.error('The upload scan has been on one file for over %s min: every upload waits',
scanning.SCAN_STUCK_SECONDS // 60)
else:
scan_stuck_reported = False
renderer = bool(render_thread and render_thread.is_alive())
healthy = time.monotonic()-last_tick < 15 and scanner and renderer
self.send_response(200 if self.path == '/health' and healthy else 503)
@@ -199,6 +236,14 @@ class Health(BaseHTTPRequestHandler):
if __name__ == '__main__':
observability.init('worker')
if isinstance(adapters['tiny'], HeldTiny):
logging.error('Worker started in production without the real Tiny: Tiny sends are held')
elif not isinstance(adapters['tiny'], FakeTiny):
try:
with connect() as c:
release_held(c)
except Exception:
logging.exception('Could not release the Tiny sends held while Tiny was off')
scan_thread = threading.Thread(target=scan_loop,args=(storage,),daemon=True)
scan_thread.start()
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)

View File

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

View File

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

View File

@@ -219,7 +219,7 @@ try{
// JPG has no transparency: refused in loose artwork as in a sheet (Dropstar,
// 2026-10-23), with the reason, before anything is read.
await evaluate(`sel([new File(['x'],'arte.jpg',{type:'image/jpeg'})])`);
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('JPG não dá para enviar')`),true);
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('JPG não entra')`),true);
// The content decides, not the name (D-13): a JPG called ".png" is refused as a JPG.
await evaluate(`sel([new File([new Uint8Array([0xFF,0xD8,0xFF,0xE0])],'disfarce.png',{type:'image/png'})])`);
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('disfarce.png é JPG')`),true);
@@ -383,7 +383,7 @@ try{
// A ready sheet now offers the same acceptance as loose art (Dropstar,
// 2026-11-05): the dots may be part of the art; the customer can take them.
assert.deepEqual(await evaluate(`({box:!!document.querySelector('[data-residuo]'),
text:$('lista').textContent.includes('Li e concordo'),stopped:itemAtual===null})`),{box:true,text:true,stopped:true});
text:$('lista').textContent.includes('Quero imprimir assim'),stopped:itemAtual===null})`),{box:true,text:true,stopped:true});
await evaluate(`(()=>{const el=document.querySelector('[data-residuo]');el.checked=true;
el.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await waitFor(()=>evaluate('itemAtual!==null'),'accepted residue lets the sheet through');

View File

@@ -91,7 +91,7 @@ try{
const itemCents=Math.round(1.1*(1990+extraCents));
const total=Math.round(itemCents)/100;
await waitFor(()=>site.eval(`Math.abs(itemAtual.total-${total})<0.005`),'manual-file price');
assert.equal(await site.eval(`$('carrLin').textContent.includes('Arquivo aberto na mão')`),extraCents>0);
assert.equal(await site.eval(`$('carrLin').textContent.includes('Abertura manual do arquivo')`),extraCents>0);
await site.fill('#fNome','Cliente Teste');
await site.fill('#fCnpj','11222333000181');
await site.fill('#fZap','11999999999');

View File

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

View File

@@ -44,11 +44,11 @@ def run():
assert rules['treatment_offered'] is True, rules
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-GRADE-{tag}.png')
item = {**item_spec('uv', '1', 50, upload_id),
item = {**item_spec('uv', '1', 50, upload_id, aspect=2),
'quality_status': 'warning', 'quality_acknowledged': True}
refused = client.call('/quotes', quote_body(item, False, mail), expected=422)
assert refused['detail'] == ('Sua arte tem nota 50: para imprimir com qualidade, '
assert refused['detail'] == ('Sua arte está abaixo da resolução mínima, então '
'o Ajuste Fino é obrigatório neste pedido.'), refused
made = client.call('/quotes', quote_body(item, True, mail))

View File

@@ -62,4 +62,27 @@ window.dtfObservability.apiError('/board', 503, 'O sistema está reiniciando.');
window.dtfObservability.uiError('O sistema está reiniciando.', 'kanban');
assert.equal(captured, null, 'a skipped restart 503 stays skipped');
// A refusal the server explains (a 4xx with a sentence) is no bug: on the
// Kanban a warning, on the Site nothing; a field list or a 5xx is an error
// (2026-11-30).
const refused = (app, status, detail) => {
// A fresh copy per app: a page starts Sentry once, for its own app.
vm.runInThisContext(readFileSync('web/observability.js', 'utf8'));
window.dtfObservability.start('https://key@o1.ingest.sentry.io/1', app);
captured = null;
window.dtfObservability.apiError('/orders/1/move', status, 'Puxe o pedido na mesma máquina.', detail);
return captured;
};
assert.equal(refused('kanban', 409, 'Puxe o pedido na mesma máquina.').options.level, 'warning');
assert.equal(refused('kanban', 409, 'Puxe o pedido na mesma máquina.').options.tags.recusa, 'sim');
assert.equal(refused('site', 409, 'Cupom não encontrado.'), null, 'a refusal on the Site is not sent');
assert.equal(refused('site', 422, [{loc: ['body', 'items'], msg: 'bad'}]).options.level, 'error');
assert.equal(refused('site', 500, 'Internal Server Error').options.level, 'error');
assert.equal(refused('kanban', 422, [{loc: ['body'], msg: 'bad'}]).options.level, 'error');
// Shown in red after it, the refusal is not sent again as a page error.
refused('site', 409, 'Cupom não encontrado.');
captured = null;
window.dtfObservability.uiError('Puxe o pedido na mesma máquina.', 'site');
assert.equal(captured, null, 'a refusal shown in red is not sent as an error');
console.log('observability web checks passed');

View File

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

View File

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

View File

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

View File

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

View File

@@ -40,12 +40,13 @@ def quote(client, item, mail, expected=200):
def arts_item(upload_id, arts):
"""One loose-art item with `arts` sources of 10 x 10 cm, one metre long."""
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 10,
"""One loose-art item with `arts` sources of 10 x 5 cm (artwork() is 2:1),
one every 10 cm."""
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 5,
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
'measurement': 'customer'} for _ in range(arts)]
placements = [{'source_index': index, 'copy_index': 0, 'x_cm': 0, 'y_cm': index * 10,
'width_cm': 10, 'length_cm': 10, 'rotation_degrees': 0, 'mirrored': False}
'width_cm': 10, 'length_cm': 5, 'rotation_degrees': 0, 'mirrored': False}
for index in range(arts)]
return {'mode': 'avulsa', 'metres': '1', 'grade': 90, 'uploads': [upload_id] * arts,
'production': {'version': 3, 'film_width_cm': 57, 'height_cm': arts * 10,
@@ -76,7 +77,7 @@ def run():
assert premium_entry['title'] == 'Têxtil Premium · 8 passadas', premium_entry
assert client.call('/session')['products'][PREMIUM]['enabled'] is False
premium_item = {**item_spec(PREMIUM, '1', 0, upload_bytes(
client, premium_sheet(), name='LOCAL-SITE-PREMIUM.png')),
client, premium_sheet(), name='LOCAL-SITE-PREMIUM.png'), aspect=3),
'quality_status': 'warning', 'quality_acknowledged': True}
refused = quote(client, premium_item, mail, expected=422)
assert refused['detail'] == 'Este produto não está à venda agora.', refused
@@ -188,7 +189,7 @@ def run():
manager.call(f'/operator/site/products/{UV}', {'enabled': True})
uid = upload_bytes(client, artwork(), name='LOCAL-SITE-ADMIN.png')
item = {**item_spec('uv', '1', 0, uid), 'quality_status': 'warning', 'quality_acknowledged': True}
item = {**item_spec('uv', '1', 0, uid, aspect=2), 'quality_status': 'warning', 'quality_acknowledged': True}
before = client.call('/session')['products'][UV]['unit_cents']
# Switched off: the Site sees it off and the server refuses a new quote.

View File

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

View File

@@ -165,8 +165,10 @@ class CartPricingCharacterizationTest(unittest.TestCase):
split = priced('split-under-one-metre')
self.assertEqual([(p['billed_metres'], p['total_cents']) for p in split],
[('0.8', 1752), ('0.2', 438)])
# A float's noise past 2,80 m is inside the 8 mm grace (Marcus,
# 2026-11-27): billed 2,80 m at the band from 2,8 m, no longer 2,90 m.
floating = priced('band-floating-metres')[0]
self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.9', 24650))
self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.8', 23800))
def test_ajuste_fino_is_per_art_with_the_band(self):
# Front 1a: 1 to 9 arts at R$ 9,90, from 10 at R$ 6,90, all arts charged

View File

@@ -105,7 +105,7 @@ class GradeCheckTests(unittest.TestCase):
storage = CountingStorage({'k.pdf': b'%PDF-1.4 test', 'k.png': encoded('PNG', (100, 50))})
files = grade_check.Files(storage)
pdf_row = {'object_key': 'k.pdf', 'size': 15, 'name': 'a.pdf'}
with mock.patch.object(grade_check, 'pdf_dpi', return_value=300):
with mock.patch.object(grade_check, 'bounded_pdf_dpi', return_value=300):
self.assertEqual(files.pdf_dpi(pdf_row), 300)
self.assertEqual(files.pdf_dpi(pdf_row), 300)
self.assertEqual(storage.downloads, 1)
@@ -158,5 +158,89 @@ class GradeCheckTests(unittest.TestCase):
self.assertIn('confirme a ressalva', issue(199.4))
def nested_forms_pdf(path, fanout=10, levels=8):
"""A 2 KB PDF whose page draws form F0 ten times, F0 draws F1 ten times,
eight deep: 10^8 draws for a reader that walks them."""
pdf = pikepdf.new()
pdf.add_blank_page(page_size=(200, 200))
forms = []
for level in reversed(range(levels)):
if forms:
content = b''.join(b'q /F%d Do Q\n' % (level + 1) for _ in range(fanout))
resources = pikepdf.Dictionary(XObject=pikepdf.Dictionary({'/F%d' % (level + 1): forms[0]}))
else:
content, resources = b'0 0 1 1 re f\n', pikepdf.Dictionary()
form = pikepdf.Stream(pdf, content)
form.Type, form.Subtype, form.BBox, form.Resources = (pikepdf.Name.XObject, pikepdf.Name.Form,
[0, 0, 1, 1], resources)
forms.insert(0, pdf.make_indirect(form))
page = pdf.pages[0]
page.obj.Resources = pikepdf.Dictionary(XObject=pikepdf.Dictionary({'/F0': forms[0]}))
page.obj.Contents = pdf.make_indirect(pikepdf.Stream(pdf, b''.join(b'q /F0 Do Q\n' for _ in range(fanout))))
pdf.save(path)
class HostilePdfTests(unittest.TestCase):
"""A tiny PDF must not hold the scanner's one thread (security review,
2026-11-27): it held it for hours, and every upload behind it."""
def test_nested_forms_end_unknown_in_seconds(self):
import time
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
nested_forms_pdf(handle.name)
start = time.monotonic()
self.assertIsNone(grade_check.pdf_dpi(handle.name))
self.assertLess(time.monotonic() - start, grade_check.PDF_MAX_SECONDS + 2)
start = time.monotonic()
self.assertIsNone(grade_check.bounded_pdf_dpi(handle.name))
self.assertLess(time.monotonic() - start, grade_check.PDF_MAX_SECONDS + 10)
def test_a_heavy_vector_page_is_still_read(self):
# Vector art has many paths and few draws: only draws are counted.
pdf = pikepdf.new()
pdf.add_blank_page(page_size=(200, 200))
pdf.pages[0].obj.Contents = pdf.make_indirect(pikepdf.Stream(pdf, b'0 0 1 1 re f\n' * 200000))
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
pdf.save(handle.name)
self.assertEqual(grade_check.pdf_dpi(handle.name), grade_check.PDF_VECTOR_DPI)
def test_a_scan_held_on_one_file_is_reported(self):
from app import scanning
import time
self.assertFalse(scanning.stuck())
with mock.patch.object(scanning, 'busy_since', time.monotonic() - scanning.SCAN_STUCK_SECONDS - 1):
self.assertTrue(scanning.stuck())
with mock.patch.object(scanning, 'busy_since', time.monotonic()):
self.assertFalse(scanning.stuck())
class ProportionTests(unittest.TestCase):
"""A file laid out at proportions it does not have is refused before
payment, not found at print time (a 5 m sheet sent as 10 cm)."""
def cart(self, length, rotation=0, top=0, bottom=0, name='sheet.png'):
source = {'upload_id': name, 'kind': 'sheet', 'width_cm': 57, 'length_cm': length,
'rotation_degrees': rotation, 'trim_top_cm': top, 'trim_bottom_cm': bottom}
return [{'production': {'sources': [source]}}], {name: {'name': name}}
def test_the_files_own_proportions_pass(self):
files = FakeFiles({'sheet.png': encoded('PNG', (570, 1000)), 'turned.png': encoded('PNG', (1000, 570))})
for args in ((100,), (90, 0, 4, 6)):
items, rows = self.cart(*args)
self.assertIsNone(grade_check.proportion_issue(files, items, rows), args)
items, rows = self.cart(100, 90, name='turned.png')
self.assertIsNone(grade_check.proportion_issue(files, items, rows))
def test_other_proportions_are_refused(self):
files = FakeFiles({'sheet.png': encoded('PNG', (570, 50000))})
items, rows = self.cart(10)
self.assertIn('não são as proporções', grade_check.proportion_issue(files, items, rows))
def test_a_pdf_is_left_to_the_print_file(self):
files = FakeFiles({})
items, rows = self.cart(10, name='sheet.pdf')
self.assertIsNone(grade_check.proportion_issue(files, items, rows))
if __name__ == '__main__':
unittest.main()

View File

@@ -34,7 +34,7 @@ class GradeRulesTest(unittest.TestCase):
def test_treatment_message(self):
self.assertEqual(
treatment_message(45),
'Sua arte tem nota 45: para imprimir com qualidade, o Ajuste Fino '
'Sua arte está abaixo da resolução mínima, então o Ajuste Fino '
'é obrigatório neste pedido.')

View File

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

View File

@@ -129,7 +129,7 @@ class PrintFileTests(unittest.TestCase):
job = {'snapshot': {'items': [spec, spec]}, 'number': 7, 'item_index': 1,
'ordered_at': datetime(2026, 10, 23, 15, 0, tzinfo=timezone.utc)}
line = footer(job, spec)
self.assertEqual(line, 'DROPSTAR · Pedido DTF-7 · Item 2/2 · 23/10/2026 · 1,00 m · ESPELHADO')
self.assertEqual(line, 'DROPSTAR · Pedido DTF-7 · Item 2/2 · 23/10/2026 · 1,00 m · 1 peça · ESPELHADO')
self.assertIn(b'/F1 31 Tf ( \xb7 ESPELHADO) Tj', footer_commands(line, (100, 80)))
# About 1 cm tall on the 57 cm film (Dropstar, 2026-10-28); on the 27 cm UV
# the line shrinks to fit the width instead of running off the film.
@@ -149,6 +149,35 @@ class PrintFileTests(unittest.TestCase):
self.assertEqual(file_prefix(130, 0, 2), 'DTF-130-v2-item-1')
self.assertEqual(file_prefix(130, 0, 1), 'DTF-130-item-1')
def test_the_footer_names_the_customer_and_the_pieces(self):
from datetime import datetime, timezone
from app.printjobs import footer
def line(name, spec, items=2):
customer = {} if name is None else {'name': name}
job = {'snapshot': {'items': [spec] * items, 'customer': customer},
'number': 7, 'item_index': 0,
'ordered_at': datetime(2026, 10, 21, 15, 0, tzinfo=timezone.utc)}
return footer(job, spec)
spec = item([placement(0, 0, 20, 10)], [source(20, 10)], 10)
start = 'DROPSTAR · Pedido DTF-7 · '
end = ' · Item 1/2 · 21/10/2026 · 1,00 m · 1 peça'
# An accent stays; an emoji does not; a long name is cut with an ellipsis.
self.assertEqual(line('Gráfica São José', spec), start + 'Gráfica São José' + end)
self.assertEqual(line('Loja 🌟 Azul', spec), start + 'Loja Azul' + end)
self.assertEqual(line('Gráfica São José do Vale do Paraíba', spec),
start + 'Gráfica São José do Val…' + end)
# Without a name the field is left out, with no stray separator.
self.assertEqual(line(None, spec), 'DROPSTAR · Pedido DTF-7' + end)
# A ready sheet counts its copies, and only says so above one.
sheet = item([placement(0, 0, 20, 10)], [{**source(20, 10), 'kind': 'sheet', 'copies': 3}], 10)
self.assertEqual(line('Cliente', sheet),
'DROPSTAR · Pedido DTF-7 · Cliente · Item 1/2 · 21/10/2026 · 1,00 m · 3 cópias')
single = item([placement(0, 0, 20, 10)], [{**source(20, 10), 'kind': 'sheet', 'copies': 1}], 10)
self.assertEqual(line('Cliente', single),
'DROPSTAR · Pedido DTF-7 · Cliente · Item 1/2 · 21/10/2026 · 1,00 m')
def test_jpeg_bytes_are_embedded_unchanged(self):
path = self.save(quadrants(), 'a.jpg', quality=90)
pdf, _ = self.render(item([placement(0, 0, 20, 10)], [source(20, 10)], 10), [path])

View File

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

View File

@@ -37,6 +37,30 @@ class PrumoReportTests(unittest.TestCase):
self.assertIn('Prumo levou 41 s', text)
self.assertNotIn('Prumo levou 341 s', text)
def test_saved_png_size_says_whether_the_customer_kept_it(self):
order = self.order()
item = order['snapshot']['items'][0]
item['production']['sources'] = [
{'width_cm': '28.0', 'length_cm': '35.2',
'saved_width_cm': '28.0', 'saved_dpi': 300},
{'width_cm': '20', 'length_cm': '25',
'saved_width_cm': '15', 'saved_dpi': 240},
]
text = '\n'.join(report(order, {'u1': {'name': 'arte.pdf'}}))
self.assertIn('Arte 1: tamanho lido do arquivo 28,0 × 35,2 cm (300 DPI), mantido', text)
self.assertIn('Arte 2: tamanho lido do arquivo 15,0 × 18,8 cm (240 DPI), '
'alterado pelo cliente para 20,0 cm', text)
# Turned 90°: the art's own width is the length along the film.
item['production']['sources'] = [
{'width_cm': '35.2', 'length_cm': '28.0', 'rotation_degrees': 90,
'saved_width_cm': '28.0', 'saved_dpi': 300}]
text = '\n'.join(report(order, {'u1': {'name': 'arte.pdf'}}))
self.assertIn('Arte 1: tamanho lido do arquivo 28,0 × 35,2 cm (300 DPI), mantido', text)
def test_without_a_saved_png_size_no_line_is_added(self):
text = '\n'.join(report(self.order(), {'u1': {'name': 'arte.pdf'}}))
self.assertNotIn('tamanho lido do arquivo', text)
def test_without_a_claim_time_the_generation_line_is_hidden(self):
order = self.order()
del order['print_files'][0]['claimed_at']

View File

@@ -7,7 +7,7 @@ import unittest
from decimal import Decimal
from app.hotfolder import reprint_default
from app.machine_stats import _film
from app.machine_log import film_metres
class ReprintTests(unittest.TestCase):
@@ -27,8 +27,24 @@ class ReprintTests(unittest.TestCase):
def test_the_machine_counts_only_the_items_printed_again(self):
snapshot = {'items': [{'billed_metres': '2.0'}, {'billed_metres': '3.5'}]}
self.assertEqual(_film(snapshot), Decimal('5.5'))
self.assertEqual(_film(snapshot, [1]), Decimal('3.5'))
self.assertEqual(film_metres(snapshot), Decimal('5.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__':

26
tests/test_saved_size.py Normal file
View File

@@ -0,0 +1,26 @@
"""The PNG's own size on an artwork source (item A1, round 5)."""
import unittest
from uuid import uuid4
try:
from pydantic import ValidationError
from app.core.models import ProductionSource
except ImportError:
# The validate job runs this file on the host, without the runtime image's
# dependencies; the runtime suites exercise the model there.
ProductionSource = ValidationError = None
class ProductionSourceSavedSizeTests(unittest.TestCase):
@unittest.skipUnless(ProductionSource, 'pydantic is only in the runtime image')
def test_saved_size_is_optional_and_saved_dpi_must_be_positive(self):
base = {'upload_id': str(uuid4()), 'kind': 'artwork', 'width_cm': '28.0',
'length_cm': '35.2', 'copies': 1, 'measurement': 'file'}
ProductionSource.model_validate(base)
ProductionSource.model_validate({**base, 'saved_width_cm': '28.0', 'saved_dpi': 300})
with self.assertRaises(ValidationError):
ProductionSource.model_validate({**base, 'saved_width_cm': '28.0', 'saved_dpi': 0})
if __name__ == '__main__':
unittest.main()

View File

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

View File

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

View File

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

View File

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

View File

@@ -7,6 +7,7 @@ Run against the local stack: python -m tests.upload_limits_test
import json
import os
import secrets
import time
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request
@@ -68,6 +69,10 @@ def run():
# DTF-WEB-3: a burst above MAX_PENDING_UPLOADS (now 30). The 31st start
# answers 429 with Retry-After 15, so the Site waits and retries alone.
assert int(os.environ.get('MAX_PENDING_UPLOADS', '30')) == 30
# The gateway allows 20 requests a second with a burst of 100
# (infra/nginx.conf.template): after the starts above, a fast runner
# meets nginx's 429 before the API's (CI run 393). Let it refill.
time.sleep(6)
pending = []
for index in range(30):
pending.append(client.call('/uploads', {'name': f'PENDING-{index}.png', 'size': 1})['id'])

View File

@@ -84,12 +84,12 @@
// What the server charges for a file opened by hand, never the page's own text.
const zona=document.getElementById('zManual');
const extra=session.manual_extra_cents>0?rs(session.manual_extra_cents/100):'';
if(zona)zona.innerHTML='Tem <b>CDR, AI, PSD ou TIFF</b>? Pode mandar também. Alguém abre na mão'+
(extra?', e o metro custa '+extra+' a mais':'')+'.';
if(zona)zona.innerHTML='<b>CDR, AI, PSD e TIFF</b> também entram. Abrimos o arquivo manualmente'+
(extra?' e o metro custa '+extra+' a mais':'')+'.';
const duvida=document.getElementById('duvidaManual');
if(duvida)duvida.textContent='alguém abre na mão'+(extra?', sai mais devagar e o metro custa '+extra+' a mais':' e sai mais devagar');
if(duvida)duvida.textContent='abrimos o arquivo manualmente'+(extra?', leva mais tempo e o metro custa '+extra+' a mais':' e leva mais tempo');
const tabela=document.getElementById('tabelaManual');
if(tabela){tabela.hidden=!extra;tabela.textContent='Arquivo em CDR, AI, PSD ou TIFF, que alguém abre na mão: + '+extra+' por metro.';}
if(tabela){tabela.hidden=!extra;tabela.textContent='Arquivo em CDR, AI, PSD ou TIFF, aberto manualmente: + '+extra+' por metro.';}
if(session.manual_extra_cents>0){
TAXA_MANUAL=session.manual_extra_cents/100;
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
@@ -214,6 +214,7 @@
rows.push(linha('Ajuste Fino Redesenho'+(arts?' · '+arts+(arts===1?' arte':' artes'):'')+' · +48 h',
rs(quote.redesign.cents/100)));
}
if(approved.proof) rows.push(linha('Prova antes de imprimir','Grátis'));
if(approved.coupon)
rows.push(linha('Cupom '+approved.coupon.code, '− '+rs(approved.coupon.discount_cents/100)));
rows.push(linha('Total', rs(approved.total_cents/100), 'tot'));
@@ -406,7 +407,7 @@
if (texto) el.append(document.createTextNode(texto));
if (e?.fase==='enviando') {
const nota=document.createElement('small'); nota.className='envioNota';
nota.textContent='O tempo depende da velocidade da sua internet. Mantenha a página aberta.';
nota.textContent='Mantenha a página aberta até o envio terminar.';
el.append(nota);
}
el.classList.toggle('ok', e?.fase==='pronto');
@@ -475,12 +476,17 @@
if (draftId && quotedCart === cartSnapshot()) { await refresh(true); return; }
if (draftId) clearDraft();
if (!clienteOk() || !entrega.cotado) return;
if (!enderecoOk()) return message('Preencha o endereço de entrega.','error');
// Guidance: the customer fills it in (Sentry DTF-WEB-24).
if (!enderecoOk()) return message('Preencha o endereço de entrega.','warn');
// Guidance, not a failure: the customer still has a quality note to
// confirm, and the page takes them to it (Sentry DTF-WEB-Y).
if (!cartPodeEnviar()) {
if (itensAPagar().some(semMargem)) {
document.querySelector('.item .avisoF')?.scrollIntoView({behavior:'smooth',block:'center'});
return message('Uma folha do carrinho foi montada antes dos 8 mm entre as cópias: remova e adicione de novo.','warn');
}
document.querySelector('.aceiteRes input:not(:checked)')?.closest('label')?.scrollIntoView({behavior:'smooth',block:'center'});
return message('Revise a qualidade e confirme a ressalva de cada item antes de enviar o pedido.','warn');
return message('Confirme a ressalva de cada item antes de seguir.','warn');
}
const semArquivo=faltaEnvioMensagem();
if (semArquivo) return message(semArquivo+'.','error');
@@ -513,7 +519,7 @@
}
// Layout versions the server takes: 3 since 2026-10-21, 2 for a cart saved before.
if (![2,3].includes(item.production?.version) || item.production.sources?.length!==uploads.length)
throw new Error('A montagem deste item precisa ser refeita antes da cotação.');
throw new Error('Monte este item de novo antes de seguir.');
items.push({mode:item.modo, metres:String(item.metros), grade:item.nota, uploads,
production:{...item.production,sources:item.production.sources.map((source,index)=>({
upload_id:uploads[index],...source}))},
@@ -597,7 +603,7 @@
if (quote.status==='pending_review') {
message((await ready).environment==='local'
? 'Arquivos enviados. No Kanban, confira a metragem e os arquivos e aprove a cotação '+draftId.slice(0,8)+'.'
: 'Arquivos enviados. Nossa equipe está conferindo a cotação '+draftId.slice(0,8)+'; o valor final aparece aqui em seguida.');
: 'Arquivos enviados. Nossa equipe confere a cotação '+draftId.slice(0,8)+' e o valor final aparece aqui.');
} else if (quote.status==='approved') {
if ((await ready).payment_provider === 'mercadopago') {
if (naPix()) await paginaPix(quote, version);
@@ -622,7 +628,7 @@
});
} else {
message(quote.status==='discarded'
? 'Esta cotação foi cancelada pela nossa equipe. Envie o carrinho de novo ou fale com a gente.'
? 'Nossa equipe cancelou esta cotação. Envie o carrinho de novo ou fale conosco.'
: 'Cotação expirada. Envie o carrinho de novo para pagar.','warn');
button('Voltar ao carrinho',()=>{clearDraft();vaiPara(CARRINHO);});
}
@@ -874,10 +880,10 @@
unmountCard();
into.replaceChildren(node('p',result.status==='approved'
? 'Pagamento aprovado. Confirmando seu pedido…'
: 'Pagamento em análise pelo Mercado Pago. Esta página atualiza assim que ele for confirmado.','pagNota'));
: 'Pagamento em análise pelo Mercado Pago. Esta página atualiza quando ele for confirmado.','pagNota'));
waitForOrder();
} else {
message(result.message||'O pagamento foi recusado. Confira os dados ou use outro cartão ou pague com PIX.','error');
message(result.message||'O pagamento foi recusado. Confira os dados, use outro cartão ou pague com PIX.','error');
throw new Error('rejected');
}
}

View File

@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>DTF Dropstar · mande sua arte e veja a qualidade</title>
<title>DTF Dropstar · envie sua arte e veja o preço</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
@@ -719,8 +719,8 @@ h2 em{font-style:normal;color:var(--laranja)}
<span class="chip2 destaque">Metro a partir de <span data-preco="file">R$ 19,90</span></span>
<span class="chip2">Franca · SP · envio em até 24 h</span>
</div>
<h1>A gente encaixa sua folha e você paga <em>menos metro</em></h1>
<p>Mande a arte, confira a folha montada e veja o preço antes de pagar. Revisão de 5 pontos e reencaixe por nossa conta.</p>
<h1>Encaixamos sua folha e você paga <em>menos metro</em></h1>
<p>Envie a arte e confira a folha montada e o preço antes de pagar. Revisamos 5 pontos e reencaixamos sem custo.</p>
<div class="hero2-cta">
<a href="/#envio" class="btn-laranja">Enviar minha arte <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg></a>
<span>Sem cadastro · preço em segundos</span>
@@ -757,7 +757,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<section id="videos" class="videos2"><div class="w">
<div class="videosCab">
<div><div class="et">Vídeos</div><h2>A DTF por dentro</h2></div>
<p>Do upload à retirada: o que acontece com a sua arte, sem letra miúda.</p>
<p>O que acontece com a sua arte, do envio à retirada.</p>
</div>
<div class="videosGrid" id="videosGrid"></div>
</div></section>
@@ -794,7 +794,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<button class="ec a" data-modo="avulsa">
<div class="ec-top"><span class="ec-kind">DTF TÊXTIL · 57 CM</span></div>
<h3>Artes avulsas</h3>
<p>Cada arte num arquivo. A gente monta a folha com o melhor encaixe. Montagem inclusa no preço.</p>
<p>Cada arte num arquivo. Montamos a folha com o melhor encaixe. Montagem inclusa no preço.</p>
<div class="ec-pe">
<div class="ec-preco"><b data-preco="avulsa">R$ 21,90</b><span>por metro</span></div>
<span class="ec-go">Enviar minhas artes</span>
@@ -862,8 +862,8 @@ h2 em{font-style:normal;color:var(--laranja)}
<span id="zLimite">Até 4 GB por arquivo.</span>
<span class="bt">ou escolher no computador</span>
<span class="zOutra"><b id="zOutra">Adicionar outra folha</b> ou arraste aqui</span>
<span class="zManual" id="zManual">Tem <b>CDR, AI, PSD ou TIFF</b>? Pode mandar também.
Alguém abre na mão, e o metro custa R$ 2,00 a mais.</span>
<span class="zManual" id="zManual"><b>CDR, AI, PSD e TIFF</b> também entram. Abrimos o arquivo
manualmente e o metro custa R$ 2,00 a mais.</span>
</div>
<div class="envios" id="envios" aria-live="polite"></div>
<div class="recusa" id="recusa" style="display:none"></div>
@@ -876,63 +876,60 @@ h2 em{font-style:normal;color:var(--laranja)}
<details>
<summary>Dicas para o seu arquivo</summary>
<ul>
<li class="s"><b>300 DPI no tamanho que vai imprimir.</b> É a resolução ideal</li>
<li class="s"><b>O tamanho manda mais que o arquivo.</b> A mesma arte passa
em 20 cm e não passa em 40. Reduzir um pouco costuma melhorar a resolução</li>
<li class="s"><b>Larguras parecidas rendem mais.</b> Se as suas artes têm
medidas próximas, cabem mais por fileira e a folha encolhe</li>
<li class="s"><b>300 DPI no tamanho de impressão.</b> É a resolução ideal</li>
<li class="s"><b>A resolução depende do tamanho.</b> A mesma arte passa
em 20 cm e não passa em 40. Reduzir um pouco melhora a resolução</li>
<li class="s"><b>Larguras parecidas rendem mais.</b> Cabem mais artes por
fileira e a folha fica menor</li>
</ul>
<p class="obs2">A resolução não muda o preço do metro; ela mostra se o arquivo pode sair nítido.</p>
<p class="obs2">A resolução não muda o preço. Ela mostra se a arte sai nítida.</p>
</details>
<details>
<summary>O que arrumamos sem cobrar</summary>
<ul>
<li class="s"><b>Artes coladas.</b> Separamos com 5 mm, sem você refazer nada</li>
<li class="s"><b>Encaixe mal aproveitado.</b> Remanejamos e a sua folha
encolhe — você paga menos metro do que enviou</li>
<li class="s"><b>Peça passando da largura.</b> Remanejamos em vez de cortar</li>
<li class="s"><b>Margem.</b> Não precisa deixar. Só respeitar a largura do filme</li>
<li class="s"><b>Artes coladas.</b> Separamos com 5 mm</li>
<li class="s"><b>Encaixe com sobra.</b> Reencaixamos, e você paga pela
folha menor</li>
<li class="s"><b>Arte passando da largura.</b> Reencaixamos em vez de cortar</li>
<li class="s"><b>Margem.</b> Não precisa deixar, basta respeitar a largura do filme</li>
</ul>
</details>
<details>
<summary>Manda em PNG e sai na hora</summary>
<summary>Formatos de arquivo</summary>
<ul>
<li class="s"><b>PNG</b> com fundo transparente entra direto, sem passar
por ninguém, e não tem limite de comprimento. Só que a gente lê a resolução
<b>do arquivo</b>: se a arte foi ampliada antes de exportar, isso não aparece
para nós — e sai serrilhado no filme do mesmo jeito</li>
<li class="s"><b>PDF é o que conferimos melhor.</b> Nele medimos a resolução de
cada imagem dentro da folha, uma por uma. É onde a conferência
de resolução fica mais precisa</li>
<li class="a"><b>PDF grande.</b> Sem UserUnit, a página passa do limite de 508 cm
do formato; divida a folha ou mande PNG. Envie um PDF de uma página por folha.</li>
<li class="a"><b>TIFF, PSD, AI e CDR</b> a gente aceita, mas ninguém consegue
conferir sozinho: <span id="duvidaManual">alguém abre na mão, sai mais devagar
<li class="s"><b>PNG</b> com fundo transparente entra direto e não tem
limite de comprimento. Lemos a resolução <b>do arquivo</b>: uma arte ampliada
antes de exportar passa na conferência e sai serrilhada no filme</li>
<li class="s"><b>PDF tem a conferência mais precisa.</b> Medimos a resolução
de cada imagem dentro da folha</li>
<li class="a"><b>PDF acima de 508 cm.</b> Só entra com UserUnit. Sem ele,
divida a folha ou envie em PNG. Um PDF de uma página por folha</li>
<li class="a"><b>TIFF, PSD, AI e CDR</b> também entram, mas o site não confere:
<span id="duvidaManual">abrimos o arquivo manualmente, leva mais tempo
e o metro custa R$ 2,00 a mais</span></li>
<li class="a"><b>JPG não passa:</b> não tem fundo transparente, e o branco do
fundo sai no filme. Exporte a folha em PNG ou PDF</li>
<li class="a">Em <b>artes avulsas</b> só PNG com fundo transparente: a montagem
precisa enxergar a sua arte para encaixar pela forma</li>
<li class="a"><b>JPG não entra:</b> não tem fundo transparente, e o fundo
sai branco no filme. Exporte em PNG ou PDF</li>
<li class="a">Em <b>artes avulsas</b>, só PNG com fundo transparente: a montagem
encaixa pela forma da arte</li>
</ul>
</details>
<details>
<summary>O que só você resolve</summary>
<ul>
<li class="n"><b>Fundo branco ou colorido.</b> Precisa ser transparente de
verdade — branco parecendo transparente sai branco no filme. Sem isso, o site
não deixa pagar</li>
<li class="n"><b>Pontinho de recorte.</b> A impressora enxerga qualquer
resíduo e imprime. Não existe pequeno demais: o site mostra onde cada um está
e pede que você apague ou aceite imprimir assim</li>
<li class="n"><b>Fundo branco ou colorido.</b> O fundo precisa ser transparente:
branco sai branco no filme, e o site não deixa pagar</li>
<li class="n"><b>Pontinho de recorte.</b> Todo ponto de tinta sai impresso,
por menor que seja. Mostramos onde estão: apague no arquivo ou aceite
imprimir assim</li>
<li class="n"><b>Cópias sobrepostas.</b> Duas iguais com 1 mm de diferença
saem duplicadas</li>
<li class="n"><b>Menos de 96 DPI.</b> Abaixo disso não imprimimos: sai
serrilhado a ponto de não valer o filme</li>
<li class="n"><b>Degradê de transparência</b>, comum em arte de IA. O branco
por baixo sai irregular e sai assim mesmo</li>
<li class="n"><b>Menos de 96 DPI.</b> Não imprimimos: sai serrilhado
demais</li>
<li class="n"><b>Degradê de transparência</b>, comum em arte feita por IA.
O branco por baixo sai irregular, e imprimimos assim mesmo</li>
</ul>
</details>
</aside>
@@ -971,7 +968,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<div class="ampliaCab"><b id="mistaTit">Traços finos e áreas chapadas</b></div>
<div class="mistaCorpo">
<p id="mistaTxt"></p>
<div class="mistaBot"><button type="button" class="ec-go" id="mistaSegue">Imprimir assim mesmo (C1)</button><button type="button" id="mistaSep">Quero subir em dois arquivos</button></div>
<div class="mistaBot"><button type="button" class="ec-go" id="mistaSegue">Imprimir assim mesmo</button><button type="button" id="mistaSep">Subir em dois arquivos</button></div>
</div>
</dialog>
<dialog class="ampliaDlg mistaDlg" id="linhaDlg" aria-labelledby="linhaTit">
@@ -1125,16 +1122,16 @@ h2 em{font-style:normal;color:var(--laranja)}
<h4>Prova antes de imprimir</h4>
<label class="provaOp"><input type="checkbox" id="fProva">
<span><b>Quero aprovar uma prova antes de imprimir</b>
Imprimimos até 15 cm por classe de contração e mandamos a foto pelo WhatsApp. O resto só é impresso
depois do seu ok, então o pedido espera a sua resposta. Até 3 provas por pedido, sem custo.</span></label>
Imprimimos uma prova de até 30 cm e mandamos a foto pelo WhatsApp. O resto sai depois
que você aprovar. Até 3 provas por pedido, sem custo.</span></label>
<p class="provaMin" id="provaMin" hidden>A prova é para pedidos acima de 10 m.</p>
</div>
<div class="cxE" id="tratamentoBox" hidden>
<h4>Ajuste Fino</h4>
<label class="provaOp"><input type="checkbox" id="fTratamento">
<span><b>Ajuste Fino em todas as artes — <span id="tratamentoPreco"></span> por arte</b>
O designer ajusta a arte para DTF, com fundo transparente e 300 DPI, e sobe o arquivo
pelo card. O prazo do pedido aumenta em 24 h.</span></label>
<span><b>Ajuste Fino em todas as artes, <span id="tratamentoPreco"></span> por arte</b>
Nosso designer deixa cada arte com fundo transparente e 300 DPI. O pedido leva 24 h a mais.</span></label>
</div>
</div>
@@ -1189,13 +1186,13 @@ h2 em{font-style:normal;color:var(--laranja)}
</tbody>
</table>
<div class="nota2" id="tabelaFaixas" hidden></div>
<p class="nota2" id="tabelaManual">Arquivo em CDR, AI, PSD ou TIFF, que alguém abre na mão: + R$ 2,00 por metro.</p>
<p class="nota2" id="tabelaManual">Arquivo em CDR, AI, PSD ou TIFF, aberto manualmente: + R$ 2,00 por metro.</p>
</div>
<div class="info2-vant">
<div><b class="n">57 cm</b><b>O dobro do filme padrão</b><span>Cabe o dobro de arte por metro corrido.</span></div>
<div><b class="n">10 cm</b><b>Você paga o que usa</b><span>Folha de 2,75 m custa 2,80 m, não 3. Pedido mínimo de 1 metro.</span></div>
<div><b class="n">Grátis</b><b>Reencaixe da folha</b><span>Sobrou espaço? Refazemos o encaixe e a conta diminui.</span></div>
<div><b class="n">5 pontos</b><b>Revisão sem custo</b><span>Erro pego antes de imprimir. Arquivo guardado por 30 dias.</span></div>
<div><b class="n">Grátis</b><b>Reencaixe da folha</b><span>Se sobrar espaço, reencaixamos e a folha fica menor.</span></div>
<div><b class="n">5 pontos</b><b>Revisão sem custo</b><span>Conferimos antes de imprimir e guardamos o arquivo por 30 dias.</span></div>
</div>
</div></section>
@@ -1217,7 +1214,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<a href="https://wa.me/message/NJ76CLIOUGXLB1" target="_blank" rel="noopener">16 99428-0056</a>
· arquivos 16 99230-2546<br>
<a href="mailto:atendimentodropstar@gmail.com">atendimentodropstar@gmail.com</a><br>
Mande sua arte em qualquer horário.<br>
Envie sua arte a qualquer hora.<br>
Retirada em Franca, de segunda a sexta, das 7h às 18h
</div>
</div>

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 room marks "Prova OK" once it is checked; without it, no Finalizado.
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 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

View File

@@ -103,7 +103,7 @@ function renderIssues(){
if(key==='open')b.append(node('span',String(board.payment_issues_total||0),'n'));
b.onclick=()=>{issueState=key;issuePage=1;loadIssues().catch(e=>say(e.message,true));};seg.append(b);
}
const tools=node('div',undefined,'pagetools');tools.append(seg,node('span','Pagamentos que o sistema não conseguiu ligar a um pedido sozinho.','lbl'));
const tools=node('div',undefined,'pagetools');tools.append(seg,node('span','Pagamentos que não se ligaram a um pedido.','lbl'));
if(!issueRows.length){
$('payments').replaceChildren(tools,emptyState(IC.check,issueState==='resolved'?'Nenhum pagamento resolvido':'Nenhum pagamento pendente',
issueState==='open'?'Quando um pagamento precisar de alguém, ele aparece aqui.':''));
@@ -343,7 +343,7 @@ function renderIntegrations(){
function mailRow(m){
const name='E-mail';
if(m.adapter!=='smtp'&&m.adapter!=='log')return integRow({name,state:'Não configurado',tone:'off',
summary:'Sem recuperação de senha por e-mail: o cliente é orientado a chamar no WhatsApp.'});
summary:'Sem recuperação de senha por e-mail: o cliente chama no WhatsApp.'});
const local=m.adapter==='log';
return integRow({name,state:m.error?'Verificar':local?'Só registro':'Ativo',tone:m.error?'warn':local?'off':'ok',
summary:m.error?'Falhou o envio para '+m.error.to+': '+m.error.error:'E-mails dos clientes: confirmação de pedido, recuperação de senha e códigos de confirmação.',

View File

@@ -154,7 +154,8 @@ function montarQuoteFigures(lines){
});
const catalog=MONTAR.catalog?.avulsa;
if(!catalog)throw new Error('Preço de tabela indisponível agora.');
const billed=heights.map(metres=>Math.max(1,Math.ceil(metres*10)/10));
// Every 10 cm, 8 mm in the customer's favour (app/core/pricing.py billed_length).
const billed=heights.map(metres=>Math.max(1,Math.ceil(+((metres-0.008)*10).toFixed(6))/10));
const total=+billed.reduce((sum,metres)=>sum+metres,0).toFixed(2);
let unit=catalog.unit_cents,best=null;
for(const band of catalog.bands||[]){
@@ -395,7 +396,7 @@ function montarPaintTotals(){
$('montar-sum-pieces').textContent=String(pieces);
$('montar-sum-film').textContent=count?(done?metres(film):metres(film)+' …'):'—';
$('montar-film-length').textContent=count?metres(film):'—';
$('montar-film-hint').textContent='em filme de 57 cm, já encaixada. Atualiza a cada mudança na lista.'+
$('montar-film-hint').textContent='em filme de 57 cm, já encaixada.'+
(count&&!done?' Calculando a montagem…':'');
$('montar-clear').disabled=!count;
$('montar-warning').hidden=!(count>20||MONTAR.lines.some(line=>line.qty>200));
@@ -948,7 +949,7 @@ function montarOpenAdjustments(){
if(!may('manage')||$('montar-sizes'))return;
MONTAR.dirty=false;MONTAR.internalDirty=false;
formDialog('Ajustes do Montar',{
text:'Valem para todas as folhas. Mudam pouco, por isso ficam aqui e não na tela.',
text:'Valem para todas as folhas.',
fields:montarAdjustmentFields(),label:'Salvar ajustes',width:720,className:'montar-ajustes-dlg',
onsave:async()=>montarSaveAdjustments()
});

View File

@@ -266,7 +266,7 @@ function nextBox(order){
title='Aguardando prova do #'+order.proof_card.number;
const manual=(board.orders.find(o=>o.id===order.proof_card.id)?.print_files||[]).some(r=>r.status==='manual');
note(manual?'O Prumo não abriu o original. Prepare o PNG completo deste pedido; a prova será gerada automaticamente a partir dele.'
:'O pedido segue para Arte conferida após Prova OK no card da prova. Você pode abrir o arquivo para consultar.');
:'O pedido segue para Arte conferida com Prova OK no card da prova.');
if(manual&&may('produce'))main.push(button('Preparar arquivo para a prova',()=>finalDialog(order,readyFinals(order)),'btn pri lg'));
if(order.proof_card.reviews?.length)more.push(...reviewButtons(order.proof_card.id,order.proof_card.reviews,order.proof_card.number));
return composeNext(title,body,main,more);
@@ -304,9 +304,8 @@ function nextBox(order){
if((st==='rec'||st==='tra'||st==='imp')&&!order.proof_parent&&!fixed&&may('produce')&&
(order.print_files||[]).some(r=>r.status==='ready'))
more.push(button('Gerar de novo',async()=>{
if(!await ask('Gerar o arquivo de novo?','O sistema gera o arquivo do pedido de novo, com o tamanho de parte de agora. '+
'O arquivo final aprovado sai: o pedido volta para Arte recebida'+(st==='imp'?', sai da hot folder da máquina,':'')+
' e o arquivo novo precisa ser aprovado.',
if(!await ask('Gerar o arquivo de novo?','O arquivo sai com o tamanho de parte atual. O pedido volta para Arte recebida'+
(st==='imp'?' e sai da hot folder':'')+', e o arquivo novo precisa ser aprovado.',
'Gerar de novo',{host:$('drawer')}))return;
await api('/orders/'+order.id+'/print-files/again',{});await load();
say('Gerando o arquivo do #'+order.number+' de novo. Aprove quando ficar pronto.');
@@ -330,7 +329,7 @@ function nextBox(order){
const manual=(order.print_files||[]).some(r=>r.status==='manual');
note(finalDone(order)?'Abra o PNG gerado pelo Prumo e confirme a contração.':manual
?'O original exige preparo manual. Abra o pedido pai, envie o PNG completo e depois gere a prova de novo.'
:'O Prumo prepara até 15 cm por classe e aprova o PNG final automaticamente.');
:'O Prumo prepara até 30 cm por classe e aprova o PNG final automaticamente.');
if(manual&&may('produce'))more.push(button('Abrir pedido pai',()=>openPanel(order.proof_parent.id),'btn lg'));
if(finalDone(order)&&may('produce'))main.push(checkButton(order,'btn pri lg'));
if((order.print_files||[]).some(r=>r.status==='failed'||r.status==='manual'||r.timed_out)&&may('produce'))
@@ -440,7 +439,7 @@ function correctionDialog(order){
const text=node('textarea');text.placeholder='Ex.: o logo da manga veio em 72 DPI';text.maxLength=1000;text.required=true;
text.setAttribute('aria-label','Motivo da correção');
formDialog('Pedir correção do pedido #'+order.number,{host:$('drawer'),className:'reason',width:540,
text:'O pedido vai para Correção. Depois, a mensagem para o cliente fica pronta para mandar no WhatsApp.',
text:'O pedido vai para Correção e a mensagem para o cliente fica pronta para o WhatsApp.',
fields:[field('Motivo',text,'O cliente vê este motivo na mensagem.')],label:'Enviar para correção',tone:'red',
onsave:async()=>{await move(order,'cor',text.value.trim());}});
}
@@ -463,7 +462,7 @@ function cancelDialog(order){
const why=node('textarea');why.placeholder='Ex.: cliente desistiu, vai refazer a arte';why.setAttribute('aria-label','Motivo do cancelamento');
why.required=true;why.minLength=3;why.maxLength=1000;
formDialog('Cancelar o pedido #'+order.number+'?',{host:$('drawer'),className:'reason',width:520,
text:'O pedido sai do quadro e fica em Cancelados, com o pagamento e o histórico. O valor fica como crédito do cliente, no controle financeiro, e o pedido no Tiny se cancela lá.',
text:'O pedido vai para Cancelados com o pagamento e o histórico. O valor vira crédito do cliente e o pedido é cancelado no Tiny.',
fields:[field('Motivo',why,'Fica no histórico do pedido.')],label:'Cancelar pedido',tone:'red',
onsave:async()=>{await api('/orders/'+order.id+'/cancel',{note:why.value.trim()});say('Pedido #'+order.number+' cancelado.');await load();}});
}
@@ -553,12 +552,12 @@ async function finalsOk(order,uploads){
async function approveReady(order,ready){
if(!await finalsOk(order,ready.flatMap(r=>r.files.map(f=>f.upload_id))))return;
const many=ready.length>1;
if(!await ask('Aprovar o arquivo final?','Conferiu? É este arquivo que vai para a impressão: '+
if(!await ask('Aprovar o arquivo final?','Este é o arquivo que vai para a impressão: '+
ready.map((r,i)=>(many?'item '+(i+1)+', ':'')+r.label).join('; ')+'.','Aprovar arquivo final',{host:$('drawer')}))return;
const note='Aprovado como está: '+[...new Set(ready.map(r=>FINAL_SOURCE[r.source]))].join(', ');
if(await saveFinalFiles(order,
ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))),note))return;
await load();say(mayMove(order.state,'tra')?'Arquivo final aprovado. Agora é só mover para Arte conferida.':'Arquivo final aprovado. Falta mover para Arte conferida.');
await load();say(mayMove(order.state,'tra')?'Arquivo final aprovado. Mova para Arte conferida.':'Arquivo final aprovado. Falta mover para Arte conferida.');
}
// The file the operator prepared, per item; a ready file comes ticked.
function finalDialog(order,ready,{replace=false}={}){
@@ -857,7 +856,7 @@ function isOk(order){
const treat=button('Tratar a arte',()=>{m.close();treatDialog(order);},'btn');
const m=formDialog('Está OK?',{host:$('drawer'),fields,left:[treat],label:'Mover para Arte conferida',
text:missing?'Falta o arquivo final de um item: trate a arte e envie o arquivo preparado.'
:'A arte chegou boa? Confira a contração e mova para Arte conferida.',
:'Confira a arte e a contração e mova para Arte conferida.',
onsave:async()=>{
if(missing)throw new Error('Falta o arquivo final de um item.');
for(const [index,select] of selects.entries())
@@ -894,12 +893,12 @@ function treatDialog(order){
row.path.textContent=name?(base.value.trim()?'':'…\\')+where(name):'Este item ainda não tem arquivo na pasta.';
row.copy.disabled=!name;
row.copy.onclick=async()=>{try{await navigator.clipboard.writeText(where(name));
say(base.value.trim()?'Caminho copiado.':'Caminho copiado a partir da pasta dos pedidos: informe onde ela fica neste computador para copiar o caminho inteiro.');}
say(base.value.trim()?'Caminho copiado.':'Caminho copiado sem o começo. Informe onde fica a pasta dos pedidos neste computador para copiar o caminho completo.');}
catch(_){say('Não foi possível copiar.',true);}};
});
base.onchange=()=>{kv.set(FOLDER_PATH_KEY,base.value.trim()).catch(()=>{});paint();};
formDialog('Tratar a arte',{host:$('drawer'),width:620,className:'finalform',
text:'Copie o caminho e abra o arquivo. Trate e salve por cima, com o mesmo nome. Depois suba aqui o arquivo tratado.',
text:'Copie o caminho e abra o arquivo. Trate, salve por cima com o mesmo nome e envie aqui o arquivo tratado.',
fields:[...rows.map(r=>r.input.closest('.fslot')),field('Pasta dos pedidos neste computador',base)],label:'Subir arte tratada',
onsave:async()=>{
// Each item keeps its approved final, or else the file ready to approve,
@@ -924,7 +923,7 @@ function treatDialog(order){
}
if(await saveFinalFiles(order,refs,TREAT_NOTE))return;
await load();
say(mayMove(order.state,'tra')?'Arte tratada aprovada como arquivo final. Agora é só mover para Arte conferida.':'Arte tratada aprovada como arquivo final.');
say(mayMove(order.state,'tra')?'Arte tratada aprovada como arquivo final. Mova para Arte conferida.':'Arte tratada aprovada como arquivo final.');
}});
// Filled once open: the names the automatic folders give the files.
(async()=>{
@@ -1074,7 +1073,7 @@ function itemCard(order,item,index){
(item.residue_accepted_at?' às '+when(item.residue_accepted_at):'')+'.','warn'));
if(item.stroke_choice)notes.append(itemNote('Traços finos e áreas chapadas no mesmo arquivo: '+
(item.stroke_choice==='client_c3'?'o cliente escolheu proteger as áreas chapadas (C3); o traço fino pode sumir em tecido escuro.'
:'o cliente foi avisado e quis imprimir assim mesmo (C1).')+
:'o cliente escolheu imprimir assim mesmo (C1).')+
(item.stroke_choice_at?' Aceito às '+when(item.stroke_choice_at)+'.':''),'warn'));
if(mirroredItem(item))notes.append(itemNote(MIRROR_NOTE+'.','bad'));
// After a customer correction, that file is the artwork: the generated

View File

@@ -323,7 +323,10 @@ function machineForm(m){
left.push(remove);
}
const d=formDialog(m?'Editar máquina':'Nova máquina',{width:520,left,
fields:[field('Nome',name),group('Imprime',products),
// The hot folder is the machine's first name, for good (FlexiPRINT watches
// that path): renaming the machine does not move it.
fields:[field('Nome',name,m?'Pasta no FlexiPRINT: 3. Imprimindo/'+(m.folder||m.name)+'. Trocar o nome não muda a pasta.':undefined),
group('Imprime',products),
field('Limite de metros em aberto',unit(limit,'metros'),'Pedidos novos vão para a máquina do produto com menos metros em aberto, dentro do limite.'),
field('Vagas em Imprimindo',places,PLACES_NOTE),
checkbox('Ativa: recebe pedidos',active)],
@@ -738,7 +741,7 @@ function accountForm(){
sect.append(node('b','Trocar a senha'),field('Senha atual',current),row);
formDialog(ME.name||ME.email,{width:560,lead:avatar({name:ME.name,email:ME.email,active:true,seen_at:new Date().toISOString()},'bigava'),
text:rolesLabel(myRoles())+(myMachine()?', na '+myMachine().name:''),fields:[dl,sect],
note:'Nome, e-mail e perfil quem muda é o administrador.',label:'Salvar senha',onsave:async()=>{
note:'Só o administrador muda nome, e-mail e perfil.',label:'Salvar senha',onsave:async()=>{
if(next.value!==again.value)throw new Error('A nova senha e a repetição não conferem.');
await api('/me/password',{current:current.value,new:next.value});say('Senha trocada.');
}});

View File

@@ -122,7 +122,7 @@
<section class="panel montar-nofolder-panel" id="montar-nofolder-panel" hidden>
<span class="montar-nofolder-ico"><svg class="i" viewBox="0 0 256 256" aria-hidden="true"><path fill="currentColor" d="M216,72H131.31L104,44.69A15.86,15.86,0,0,0,92.69,40H40a16,16,0,0,0-16,16V200.62A15.4,15.4,0,0,0,39.38,216H216.89A15.13,15.13,0,0,0,232,200.89V88A16,16,0,0,0,216,72ZM40,56H92.69l16,16H40ZM216,200H40V88H216Z"></path></svg></span>
<b>Escolha a pasta dos pedidos</b>
<span>O Montar lê as estampas da pasta Estampas/, dentro da pasta dos pedidos deste computador. É a mesma pasta de Integrações; basta escolher uma vez.</span>
<span>As estampas vêm da pasta Estampas/, dentro da pasta dos pedidos (a mesma de Integrações).</span>
<button class="btn pri" id="montar-nofolder-choose" type="button">Escolher pasta</button>
</section>
<section class="panel clip" id="montar-setup" hidden>
@@ -146,7 +146,7 @@
<div class="montar-sheetinfo">
<span>Prévia da folha</span>
<b id="montar-film-length">—</b>
<span id="montar-film-hint">em filme de 57 cm, já encaixada. Atualiza a cada mudança na lista.</span>
<span id="montar-film-hint">em filme de 57 cm, já encaixada.</span>
</div>
</div>
</section>

View File

@@ -27,6 +27,8 @@ function outcomeText(outcome){
[/^refused: quote was never reviewed/,()=>'a cotação ainda não tinha sido revisada'],
[/^refused: quote uses an obsolete/,()=>'a cotação usa uma montagem antiga'],
[/^attention: payment (\w+) for order (\d+)/,m=>'pagamento '+(m[1]==='refunded'?'estornado':'cancelado')+' depois do pedido #'+m[2]],
// The customer paid the same cart twice (a PIX and a card): one is refunded.
[/^attention: second payment (\S+) for order (\d+)/,m=>'segundo pagamento ('+m[1]+') do pedido #'+m[2]+': o cliente pagou duas vezes, estorne um no Mercado Pago'],
];
for(const [pattern,text] of rules){const m=outcome.match(pattern);if(m)return text(m);}
return outcome;
@@ -368,10 +370,10 @@ function folderCard(){
if(FOLDER.mode==='none'){
if(FOLDER.brave){
const first=node('li','Copie este endereço: ');first.append(node('code',BRAVE_FLAG,'flag'));
row=integration({name,state:'Desligada no Brave',tone:'warn',summary:'O Brave bloqueia o acesso a pastas. Dá para liberar em 1 minuto.',
row=integration({name,state:'Desligada no Brave',tone:'warn',summary:'O Brave bloqueia o acesso a pastas. Libere com os passos abaixo.',
actions:[act('Copiar endereço',async()=>{await navigator.clipboard.writeText(BRAVE_FLAG);say('Endereço copiado: cole na barra do Brave.');})],
details:[steps(first,'Cole na barra do Brave e mude “File System Access API” para “Enabled”.','Reinicie o Brave e volte aqui.'),
node('p','Ou abra o Kanban no Chrome ou no Edge, que já vêm com isso ligado.')]});
node('p','Ou abra o Kanban no Chrome ou no Edge.')]});
}else row=integration({name,state:'Não funciona aqui',tone:'off',summary:'Abra o Kanban no Chrome ou no Edge para salvar numa pasta.'});
}else if(FOLDER.mode==='downloads'){
const how=[steps('No Firefox, abra Configurações → Geral → Arquivos e aplicativos.',
@@ -381,13 +383,12 @@ function folderCard(){
? integration({name,state:FOLDER.error?'Verificar':'Ligada',tone:FOLDER.error?'warn':'ok',
summary:FOLDER.error||FOLDER.status||'Baixando na pasta de downloads do Firefox · '+folderCount(),
details:how,extra:[ghost('Desligar',()=>setDownloads(false))]})
: integration({name,state:'Desligada',tone:'off',summary:'No Firefox, baixa sozinho os arquivos que entram em Arte conferida; as pastas do fluxo pedem o Chrome ou o Edge.',
: integration({name,state:'Desligada',tone:'off',summary:'No Firefox, baixa os arquivos que entram em Arte conferida. As pastas do fluxo precisam do Chrome ou do Edge.',
actions:[act('Ligar',()=>setDownloads(true))],details:how});
}else if(!h){
row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho os arquivos dos pedidos nas pastas do fluxo, de 1. Arte recebida a 5. Finalizado, o recibo de cada retirada em Recibos e as fotos da revisão em Revisões.',
row=integration({name,state:'Desligada',tone:'off',summary:'Salva o arquivo de cada pedido na pasta da etapa em que ele está, os recibos em Recibos e as fotos da revisão em Revisões.',
actions:[act('Escolher pasta',chooseFolder)],
details:[node('p','Escolha uma vez a pasta principal, na rede do servidor: o Kanban cria dentro dela as pastas do fluxo e move o arquivo conforme o card anda. '+
'Os arquivos levam o número do pedido no nome. Funciona neste computador, com o Kanban aberto e um usuário que vê todos os pedidos, como o de Gestão.')]});
details:[node('p','Escolha a pasta principal, na rede do servidor. Funciona com o Kanban aberto neste computador, num usuário que vê todos os pedidos, como o de Gestão.')]});
}else if(!FOLDER.granted){
row=integration({name,state:'Liberar',tone:'warn',summary:'O navegador pede um clique para voltar a salvar em “'+h.name+'”.',
actions:[act('Liberar pasta',releaseFolder)],extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
@@ -396,13 +397,11 @@ function folderCard(){
summary:FOLDER.error||FOLDER.status||'Salvando em “'+h.name+'” · '+folderCount(),
details:[['Pasta','“'+h.name+'”'],['Arquivos salvos',String(FOLDER.saved.size)],
['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'],
node('p','Dentro de “'+h.name+'”: o arquivo do pedido chega em '+STAGE_FOLDERS.rec+', passa para '+STAGE_FOLDERS.tra+' quando o card vai para lá '+
'e fica lá enquanto imprime, vai para '+STAGE_FOLDERS.rev+' com o card e para '+STAGE_FOLDERS.fin+' quando o pedido é finalizado, onde fica '+KEEP_FINISHED_DAYS+' dias.'),
node('p','A pasta '+WORK_FOLDER+' é a de trabalho do Kanban: cada arquivo é gravado nela e só entra na pasta da etapa ou na hot folder completo, com o nome final. Não coloque nada nela.'),
node('p','Pedido de retirada que chega em Finalizado: o recibo para a bobina de 80 mm vai para '+RECEIPTS_FOLDER+', uma vez só, por um dos computadores com a pasta ligada. As fotos da revisão vão para '+REVIEWS_FOLDER+' e não saem de lá.'),
node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai das pastas. Arquivo trocado: a versão antiga sai. '+
'Pedidos que já estavam imprimindo quando a pasta foi escolhida não são baixados. Se este computador ficar desligado, '+
'ao voltar ele busca também o que passou nesse tempo, cada arquivo na pasta da etapa em que o pedido está. Deixe o Kanban aberto neste computador.')],
node('p','Cada arquivo fica na pasta da etapa do pedido, de '+STAGE_FOLDERS.rec+' a '+STAGE_FOLDERS.fin+'. Em '+STAGE_FOLDERS.fin+' fica '+KEEP_FINISHED_DAYS+' dias.'),
node('p','Não coloque nada na pasta '+WORK_FOLDER+': é a de trabalho do Kanban.'),
node('p','O recibo de cada retirada vai para '+RECEIPTS_FOLDER+' quando o pedido é finalizado. As fotos da revisão ficam em '+REVIEWS_FOLDER+'.'),
node('p','Pedido cancelado, excluído ou em correção sai das pastas. Pedidos que já imprimiam quando a pasta foi escolhida não são baixados.'),
node('p','Deixe o Kanban aberto neste computador. Se ele ficar desligado, ao voltar busca o que faltou.')],
extra:[ghost('Trocar pasta',chooseFolder),ghost('Desligar',forgetFolder)]});
}
row.id='folder-card';return row;
@@ -566,6 +565,9 @@ async function fetchFile(url,options){
}
async function fetchInto(dir,file,watched=false){
const r=await fetchFile(file.url,{referrerPolicy:'no-referrer'});
// A link that ran out while the files before it were downloading: the next
// pass asks for a new one, as for a network that dropped.
if(r.status===403){const e=new Error('o link de '+file.name+' venceu antes do download.');e.unreachable=true;throw e;}
if(!r.ok||!r.body)throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').');
await writeWhole(dir,file.name,r,watched);
}
@@ -624,9 +626,16 @@ async function syncFolder(force=false){
FOLDER.busy=true;
try{
if(stages)await makeStageFolders();
const held=stages?[...new Set([...FOLDER.saved.values()].filter(r=>!r.review).map(r=>r.order).filter(Boolean))].slice(-1000):[];
// The server answers for up to 1000 orders a pass: the ones still in the
// flow first, then those in Finalizado. A file whose order was not asked
// this time stays as it is; only an order the server says is gone,
// cancelled or moved changes its files.
const records=[...FOLDER.saved.values()].filter(r=>!r.review&&r.order);
const held=stages?[...new Set([...records.filter(r=>r.folder!==STAGE_FOLDERS.fin),...records.filter(r=>r.folder===STAGE_FOLDERS.fin)]
.map(r=>r.order))].slice(0,1000):[];
const asked=new Set(held);
const {files,states,receipts=[],reviews=[]}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null});
// By file: an item 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 where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads';
let removed=0, moved=0, saved=0;
@@ -640,7 +649,7 @@ async function syncFolder(force=false){
...(folder===STAGE_FOLDERS.fin?{at:file.at||Date.now()}:{})});
FOLDER.last=new Date();await keepSaved();};
if(stages)for(const [uid,rec] of [...FOLDER.saved])await step(rec.name,async()=>{
if(!rec.order||!rec.folder)return;
if(!rec.order||!rec.folder||!asked.has(rec.order))return;
const state=states[rec.order], target=STAGE_FOLDERS[state];
const now=wanted.get(uid);
const replaced=(state==='rec'||state==='tra')&&(!now||now.order!==rec.order);
@@ -769,7 +778,7 @@ async function syncFolder(force=false){
}
FOLDER.awaySince=0;FOLDER.awayReported=false;
if(e.name==='NotAllowedError')FOLDER.granted=false;
else if(e.name==='NotFoundError')FOLDER.error='Um arquivo ou pasta dentro de “'+name+'” sumiu durante a passagem (alguém tirou ou renomeou?). O Kanban tenta de novo sozinho.';
else if(e.name==='NotFoundError')FOLDER.error='Um arquivo ou pasta dentro de “'+name+'” foi movido ou renomeado. O Kanban tenta de novo sozinho.';
else FOLDER.error='A última tentativa falhou: '+e.message+' O Kanban tenta de novo sozinho.';
FOLDER.status='';say('Pastas automáticas: '+(FOLDER.error||'o navegador pediu para liberar a pasta de novo, em Integrações.'),true);
}finally{FOLDER.busy=false;paintFolder();}

View File

@@ -122,6 +122,14 @@
if (!started || status === 401 || typeof Sentry === 'undefined') return;
// A restart's few seconds without the database (app/app.py): not a bug.
if (status === 503 && /reiniciando/.test(String(message))) return;
// A refusal the server explains to the person (a rule, a check, a limit:
// a 4xx with a sentence for them) is the system working, not a bug: on
// the Kanban it stays, as a warning, since a refusal the team keeps
// meeting says a screen confuses; on the Site the customer reads it and
// nothing is sent (2026-11-30). A 4xx without a sentence (a list of
// fields: what the page sent was wrong) and a 5xx stay errors.
const refusal = status >= 400 && status < 500 && typeof detail === 'string';
if (refusal && app !== 'kanban') return;
try {
// One issue per kind of API error: without this Sentry groups them all
// by apiError and DTF-WEB-1 mixes a 422 for 66 files with a 422 for
@@ -131,7 +139,7 @@
const extra = {path, status, page: location.pathname};
if (status === 422 && detail) extra.detail = detail;
Sentry.captureMessage('API ' + status + ' ' + kindPath + ': ' + kindMessage,
{level: 'error', tags: {app}, extra,
{level: refusal ? 'warning' : 'error', tags: {app, ...(refusal ? {recusa: 'sim'} : {})}, extra,
fingerprint: ['api-error', String(status), kindPath, kindMessage]});
} catch (error) {
// Reporting an error must never break the page.

View File

@@ -208,7 +208,7 @@
<a href="https://wa.me/message/NJ76CLIOUGXLB1" target="_blank" rel="noopener">16 99428-0056</a>
· arquivos 16 99230-2546<br>
<a href="mailto:atendimentodropstar@gmail.com">atendimentodropstar@gmail.com</a><br>
Mande sua arte em qualquer horário.<br>
Envie sua arte a qualquer hora.<br>
Retirada em Franca, de segunda a sexta, das 7h às 18h
</div>
</div>

View File

@@ -326,7 +326,7 @@ $('fPerfil').onsubmit=async event=>{
try{
const r=await api('/account/profile',{name:$('dNomeCli').value,zap:$('dZap').value,address});
conta=r.customer;aviso('Dados salvos.');
}catch(e){aviso(e.status===422?(algum?'Confira o nome, o WhatsApp e o endereço: todos os campos, menos o complemento, são necessários.':'Confira o nome e o WhatsApp.'):e.message,true);}
}catch(e){aviso(e.status===422?(algum?'Preencha nome, WhatsApp e endereço. Só o complemento é opcional.':'Confira o nome e o WhatsApp.'):e.message,true);}
};
// A new e-mail is confirmed with the code sent to it before the account changes.
let troca=null, trocaTimer=null;

View File

@@ -118,9 +118,18 @@ function invalidaItemAtual(){
pintaPedido();
}
function itemPodeEnviar(item){
if(semMargem(item)) return false;
return item.qualityStatus==='ok' || item.qualityStatus==='unverified' ||
(item.qualityStatus==='warning' && item.qualityAcknowledged===true);
}
// Uma folha pronta guardada no carrinho antes dos 8 mm entre as cópias
// (27/11/2026): o servidor a recusa no pagamento, então o carrinho diz já,
// no próprio item, para refazê-lo (Sentry DTF-WEB-22).
function semMargem(item){
if(!['file','uvfile','premium'].includes(item.modo) || !item.production?.placements) return false;
const ps=[...item.production.placements].sort((a,b)=>a.y_cm-b.y_cm);
return ps.some((p,i)=>i>0 && p.y_cm < ps[i-1].y_cm+ps[i-1].length_cm+MARGEM_FOLHA_CM-0.02);
}
// Os itens marcados no carrinho são os que vão para o pagamento; um item
// desmarcado fica guardado para depois. O item aberto no produto sempre vai.
function itensAPagar(){
@@ -176,7 +185,7 @@ function aplicaTratamento(aPagar){
document.querySelectorAll('[data-ajuste],[data-ajustea]').forEach(el=>{el.checked=true;});
}
check.checked=ajusteTudo;check.disabled=true;
mostraAvisoTratamento('Sua arte tem nota '+worst+': para imprimir com qualidade, o Ajuste Fino é obrigatório neste pedido.');
mostraAvisoTratamento('Sua arte está abaixo da resolução mínima, então o Ajuste Fino é obrigatório neste pedido.');
}else{
check.checked=ajusteTudo;check.disabled=false;mostraAvisoTratamento('');
}
@@ -209,7 +218,8 @@ function pintaPedido(){
' aria-label="Incluir '+escapeHTML(it.tit)+' no pagamento"></label>'+
'<span class="miniItem">'+(it.mini ? '<img src="'+escapeHTML(it.mini)+'" alt="">' : '<i>'+escapeHTML(it.ext||'')+'</i>')+
(it.arquivos>1 ? '<em>+'+(it.arquivos-1)+'</em>' : '')+'</span>'+
'<div class="nm2"><b>'+escapeHTML(it.tit)+'</b><span>'+escapeHTML(it.desc)+'</span></div>'+
'<div class="nm2"><b>'+escapeHTML(it.tit)+'</b><span>'+escapeHTML(it.desc)+'</span>'+
(semMargem(it)?'<span class="avisoF">O espaço entre as cópias passou a ser de 8 mm. Remova este item e adicione a folha de novo.</span>':'')+'</div>'+
'<div class="vl2">'+rs(it.total)+'</div>'+
'<button type="button" class="x" data-rmi="'+i+'" aria-label="Remover '+escapeHTML(it.tit)+'">'+icone('lixeira')+'<span>Remover</span></button></div>').join('');
$('itens').querySelectorAll('[data-sel]').forEach(c=>c.addEventListener('change',()=>{
@@ -232,8 +242,8 @@ function pintaPedido(){
// The whole order waits 48 h when any art was sent to Redesenho, else 24 h.
const prazoTratamento=document.querySelector('#tratamentoBox .provaOp span');
if(prazoTratamento) for(const no of prazoTratamento.childNodes)
if(no.nodeType===3) no.textContent=no.textContent.replace(/aumenta em \d+ h/,
'aumenta em '+(artesRedesenho>0?48:24)+' h');
if(no.nodeType===3) no.textContent=no.textContent.replace(/leva \d+ h a mais/,
'leva '+(artesRedesenho>0?48:24)+' h a mais');
const soma = itens + frete + tratamento + redesenho;
const n = aPagar.length, noCarrinho = pedido.length + (itemAtual?1:0);
$('resLin').innerHTML =
@@ -247,6 +257,8 @@ function pintaPedido(){
' · +24 h</span><b>'+rs(tratamento)+'</b></div>':'')+
(redesenho?'<div class="l"><span>Ajuste Fino Redesenho · '+artesRedesenho+
(artesRedesenho===1?' arte':' artes')+' · +48 h</span><b>'+rs(redesenho)+'</b></div>':'')+
($('fProva')?.checked?'<div class="l"><span>Prova antes de imprimir</span>'+
'<b><span style="color:var(--verde-ml)">Grátis</span></b></div>':'')+
'<div class="l"><span>Revisão e reencaixe</span>'+
'<b><span style="color:var(--verde-ml)">Grátis</span></b></div>';
$('carrTot').textContent=rs(soma);
@@ -258,9 +270,12 @@ function pintaPedido(){
: n>1
? 'Pagar os '+n+' itens de uma vez'
: 'Ir para o pagamento';
// The proof is only for orders above 10 m (Dropstar, 2026-10-28): below it the box is gone.
// The proof is only for orders above 10 m (Dropstar, 2026-10-28; the server's
// PROOF_ABOVE_METRES). Below it the box stays, closed, and says the rule
// (Rodada 5, B3).
const prova=$('fProva');
if(prova){ const longo=aPagar.reduce((t,it)=>t+(it.cob||0),0)>10; prova.closest('.cxE').hidden=!longo; if(!longo) prova.checked=false; }
if(prova){ const longo=aPagar.reduce((t,it)=>t+(it.cob||0),0)>10;
prova.disabled=!longo; if(!longo) prova.checked=false; $('provaMin').hidden=longo; }
$('bPagar').disabled = !cartPodeEnviar() || !entrega.cotado || !clienteOk() || !enderecoOk() || falta>0;
if(pedido.length || itemAtual) $('carr').classList.add('on');
if($('cartN')){ $('cartN').textContent=noCarrinho>99?'99+':noCarrinho; $('cartN').hidden=!noCarrinho;
@@ -272,7 +287,8 @@ function pintaPedido(){
// A arte avulsa como fonte da montagem: largura, comprimento, cópias e giro.
const fonteDaArte=x=>({kind:'artwork',width_cm:x.cm,length_cm:+(x.cm*propDe(x)).toFixed(4),
copies:x.q,rotation_degrees:x.giro||0,mirrored:!!x.esp,
measurement:(x.src||x.semPrevia)?'file':'customer'});
measurement:(x.src||x.semPrevia)?'file':'customer',
...(x.cmSalvo?{saved_width_cm:x.cmSalvo,saved_dpi:x.dpiSalvo}:{})});
function carrinho(){
const cob=cobrarMontagem();
const extra=folhaManual()? TAXA_MANUAL : 0;
@@ -285,8 +301,8 @@ function carrinho(){
$('carr').classList.add('on');
let l='<div class="l"><span>'+MODOS[modo].tit+'</span><b>'+rs(base)+'/m</b></div>';
if(!ehFolha()) l += '<div class="l" style="color:#8D9AB0"><span>'+(montagemFolhas?'Montagem em '+montagemFolhas.length+' folhas, pela espessura do traço':'Montagem da folha')+'</span><b>inclusa</b></div>';
if(extra) l += '<div class="l"><span>Arquivo aberto na mão</span><b>+'+rs(extra)+'/m</b></div>';
l += '<div class="l"><span>Metragem'+(sobra>0.001?' · arredondada para 10 cm':'')+
if(extra) l += '<div class="l"><span>Abertura manual do arquivo</span><b>+'+rs(extra)+'/m</b></div>';
l += '<div class="l"><span>Metragem'+(sobra>0.001?' · a cada 10 cm':'')+
'</span><b>'+fmtM(cob)+' m</b></div>';
l += '<div class="l"><span>Preço final do metro</span><b>'+rs(unit)+'</b></div>'+
'<div class="l" style="color:var(--laranja2)"><span>Revisão e reencaixe</span><b>grátis</b></div>';
@@ -363,6 +379,7 @@ function avisaDesfazer(texto,acao){
function fechaDesfazer(){ clearTimeout(desfazerTimer); desfazerAcao=null; $('desfazer').hidden=true; }
addEventListener('dtf-page-changed',fechaDesfazer);
$('desfazerBtn').addEventListener('click',()=>{ const acao=desfazerAcao; fechaDesfazer(); if(acao) acao(); });
$('fProva')?.addEventListener('change',()=>pintaPedido());
$('fTratamento')?.addEventListener('change',()=>{
if($('fTratamento').checked){ ajusteTudo=true; limpaRedesenho(); }
else limpaAjuste();

View File

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

View File

@@ -206,11 +206,16 @@ function faltaLeitura(l){
return s<10 ? 'faltam '+Math.max(1,Math.ceil(s))+' s' : s<60 ? 'faltam cerca de '+Math.ceil(s/5)*5+' s' : 'faltam cerca de '+duracao(s);
}
const larguraFilme=()=>MODOS[modo].larg;
// cobrança proporcional: arredonda para cima em 10 cm · 2,75 m vira 2,80 m
const cobrar=m=>Math.max(MINIMO_M, Math.ceil(m*10)/10);
// Cobrança a cada 10 cm, com 8 mm a favor do cliente (Marcus, 27/11/2026):
// passou até 8 mm de um múltiplo de 10 cm, fica nele; passou mais, vai para o
// próximo. 2,75 m vira 2,80 m; 6,005 m fica 6,00 m. A mesma regra do servidor
// (app/core/pricing.py billed_length).
const TOLERANCIA_M=0.008;
const arredonda10=m=>Math.max(0.1, Math.ceil(+((m-TOLERANCIA_M)*10).toFixed(6))/10);
const cobrar=m=>Math.max(MINIMO_M, arredonda10(m));
// Com as artes em folhas separadas por traço (item 17), cada folha arredonda
// a 10 cm e o mínimo de 1 m vale para a soma: o cliente não escolheu separar.
const cobrarFolhas=fs=>Math.max(MINIMO_M, +fs.reduce((t,f)=>t+Math.ceil(+(f.alturaCm/100).toFixed(4)*10)/10,0).toFixed(1));
const cobrarFolhas=fs=>Math.max(MINIMO_M, +fs.reduce((t,f)=>t+arredonda10(+(f.alturaCm/100).toFixed(4)),0).toFixed(1));
const cobrarMontagem=()=>!ehFolha() && montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(metros);
const fmtM=m=>m.toFixed(2).replace('.',',');
const cls=n=>n>=85?'ok':n>=50?'av':'er';
@@ -218,3 +223,7 @@ const dpiDe=a=>a.cm>0? (a.giro?a.py:a.px)/(a.cm/2.54) : 0;
// girar 90° inverte a proporção · espelhar não muda medida, só o desenho
const propDe=a=>{ const p=a.prop||1; return a.giro? 1/p : p; };
const TAMANHOS={57:[10,15,20,25,28.2], 27:[5,8,10,13,26.7]};
// "12x nome.png" já entra com 12 cópias (Rodada 5, B6; a BinnFlow faz assim):
// até 3 dígitos, um x e um separador, para "1920x1080.png" não virar cópias.
const copiasDoNome=nome=>{ const m=/^(\d{1,3})\s*[xX×][\s_-]+\S/.exec(nome||'');
return m? Math.max(1,Math.min(200,+m[1]||1)) : 1; };

View File

@@ -13,8 +13,8 @@ $('qOk').addEventListener('click',()=>{
if($('qOk').disabled) return;
if(!$('prev').classList.contains('on')){ adicionaAoCarrinho(); return; }
const ok=$('ciente').classList.contains('on');
qm(ok? '<b>Registrado.</b> Você confirmou que viu a ressalva de resolução.'
: '<b>Certo.</b> Confira a folha montada abaixo.','var(--tx)');
qm(ok? '<b>Ressalva aceita.</b> Confira a folha montada abaixo.'
: 'Confira a folha montada abaixo.','var(--tx)');
$('prev').scrollIntoView({behavior:'smooth',block:'start'});
});

View File

@@ -95,8 +95,8 @@ function recusaFolha(x, md){
folhas=folhas.filter(y=>y!==x);
pintaFolha();
avisoTipo('<b>'+escapeHTML(arquivo.name)+' não é uma folha montada.</b> '+
'Para ocupar os '+n1(larguraFilme())+' cm do filme ela teria só '+md.dpiFolha+
' DPI, e o mínimo para imprimir é '+DPI_RECUSA+'. '+
'Nos '+n1(larguraFilme())+' cm do filme ela teria só '+md.dpiFolha+
' DPI, abaixo do mínimo de '+DPI_RECUSA+'. '+
'Se for uma arte para montarmos, use <b>'+MODOS[destino].tit+'</b>, '+
'a '+rs(PRECO[destino])+' o metro. '+
'<button type="button" id="usarAvulsa">Enviar como '+MODOS[destino].tit.toLowerCase()+'</button>');

View File

@@ -90,7 +90,7 @@ function desenhaMontagem(area,lista,mts,W,fora,aoTerminar){
if(fora) fora.innerHTML='';
if(!itens.length){
area.innerHTML='<div class="semmont"><b>A montagem aparece aqui</b>'+
'<span>informe a largura de cada arte e a folha se desenha sozinha</span></div>';
'<span>informe a largura de cada arte para montar a folha</span></div>';
if(aoTerminar) aoTerminar({alturaCm:0, uso:0, girou:0});
return;
}
@@ -148,8 +148,8 @@ function desenhaMontagem(area,lista,mts,W,fora,aoTerminar){
el.className = uso>=70? 'usoBom' : 'usoRuim';
el.innerHTML = (uso>=70
? '<b>'+uso+'% da folha virou arte</b> bom aproveitamento'
: '<b>'+uso+'% da folha virou arte</b> dá para melhorar: artes de larguras parecidas '+
'se encaixam melhor lado a lado')
: '<b>'+uso+'% da folha virou arte</b> artes de larguras parecidas '+
'encaixam melhor lado a lado')
+ (girou? ' · <b style="display:inline">'+girou+
(girou>1?' artes giradas':' arte girada')+' 90°</b> para caber melhor':'');
(fora||area).appendChild(el);
@@ -208,9 +208,9 @@ function previaAoVivo(){
? medidas.length+' folhas · '+fmtM(tot)+' m'
: n1(medidas[0].med.larg)+' × '+n1(medidas[0].med.alt)+' cm')+'</b>'+
'<span>'+(medidas.length>1? 'medidas lidas de cada arquivo' : medidas[0].med.fonte)+
' · vão para a máquina do jeito que você montou</span></div>'
' · imprimimos como você montou</span></div>'
: '<div class="semmont"><b>Sua folha aparece aqui</b>'+
'<span>a medida é lida do próprio arquivo, não do peso dele</span></div>';
'<span>lemos a medida do próprio arquivo</span></div>';
}
return;
}
@@ -257,7 +257,7 @@ function montaFolhasDeTraco(grupos,W){
figura.append(legenda,desenho); painel.append(figura);
desenhaMontagem(desenho, lista, 0, W, uso, r=>{
if(area.montagemVersao!==versao) return; // a montagem mudou nesse meio-tempo
legenda.textContent='Folha '+(i+1)+' · '+NOMES_TRACO[i]+' · '+fmtM(Math.ceil(+(r.alturaCm/100).toFixed(4)*10)/10)+' m';
legenda.textContent='Folha '+(i+1)+' · '+NOMES_TRACO[i]+' · '+fmtM(arredonda10(+(r.alturaCm/100).toFixed(4)))+' m';
feitas[i]={nome:NOMES_TRACO[i], artes:lista, alturaCm:r.alturaCm, folgaCm:r.folgaCm ?? MARGEM_CM,
layout:r.placements ? {height_cm:+r.alturaCm.toFixed(4), placements:r.placements} : null};
if(feitas.filter(Boolean).length<grupos.length) return;
@@ -273,19 +273,6 @@ function montaFolhasDeTraco(grupos,W){
area.replaceChildren(painel);
}
function motivoNota(){
if(!nota) return 'sem nota ainda · a conferência roda na sala antes de imprimir';
if(!ehFolha()){
const ruins=artes.filter(a=>a.cm>0 && dpiDe(a)<300);
if(!ruins.length) return 'nota '+nota+' · todas as artes em 300 DPI ou mais';
const pior=ruins.reduce((p,a)=>dpiDe(a)<dpiDe(p)?a:p);
return 'nota '+nota+' · '+ruins.length+(ruins.length>1?' artes abaixo':' arte abaixo')+
' de 300 DPI · a menor é "'+pior.f.name+'" com '+
Math.round(dpiDe(pior))+' DPI em '+pior.cm.toFixed(1).replace('.',',')+' cm';
}
return nota>=90 ? 'nota '+nota+' · resolução ótima em toda a folha'
: 'nota '+nota+' · a resolução é o único ponto — o resto corrigimos por você';
}
function previa(){
const T=window.dtfTimings;
if(T && T.montageStart!=null && T.montageEnd==null) T.montageEnd=performance.now();
@@ -301,12 +288,11 @@ function previa(){
['var(--verde)','✓','Espaço entre artes', montagemFolgaCm>=MARGEM_CM-1e-9
? '5 mm entre as artes e nas bordas'
: n1(montagemFolgaCm*10)+' mm · 5 mm não cabem na largura, a sobra fica dividida por igual'],
['var(--verde)','✓','Metragem proporcional',
'sua folha tem '+fmtM(metros)+' m e você paga '+fmtM(cob)+
' m · arredondamos só até os 10 cm mais próximos'],
['var(--verde)','✓','Metragem',
'sua folha tem '+fmtM(metros)+' m e você paga '+fmtM(cob)+' m · cobramos a cada 10 cm'],
];
linhas.push(['var(--verde)','+','Identificação do pedido',
'aplicamos seu nome e o número do pedido no fim da folha · por nossa conta']);
'seu nome e o número do pedido no fim da folha, sem custo']);
$('pInfo').innerHTML=linhas.map(l=>
'<div class="li"><span class="c" style="background:'+l[0]+
(l[0]==='var(--laranja)'?';color:#241703':'')+'">'+l[1]+'</span>'+
@@ -315,5 +301,5 @@ function previa(){
$('pArea').innerHTML='<div class="carregando">montando a prévia…</div>';
try{ previaArtes(); }
catch(e){ $('pArea').innerHTML='<div class="semprev"><b>Prévia indisponível</b>'+
'O arquivo será processado normalmente.</div>'; }
'O pedido segue normalmente.</div>'; }
}

View File

@@ -192,6 +192,30 @@ async function dimensoesImagem(file){
}
return null;
}
// The PNG may record its own resolution in the pHYs chunk. A loose art that
// says 200 DPI or more has a real size in pixels ÷ DPI, offered as "Manter";
// below 200 DPI, or without the chunk, it says nothing. Never throws.
async function dpiSalvoPng(file){
try{
if(!file || !(file.size>0)) return null;
const b=new Uint8Array(await file.slice(0,Math.min(file.size,4*1048576)).arrayBuffer());
if(!(b.length>=8 && b[0]===0x89 && b[1]===0x50 && b[2]===0x4E && b[3]===0x47)) return null;
const u32=i=>((b[i]<<24)>>>0)+(b[i+1]<<16)+(b[i+2]<<8)+b[i+3];
let i=8;
while(i+12<=b.length){
const len=u32(i), tipo=String.fromCharCode(...b.slice(i+4,i+8));
if(tipo==='pHYs'){
if(len<9 || i+8+len>b.length) return null;
const ppmX=u32(i+8), ppmY=u32(i+12), unidade=b[i+16];
if(unidade===1 && ppmX>0 && ppmX===ppmY) return Math.round(ppmX*0.0254);
return null;
}
if(tipo==='IDAT' || tipo==='IEND') return null;
i+=12+len;
}
return null;
}catch(e){ return null; }
}
// A small copy of a large PNG, read as a stream: the file is inflated in
// pieces and only every n-th pixel of every n-th row is kept, so memory stays
// at a few MB whatever the file's size. It is the preview. Given the sheet's
@@ -378,29 +402,29 @@ function medirFolha(file){
verbosity:0}).promise;
if(doc.numPages!==1)
return {rejected:true, reason:'O PDF tem '+doc.numPages+
' páginas. Envie cada folha como um PDF de uma página para calcular o preço correto.'};
' páginas. Envie cada folha como um PDF de uma página.'};
const page=await doc.getPage(1);
const view=page.view, unit=page.userUnit, vp=page.getViewport({scale:1});
if(!Array.isArray(view) || view.length!==4 ||
!Number.isFinite(unit) || unit<=0 ||
!Number.isFinite(vp.width) || !Number.isFinite(vp.height) ||
vp.width<=0 || vp.height<=0)
return {rejected:true, reason:'Não conseguimos determinar o tamanho desta página PDF. Exporte-a novamente.'};
return {rejected:true, reason:'Não conseguimos ler o tamanho desta página. Exporte o PDF de novo.'};
const ptW=Math.abs(view[2]-view[0]), ptH=Math.abs(view[3]-view[1]);
if(!(ptW>0 && ptH>0) ||
(unit===1 && (ptW>PDF_MAX_PT || ptH>PDF_MAX_PT)))
return {rejected:true, reason:'A página passa do limite de 508 cm sem UserUnit. Divida a folha ou exporte em PNG.'};
return {rejected:true, reason:'A página passa de 508 cm e não tem UserUnit. Divida a folha ou exporte em PNG.'};
// This pinned PDF.js build exposes the page's rotated view in points;
// userUnit is separate and must scale both physical dimensions.
const w=vp.width*unit*PT_CM, h=vp.height*unit*PT_CM;
if(!Number.isFinite(w) || !Number.isFinite(h) || w<=0 || h<=0 || h>6000)
return {rejected:true, reason:'O tamanho desta página PDF não é suportado. Divida a folha em partes menores.'};
return {rejected:true, reason:'Esta página é grande demais. Divida a folha em partes menores.'};
// Keep precise geometry for the fit and quote; the UI rounds only
// when displaying dimensions.
return {larg:+w.toFixed(3), alt:+h.toFixed(3),
fonte:'página do PDF'+(unit!==1 ? ' · UserUnit '+unit : '')};
}).then(res).catch(()=>res({rejected:true,
reason:'Não conseguimos ler este PDF. Exporte-o novamente como PDF de uma página ou PNG.'}))
reason:'Não conseguimos ler este PDF. Exporte de novo como PDF de uma página ou PNG.'}))
.finally(()=>{ if(doc) doc.destroy().catch(()=>{}); });
return;
}
@@ -463,7 +487,7 @@ function chipsDaFolha(a,aceito){
return dpi+chip('ok','Fundo transparente')+
(a.residuos? chip(aceito?'av':'er',a.residuos+' resíduo'+(a.residuos>1?'s':'')+(aceito?' aceito'+(a.residuos>1?'s':''):''))
: chip('ok','Sem resíduos'))+
(a.encostadas? chip('fix',a.encostadas+' peças coladas · separamos grátis') : chip('ok','Peças separadas'));
(a.encostadas? chip('fix',a.encostadas+' peças coladas · separamos sem custo') : chip('ok','Peças separadas'));
}
// Resíduo e fundo chapado barram o pedido (Dropstar, 21/10/2026): o texto diz
// quantos pontos, onde estão e o que fazer, sem "arquivo com problema". O
@@ -471,20 +495,20 @@ function chipsDaFolha(a,aceito){
function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
if(a.grande) return '';
if(a.fundoChapado) return /\.jpe?g$/i.test(nome||'')
? '<p class="avisoF"><b>JPG não tem fundo transparente.</b> O que parece branco na tela sai branco '+
'no filme. Exporte a folha em PNG ou PDF, com fundo transparente, e envie de novo.</p>'
: '<p class="avisoF"><b>O fundo da sua folha não é transparente.</b> O que parece branco na tela sai '+
'branco no filme. Exporte a folha com fundo transparente, em PNG ou PDF, e envie de novo.</p>';
? '<p class="avisoF"><b>JPG não tem fundo transparente.</b> O fundo sai branco no filme. '+
'Exporte em PNG ou PDF com fundo transparente e envie de novo.</p>'
: '<p class="avisoF"><b>O fundo da sua folha não é transparente.</b> Ele sai impresso no filme. '+
'Exporte com fundo transparente, em PNG ou PDF, e envie de novo.</p>';
if(!a.residuos) return '';
const n=a.residuos, varios=n>1;
const aceite='<label class="aceiteRes"><input type="checkbox" data-residuo="'+i+'"'+(aceito?' checked':'')+'>'+
'<span>Esses pontos fazem parte da arte. Li e concordo em imprimir assim — eles podem sair no recorte.</span></label>';
'<span>Esses pontos fazem parte da arte e podem sair impressos. Quero imprimir assim.</span></label>';
if(aceitavel && aceito) return aceite;
return '<p class="avisoF"><b>'+(varios?'Sobraram ':'Sobrou ')+n+(varios?' pontos':' ponto')+
' de recorte na sua folha.</b> São restos da remoção de fundo: não aparecem na sua tela, mas a '+
'impressora enxerga e imprime. Apague '+(varios?'os pontos':'o ponto')+' na ferramenta que você '+
'usou e envie de novo. '+(varios?'Os círculos vermelhos na prévia mostram onde estão.':'O círculo vermelho na prévia mostra onde está.')+
(aceitavel?' Se '+(varios?'os pontos são':'o ponto é')+' da própria arte, marque abaixo.</p>'+aceite:'</p>');
' de recorte na sua folha.</b> Não aparece'+(varios?'m':'')+' na tela, mas sai'+(varios?'em':'')+' impresso'+(varios?'s':'')+'. '+
(varios?'Os círculos vermelhos na prévia mostram onde estão':'O círculo vermelho na prévia mostra onde está')+
': apague e envie de novo.'+
(aceitavel?' Se '+(varios?'fazem':'faz')+' parte da arte, marque abaixo.</p>'+aceite:'</p>');
}
// Ajuste Fino (front 1a) and Ajuste Fino Redesenho (front 1b): under a Prumo
// warning, the customer may hand this art to the designer. One service per
@@ -511,21 +535,21 @@ function ajusteLinha(i,attr){
const marcado=ajusteTudo || !!x.ajuste;
linha+='<label class="aceiteRes ajusteArte"><input type="checkbox" '+attr+'="'+i+'"'+
(marcado?' checked':'')+'>'+
'<span>Quer que um designer resolva? <b>Ajuste Fino</b> — '+rs(TAXA_TRATAMENTO)+'</span></label>';
'<span><b>Ajuste Fino</b>: nosso designer ajusta esta arte por '+rs(TAXA_TRATAMENTO)+'</span></label>';
}
if(redesenhado){
const attrRedesenhado=folha?'data-redesenho':'data-redesenhoa';
linha+='<label class="aceiteRes ajusteArte"><input type="checkbox" '+attrRedesenhado+'="'+i+'"'+
(x.redesenho?' checked':'')+'>'+
'<span>Precisa redesenhar ou vetorizar? <b>Ajuste Fino Redesenho</b> — '+rs(TAXA_REDESENHO)+
' (com prévia, +48 h)</span></label>';
'<span><b>Ajuste Fino Redesenho</b>: redesenhamos ou vetorizamos esta arte por '+rs(TAXA_REDESENHO)+
', com prévia e 48 h a mais</span></label>';
}
return linha;
}
function detalhesDaFolha(a,i,aberto){
const linhas = a.grande
? ['Resolução '+a.dpi+' DPI, lida do arquivo',
'Arquivo grande: peças, resíduos e fundo são conferidos pela equipe']
'Arquivo grande: a equipe confere peças, resíduos e fundo']
: [a.artes+' peça'+(a.artes===1?'':'s')+' · '+a.aproveitamento+'% da folha com arte',
'Resolução '+a.dpi+' DPI · '+(a.fonteDpi==='imagens'? 'medida imagem por imagem dentro do PDF'
: a.fonteDpi==='vetor'? 'arte vetorial, sem imagem embutida' : 'lida do arquivo'),
@@ -568,20 +592,17 @@ function pintaFolha(){
// Over 150 MB the browser cannot check a PDF: said before payment, as
// for a file opened by hand (Dropstar, 2026-10-23).
(x.pdfGrande? '<span class="chipSo">Conferência manual · sem conferência no site</span>'+
'<p class="repTxt">Este PDF tem mais de 150 MB, e o site não confere arquivo desse tamanho: '+
'resíduo de recorte, fundo e resolução ficam para a equipe, que abre antes de imprimir, e o '+
'pedido pode voltar depois de pago. '+
'Exportando em <b>PNG</b>, ou num PDF menor, a conferência sai aqui, antes de pagar.</p>' : '')+
(suspeito? '<p class="avisoF"><b>Este PDF passa do tamanho que o formato comporta.</b> '+
'A especificação para em 508 cm e o seu tem '+n1(x.med.alt)+' cm. '+
'Ele abre certo só em quem o gerou — aqui vai precisar do Ajuste Fino. '+
'Manda em <b>PNG ou TIFF</b>, ou divide em partes de até 5 m, que sai na hora.</p>':'')+
(larga? '<p class="avisoF"><b>Esta folha não roda neste filme.</b> Ela tem '+n1(x.med.larg)+
' cm de largura e o filme aqui tem '+n1(L)+' cm. Não dá para reduzir: '+
'encolher a folha encolheria cada arte junto.'+
'<p class="repTxt">O site não confere PDF acima de 150 MB: a equipe confere antes de imprimir, '+
'e o pedido pode voltar depois de pago. '+
'Em <b>PNG</b> ou num PDF menor, a conferência sai aqui, antes de pagar.</p>' : '')+
(suspeito? '<p class="avisoF"><b>Este PDF passa de 508 cm, o limite do formato.</b> '+
'O seu tem '+n1(x.med.alt)+' cm e só abre certo no programa que o gerou, então precisaria do Ajuste Fino. '+
'Envie em <b>PNG ou TIFF</b>, ou divida em partes de até 5 m.</p>':'')+
(larga? '<p class="avisoF"><b>Esta folha não cabe neste filme.</b> Ela tem '+n1(x.med.larg)+
' cm de largura e o filme tem '+n1(L)+' cm. Reduzir a folha reduziria cada arte.'+
(x.med.larg<=57.5
? ' Ela cabe no <b>DTF têxtil de 57 cm</b> — troque de produto ali em cima.'
: ' Remonte a folha em '+n1(L)+' cm e suba de novo.')+'</p>':'');
? ' Ela cabe no <b>DTF têxtil de 57 cm</b>: troque de produto acima.'
: ' Remonte a folha em '+n1(L)+' cm e envie de novo.')+'</p>':'');
}else if(x.measurementError){
medida='<span class="repPeso">'+escapeHTML(extDe(x.f.name))+' · '+fmt(x.f.size)+'</span>'+
'<p class="avisoF"><b>Este arquivo não pode ser orçado.</b> '+escapeHTML(x.measurementError)+'</p>';
@@ -589,13 +610,13 @@ function pintaFolha(){
// Só a abertura manual muda o metro (TAXA_MANUAL); a nota não mexe no preço.
const dif=(x.m>0)? TAXA_MANUAL*cobrar(x.m*(x.rep||1)) : 0;
medida='<span class="chipSo">Conferência manual</span>'+
'<p class="repTxt">O navegador não abre '+escapeHTML(extDe(x.f.name))+', então alguém da equipe '+
'<p class="repTxt">O site não abre '+escapeHTML(extDe(x.f.name))+': a equipe '+
'confere antes de imprimir'+
(TAXA_MANUAL? ' e o metro sai a <b>'+rs(precoMetro()+TAXA_MANUAL)+'</b>, com <b>'+rs(TAXA_MANUAL)+
'</b> pela abertura manual' : '')+'. '+
'Exportando em <b>PNG ou PDF</b>, a conferência sai aqui, antes de pagar'+
'Em <b>PNG ou PDF</b>, a conferência sai aqui, antes de pagar'+
(TAXA_MANUAL? ', e o metro fica em <b>'+rs(precoMetro())+'</b>'+
(dif>0.5? ' — <b>'+rs(dif)+' a menos</b> só nesta folha' : '') : '')+'.</p>';
(dif>0.5? ' (<b>'+rs(dif)+' a menos</b> nesta folha)' : '') : '')+'.</p>';
manual='<div class="campo"><label for="comp'+i+'">Comprimento</label>'+
'<span class="un"><input type="number" id="comp'+i+'" min="0.5" max="60" step="0.01" data-comp="'+i+'" '+
'placeholder="0,00" value="'+(x.m? x.m.toFixed(2):'')+'"><i>m</i></span></div>';
@@ -605,8 +626,8 @@ function pintaFolha(){
'<span class="progT">'+textoProgresso(x)+'</span>'
: x.semAnalise
? '<div class="progF"><b>Não conseguimos conferir esta folha.</b> '+escapeHTML(x.semAnalise)+
'. A conferência será feita na sala. Para conferir a resolução aqui, exporte a mesma '+
'folha em <b>PNG</b>.</div>'
'. A equipe confere antes de imprimir. Para ver a resolução aqui, exporte '+
'em <b>PNG</b>.</div>'
: '';
// A small thumbnail made once: the list is rebuilt on every change, and the
// full preview of a file up to 150 MB would be re-parsed each time.
@@ -620,7 +641,12 @@ function pintaFolha(){
'<span class="passo"><button type="button" data-passo="-1" data-i="'+i+'" aria-label="Menos uma cópia">−</button>'+
'<input type="number" id="repf'+i+'" min="1" max="200" data-repf="'+i+'" value="'+x.rep+'">'+
'<button type="button" data-passo="1" data-i="'+i+'" aria-label="Mais uma cópia">+</button></span></div>'+
'<div class="conta">'+(x.rep>1? x.rep+' × '+fmtM(x.m)+' m = ' : '')+'<b>'+fmtM(sub)+' m</b></div>' : '')+
// A conta inteira, como é cobrada: o comprimento exato do arquivo e os
// 8 mm entre as cópias (Marcus, 27/11/2026: "falta explicar melhor").
'<div class="conta">'+(x.rep>1
? x.rep+' × '+n1(x.m*100)+' cm + '+(x.rep-1)+(x.rep>2?' espaços':' espaço')+' de 8 mm = <b>'+
n1(sub*100+(x.rep-1)*MARGEM_FOLHA_CM)+' cm</b>'
: '<b>'+n1(x.m*100)+' cm</b>')+'</div>' : '')+
'</div>' : '';
return '<div class="rep" data-folha="'+i+'">'+
'<div class="repTopo"><div class="miniF">'+mini+'</div><div class="repInfo">'+
@@ -719,7 +745,7 @@ function pintaArtes(){
}else if(a.decodeError){
aviso='<p class="avisoF"><b>Não conseguimos ler esta imagem.</b> Exporte novamente em PNG.</p>';
}else if(a.cm>larguraFilme()){
aviso='<p class="avisoF"><b>Largura maior que o filme.</b> O filme aqui tem '+n1(larguraFilme())+' cm.</p>';
aviso='<p class="avisoF"><b>Largura maior que o filme.</b> O filme tem '+n1(larguraFilme())+' cm.</p>';
}else if(a.cm>0 && (a.src||a.semPrevia)){
const dpi=Math.round(dpiDe(a));
medida='<b>'+n1(a.cm)+' × '+n1(a.cm*propDe(a))+' cm</b>';
@@ -733,8 +759,8 @@ function pintaArtes(){
? '<div class="dica av">Pequena para '+n1(a.cm)+' cm. Em '+DPI_AVISA+' DPI ela sai com até '+
n1(maxCm)+' cm, ou envie um arquivo maior.</div>'
: sug
? '<div class="dica">Com '+n1(sug.alvo)+' cm cabem '+sug.para+' por fileira e a folha encolhe '+
n1(sug.cm)+' cm.<button data-usar="'+i+'" data-cm="'+sug.alvo+'">Usar '+n1(sug.alvo)+' cm</button></div>'
? '<div class="dica">Com '+n1(sug.alvo)+' cm cabem '+sug.para+' por fileira e a folha fica '+
n1(sug.cm)+' cm menor.<button data-usar="'+i+'" data-cm="'+sug.alvo+'">Usar '+n1(sug.alvo)+' cm</button></div>'
: '';
}
// Item 4: the art's dots under 2 mm, with the same warning and acceptance as a sheet.
@@ -746,6 +772,12 @@ function pintaArtes(){
'A arte entra na folha pela medida, e a equipe confere antes de imprimir. Em PNG, a prévia aparece.</p>';
const mini = a.miniSrc ? '<img src="'+escapeHTML(a.miniSrc)+'" alt="">' : '<span>'+escapeHTML(extDe(a.f.name))+'</span>';
const sub = a.cm>0 && (a.src||a.semPrevia) ? (a.q>1? a.q+' × ' : '')+'<b>'+n1(a.cm)+' × '+n1(a.cm*propDe(a))+' cm</b>' : '';
// Girada, a largura na folha é a altura salva no arquivo.
const salvo = a.cmSalvo ? Math.round((a.giro? a.cmSalvo*(a.prop||1) : a.cmSalvo)*10)/10 : 0;
const manter = salvo && salvo<=larguraFilme()
? '<button class="tm'+(Math.abs(a.cm-salvo)<0.05?' on':'')+'" data-tam="'+i+'" data-t="'+salvo+'">'+
'Manter '+n1(salvo)+' × '+n1(salvo*propDe(a))+' cm</button>'
: '';
return '<div class="rep art2'+(a===recemChegada?' nova':'')+'" data-arte="'+i+'">'+
'<div class="repTopo"><div class="miniF">'+mini+'</div><div class="repInfo">'+
'<div class="l1"><b>'+escapeHTML(a.f.name)+'</b>'+(a===recemChegada?'<em class="novaT">nova</em>':'')+
@@ -767,7 +799,7 @@ function pintaArtes(){
'<button class="gr'+(a.giro?' on':'')+'" data-giro="'+i+'" title="Girar 90°" aria-label="Girar 90°">'+icone('girar')+'</button>'+
(espelhavel() ? '<button class="gr'+(a.esp?' on':'')+'" data-esp="'+i+'" title="Espelhar" aria-label="Espelhar">'+icone('espelhar')+'</button>' : '')+'</span>'+
(sub? '<div class="conta">'+sub+'</div>' : '')+
'<div class="atalhos">'+(TAMANHOS[larguraFilme()]||[]).map(t=>'<button class="tm'+
'<div class="atalhos">'+manter+(TAMANHOS[larguraFilme()]||[]).map(t=>'<button class="tm'+
(Math.abs(a.cm-t)<0.05?' on':'')+'" data-tam="'+i+'" data-t="'+t+'">'+n1(t)+' cm</button>').join('')+'</div>'+
'</div>'+
'</div>';

View File

@@ -21,13 +21,13 @@ const residuosAceitos=()=>ehFolha()
// no máximo 10% da tinta em traços de até 4 px.
const mista=t=>!!(t && t.px<=4 && t.largos>=0.6 && t.finos<=0.10);
const tracoDoArquivo=x=>ehFolha()?x.an&&x.an.traco:tracoDaArte(x);
const MISTA_BRANCO='O branco por baixo precisa de um ajuste para traço fino e outro para área chapada. '+
'Imprimindo assim, protegemos os traços e as áreas chapadas podem ganhar uma borda branca muito fina. ';
const TEXTO_MISTA={
arte:'Esta arte tem traços finos e áreas chapadas no mesmo arquivo. O branco por baixo precisa de ajuste diferente pra cada um. '+
'Vamos proteger os traços finos; as áreas chapadas podem mostrar uma borda branca muito fina. Quer evitar? Suba esta arte em dois '+
'arquivos, um com os traços finos e outro com as áreas chapadas; a gente monta cada um na folha certa. Pode dar alguns centímetros a mais de filme.',
folha:'Esta folha tem traços finos e áreas chapadas no mesmo arquivo. O branco por baixo precisa de ajuste diferente pra cada um. '+
'Vamos proteger os traços finos; as áreas chapadas podem mostrar uma borda branca muito fina. Quer evitar? Mande em duas folhas, '+
'uma com os traços finos e outra com as áreas chapadas. Pode dar alguns centímetros a mais de filme.'};
arte:MISTA_BRANCO+'Para evitar, suba em dois arquivos: um com os traços finos, outro com as áreas chapadas. '+
'Montamos cada um na folha certa, com alguns centímetros a mais de filme.',
folha:MISTA_BRANCO+'Para evitar, envie em duas folhas: uma com os traços finos, outra com as áreas chapadas. '+
'Pode usar alguns centímetros a mais de filme.'};
// O aviso não barra e aparece uma vez por arquivo, na folha pronta e na arte
// avulsa: imprimir assim mesmo (C1), ou trocar o arquivo por dois.
function perguntaMista(){
@@ -117,9 +117,9 @@ function avaliar(){
const ausentes=folhas.filter(f=>!f.an);
const exts=[...new Set(ausentes.map(f=>extDe(f.f.name)))].join(', ');
mostraNota([
['av','Conferência manual · '+exts+' sem análise completa',
ausentes.length+' de '+folhas.length+' folha(s) precisam de conferência manual'],
['fix','Alguém abre seu arquivo','a conferência é feita na mão, na sala']
['av','Conferência manual · '+exts,
ausentes.length+' de '+folhas.length+' folha(s) sem conferência automática'],
['fix','Conferimos manualmente','antes de imprimir']
], 0, folhas.length>1? folhas.length+' folhas' : folhas[0].f.name,
larguraFilme()+' cm · '+fmtM(metros)+' m');
return {pronto:true};
@@ -134,7 +134,7 @@ function avaliar(){
ans.some(a=>a.fonteDpi==='imagens')
? 'média por área das imagens dentro do PDF · pior em '+
Math.min(...ans.map(a=>a.res? a.res.pior : a.dpi))+' DPI'
: 'resolução do arquivo · arte ampliada antes de exportar não aparece aqui'],
: 'resolução do arquivo · não mostra arte ampliada antes de exportar'],
ans.some(a=>a.grande) ? ['ok','Arquivo grande','peças, resíduos e fundo conferidos pela equipe'] : null,
ans.some(a=>a.grande) ? null : ['ok', soma('artes')+' peças na folha',
Math.round(soma('aproveitamento')/ans.length)+'% da folha virou arte'],
@@ -156,7 +156,7 @@ function avaliar(){
const grande=artes.find(a=>a.lendo!=null);
if(grande) return {pronto:false, falta:'Gerando a prévia das artes grandes… · '+segundosDesde(grande.analiseInicio)+' s'};
if(artes.some(a=>a.decodeError || !(a.src||a.semPrevia) || !(a.px>0) || !(a.py>0)))
return {pronto:false, falta:'Não conseguimos ler uma das imagens. Exporte-a novamente em PNG antes de continuar.'};
return {pronto:false, falta:'Não conseguimos ler uma das imagens. Exporte de novo em PNG.'};
if(artes.some(a=>!Number.isFinite(a.cm) || a.cm>larguraFilme()))
return {pronto:false, falta:'A largura da arte precisa caber no filme de '+
n1(larguraFilme())+' cm. Reduza a medida solicitada antes de continuar.'};
@@ -178,7 +178,7 @@ function avaliar(){
const notas=artes.map(a=>Math.max(6,Math.min(100,Math.round(dpiDe(a)/DPI_AVISA*100))));
const media=Math.round(notas.reduce((s,n)=>s+n,0)/notas.length), pior=Math.min(...notas);
mostraNota([
['ok','Montagem por nossa conta','5 mm garantidos'],
['ok','Montagem inclusa','5 mm entre as artes'],
[cls(pior),'Resolução das artes',pior>=85?'todas em boa resolução':'há arte abaixo da resolução ideal']
],media,artes.length+' arte'+(artes.length>1?'s':''),
'folha montada por nós · '+fmtM(metros)+' m');
@@ -197,8 +197,8 @@ function agendaAvaliacao(){
if(!el) return;
if(r.pronto){
el.className='aoVivo pronto';
el.innerHTML='<span class="pt2"></span><span><b>Conferência e preço calculados.</b> '+
'Confira abaixo e feche o pedido.</span>';
el.innerHTML='<span class="pt2"></span><span><b>Conferência e preço prontos.</b> '+
'Confira abaixo e adicione ao carrinho.</span>';
}else{
el.className='aoVivo';
el.innerHTML='<span class="pt2"></span><span>'+escapeHTML(r.falta)+'</span>';
@@ -258,16 +258,16 @@ function ressalvaResolucao(){
// e não existe aceite que destrave.
if(recusadas.length){
$('cienteTxt').innerHTML=
'<p><b>A média da folha ficou abaixo de '+DPI_RECUSA+' DPI.</b> Nesse ponto a peça '+
'sai serrilhada a ponto de não valer o filme. Reenvie maior ou reduza a largura.</p>'+
'<div class="lista">'+recusadas.map(b=>'<div><b>'+escapeHTML(b.nome)+'</b> — '+
'<p><b>'+(recusadas.length>1?recusadas.length+' artes ficaram':'Uma arte ficou')+' abaixo de '+DPI_RECUSA+' DPI.</b> Não imprimimos assim: '+
'sai serrilhado demais. Envie em resolução maior ou reduza a largura.</p>'+
'<div class="lista">'+recusadas.map(b=>'<div><b>'+escapeHTML(b.nome)+'</b>: '+
(b.quantas
? 'média de '+b.dpi+' DPI · pior imagem em '+b.pior+' DPI · '+b.quantas+
' de '+b.de+' imagens abaixo de '+DPI_RECUSA+' DPI, cobrindo '+b.parte+'% da arte'
: b.dpi+' DPI em '+n1(b.cm)+' cm · precisa de '+
Math.ceil(DPI_AVISA*b.cm/2.54)+' px de largura')+'</div>')
.join('')+'</div>';
$('cienteTit').textContent='Resolução abaixo do que imprimimos';
$('cienteTit').textContent='Resolução baixa demais para imprimir';
box.className='ciente on recusa'; chk.checked=false; $('qOk').disabled=true;
return;
}
@@ -280,9 +280,9 @@ function ressalvaResolucao(){
const media=Math.round(baixas.reduce((s,b)=>s+b.dpi,0)/baixas.length);
$('cienteTxt').innerHTML=
'<p><b>Parte da arte está abaixo de '+DPI_AVISA+' DPI.</b> Essas peças podem sair '+
'com traço serrilhado, e isso não tem conserto depois de impresso. '+
'serrilhadas, sem conserto depois de impressas. '+
'O resto da folha sai normal.</p>'+
'<div class="lista">'+baixas.map(b=>'<div><b>'+escapeHTML(b.nome)+'</b> — '+
'<div class="lista">'+baixas.map(b=>'<div><b>'+escapeHTML(b.nome)+'</b>: '+
(b.quantasAviso
? 'média de '+b.dpi+' DPI · '+b.quantasAviso+' de '+b.de+' imagens abaixo de '+
DPI_AVISA+' DPI, cobrindo '+b.parteAviso+'% da arte'+

View File

@@ -21,7 +21,7 @@
aviso.style.cssText='position:fixed;left:12px;right:12px;bottom:12px;z-index:9999;padding:14px 16px;border-radius:10px;'+
'background:#1f1f1f;color:#fff;font:15px/1.4 system-ui,sans-serif;display:flex;gap:12px;align-items:center;justify-content:space-between';
const texto=document.createElement('span');
texto.textContent='Uma parte do site não carregou, provavelmente a conexão oscilou. Atualize a página para continuar.';
texto.textContent='Uma parte do site não carregou. Atualize a página para continuar.';
const botao=document.createElement('button');
botao.type='button'; botao.textContent='Atualizar';
botao.style.cssText='flex:none;padding:8px 14px;border:0;border-radius:8px;background:#F28C1E;color:#111;font-weight:700';

View File

@@ -36,18 +36,17 @@ function recusa(lista){
el.style.display='block';
if(lista.every(f=>/\.jpe?g$/i.test(f.name))){
const disfarcados=lista.filter(f=>f.nomeEnviado).map(f=>f.nomeEnviado);
el.innerHTML='<b>JPG não dá para enviar.</b> '+
el.innerHTML='<b>JPG não entra.</b> '+
(disfarcados.length ? escapeHTML(disfarcados.join(', '))+' é JPG, mesmo com outro nome. ' : '')+
'JPG não tem fundo transparente, e o branco do fundo '+
'sai no filme. Exporte em '+(ehFolha()?'PNG ou PDF':'PNG')+' com fundo transparente e envie de novo.';
'JPG não tem fundo transparente, e o fundo '+
'sai branco no filme. Exporte em '+(ehFolha()?'PNG ou PDF':'PNG')+' com fundo transparente e envie de novo.';
return;
}
el.innerHTML = ehFolha()
? '<b>'+exts+' não dá para enviar aqui.</b> A folha pronta aceita PNG, PDF, TIFF, '+
? '<b>'+exts+' não entra aqui.</b> A folha pronta aceita PNG, PDF, TIFF, '+
'PSD, AI e CDR, com fundo transparente.'
: '<b>'+exts+' não dá para enviar aqui.</b> Artes avulsas precisam de PNG com '+
'fundo transparente — é o que a montagem enxerga para encaixar. '+
'Se o seu arquivo é CDR, AI ou PSD, exporte em PNG ou use <b>Arquivo por metro</b>.';
: '<b>'+exts+' não entra aqui.</b> Artes avulsas só aceitam PNG com '+
'fundo transparente. Para CDR, AI ou PSD, exporte em PNG ou use <b>Arquivo por metro</b>.';
}
const Z=$('zona'), I=$('inp');
Z.addEventListener('click',()=>I.click());
@@ -188,7 +187,7 @@ async function sel(fs){
// On their way at once; a JPG is refused at the order anyway.
fs.filter(f=>!/\.jpe?g$/i.test(f.name)).forEach(f=>window.dtfEnvio?.enviar(f));
if(ehFolha()){
const novas=fs.map(f=>({f, med:null, rep:1, m:0, corte:null, semAnalise:null, analiseInicio:Date.now()}));
const novas=fs.map(f=>({f, med:null, rep:copiasDoNome(f.name), m:0, corte:null, semAnalise:null, analiseInicio:Date.now()}));
folhas=folhas.concat(novas); // soma, não substitui
pintaFolha();
novas.forEach(x=>{
@@ -261,7 +260,7 @@ async function sel(fs){
rasterizarPdf(x.f, md.larg, md.alt, true).then(r=>{
if(r && r.erro){
x.semAnalise = r.erro + (r.semWorker
? ' · este navegador não deixa o leitor rodar em segundo plano'
? ' · o navegador bloqueou a leitura em segundo plano'
: '');
}
if(r && r.tela && r.mapa){
@@ -283,7 +282,7 @@ async function sel(fs){
});
return;
}
const novos=fs.map(f=>({f,px:0,py:0,cm:0,q:1,prop:1,giro:0,esp:false,analiseInicio:Date.now()}));
const novos=fs.map(f=>({f,px:0,py:0,cm:0,q:copiasDoNome(f.name),prop:1,giro:0,esp:false,analiseInicio:Date.now()}));
artes=novos.concat(artes); // a mais recente fica no topo da fila
recemChegada=novos[0];
pintaArtes();
@@ -297,6 +296,11 @@ function medir(a){
return dimensoesImagem(a.f).then(async d=>{
if(!d || !(d.w>0) || !(d.h>0)){ a.decodeError=true; return a; }
a.px=d.w; a.py=d.h; a.prop=d.h/d.w; a.grande=true;
a.dpiSalvo=await dpiSalvoPng(a.f);
if(a.dpiSalvo>=200){
a.cmSalvo=Math.round(a.px/a.dpiSalvo*2.54*10)/10;
if(a.cmSalvo>=1 && a.cmSalvo<=larguraFilme() && !a.cm) a.cm=a.cmSalvo;
}
// WebP cannot be read in parts (JPG is refused): the art is placed by its
// measurements, as a full box, and the team checks it before printing.
if(!/\.png$/i.test(a.f.name)){ a.semPrevia=true; return a; }
@@ -316,7 +320,13 @@ function medir(a){
}).catch(()=>{ a.decodeError=true; return a; });
}
return carregarImagem(a.f).then(async img=>{
if(img){ a.prop=img.height/img.width; a.px=img.width; a.py=img.height; a.src=img.src; a.miniSrc=miniatura(img); a.fotoSrc=miniatura(img,480,720);
if(img){ a.prop=img.height/img.width; a.px=img.width; a.py=img.height;
a.dpiSalvo=await dpiSalvoPng(a.f);
if(a.dpiSalvo>=200){
a.cmSalvo=Math.round(a.px/a.dpiSalvo*2.54*10)/10;
if(a.cmSalvo>=1 && a.cmSalvo<=larguraFilme() && !a.cm) a.cm=a.cmSalvo;
}
a.src=img.src; a.miniSrc=miniatura(img); a.fotoSrc=miniatura(img,480,720);
// Read at its own pixels while the customer sets the width.
a.lendoArte=true;
mapaDaImagem(img, a.px/300*2.54).then(m=>guardaMapaDaArte(a,m)).catch(()=>{})

View File

@@ -348,6 +348,8 @@ section+section{border-top:0}
.provaOp{display:flex;gap:10px;align-items:flex-start;cursor:pointer;font-size:15px;line-height:1.5;color:var(--fraco)}
.provaOp input{margin-top:3px;width:17px;height:17px;flex:none;accent-color:var(--laranja)}
.provaOp b{display:block;color:var(--preto);font-weight:700}
.provaOp:has(input:disabled){cursor:default;opacity:.55}
.provaMin{margin:8px 0 0 27px;font-size:14px;color:var(--fraco)}
.cp input,.cepL input{height:46px;border-radius:var(--raio2)}
.cp input:focus,.cepL input:focus{border-color:var(--laranja2);box-shadow:0 0 0 3px rgba(255,168,26,.18)}
.opE{border-radius:12px}

View File

@@ -3,7 +3,7 @@ const VIDEOS = [
{id: 'subindo', title: 'Subindo a arte pelo celular',
desc: 'Do primeiro toque ao preço, sem instalar nada.', product: null,
src: null, captions: null},
{id: 'nota', title: 'O que é a nota da arte — e o que ela não é',
{id: 'nota', title: 'O que a nota da arte mostra',
desc: 'A nota explica o arquivo; ela não muda o preço.', product: 'file',
src: null, captions: null},
{id: 'png', title: 'Por que PNG com fundo transparente',

View File

@@ -81,9 +81,17 @@ async function sendUpload(file, {api, prefix='/uploads', startPath=prefix, progr
signal?.addEventListener('abort',()=>xhr.abort(),{once:true});
xhr.send(body);
});
// A file taken off the page while it went gives its place back at once: a
// reservation it left would hold the pending cap for 20 minutes, and a
// customer switching products filled it (Sentry DTF-WEB-14, 29/11).
const giveBack=()=>{
fetch('/api'+prefix+'/'+id,{method:'DELETE',credentials:'same-origin'}).catch(()=>{});
if(resume)localStorage.removeItem(key);
};
if(signal?.aborted){giveBack();throw cancelled();}
for(let offset=0,part=1;offset<file.size;offset+=size,part++){
if(done.has(part))continue;
if(signal?.aborted)throw cancelled();
if(signal?.aborted){giveBack();throw cancelled();}
progress('Enviando '+file.name+' · parte '+part+'/'+Math.ceil(file.size/size));
// A part the network dropped goes again twice, on a fresh link, before
// the customer is asked to resume (DTF-WEB-13).
@@ -91,7 +99,8 @@ async function sendUpload(file, {api, prefix='/uploads', startPath=prefix, progr
const signed=await withRetry(options=>api(prefix+'/'+id+'/parts/'+part,{},options));
try{await put(signed.url,file.slice(offset,offset+size));break;}
catch(error){
if(error?.name==='AbortError'||attempt>=2)throw error;
if(error?.name==='AbortError'){giveBack();throw error;}
if(attempt>=2)throw error;
await new Promise(resolve=>setTimeout(resolve,(attempt+1)*3000));
}
}
@@ -104,6 +113,10 @@ async function sendUpload(file, {api, prefix='/uploads', startPath=prefix, progr
window.dtfUpload = async (file, options) => {
if(options?.signal?.aborted)throw new DOMException('Envio cancelado.','AbortError');
await uploadSlot();
try{return await sendUpload(file, options);}
try{
// Taken off the page while it waited for a place: no reservation at all.
if(options?.signal?.aborted)throw new DOMException('Envio cancelado.','AbortError');
return await sendUpload(file, options);
}
finally{releaseUploadSlot();}
};