Compare commits

...

134 Commits

Author SHA1 Message Date
Cauê Faleiros
c4f8ba1b70 copy: the Kanban says what to do, not how the system does it
Some checks are pending
Build and deploy / Integration suite on a real stack (push) Blocked by required conditions
Build and deploy / Secret scan and release gate (push) Blocked by required conditions
Build and deploy / Publish images (push) Blocked by required conditions
Build and deploy / Validate source (push) Successful in 7s
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
Cauê Faleiros
f35a347a28 fix: a reprint keeps an all-items choice, an undone pass to Revisão prints nothing again, and Prova OK tells Tiny (#105)
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 7m56s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m26s
- Every item ticked was saved as NULL, which also means "not chosen", so the
  pass to the queue replaced it with the suggestion and only the changed
  item went to the machine; the panel showed the suggestion again. The
  choice is now the whole list.
- Undoing a pass to Revisão (back to Imprimindo) started a new round with
  every file, so FlexiPRINT printed the order again. It now writes back only
  what Flexi had not taken, and the reprint choice of that pass returns. A
  pass undone this way no longer counts its film twice in the machine's
  metres (machine log and Números).
- An order entering the queue by Prova OK never sent Tiny's "Preparando
  envio". The stage's Tiny event is now one function, used by the move and
  by the Prova OK.

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:48:34 -03:00
Cauê Faleiros
742ea5f5bd fix: the choice of items to reprint ends with the print, a new final or "Gerar de novo", so a later correction always goes to the machine (#105)
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 7m54s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m27s
Kept until Finalizado, an old choice would leave out an item corrected after
it (an order back from Revisão, or a second correction). It is now cleared
when the pass to Revisão records it, when a final changes and when the files
are generated again; the next entry to the queue works it out anew. An
integration test follows the whole reprint: first print, one item corrected,
the queue, the hot folder with that item only, Revisão.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 14:19:37 -03:00
Cauê Faleiros
b2876487bd fix: a film's parts go to the machine in their own order, p2 before p10
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Failing after 47s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Has been skipped
The hot folder and the folders' list ordered the parts by name, so a film of
ten parts or more (#81, 91,5 m) would send p10 second. They now follow the
part number. Checked on Postgres 17 with an 11-part film.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 14:16:31 -03:00
Cauê Faleiros
331e43aa14 fix: a film is cut into parts where its own pixels are clear, never through the art when it can be helped (#136)
Some checks failed
Build and deploy / Validate source (push) Successful in 9s
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 layout sees a ready sheet as one piece, so a part was cut at its length,
through the artwork. Where no gap between pieces is near the limit, the
film is read there: the cut falls in the middle of the nearest clear band of
3 mm, else of the widest clear band (#83's packed sheets have 2 mm between
rows), else on the row with the least ink. A part is never shorter than half
the limit, and the render limit allows one part more.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 14:11:15 -03:00
Cauê Faleiros
eb56c49016 fix: the card's "Arquivo gerado" names every part of a film, not the first one's (#130)
All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 7m56s
Build and deploy / Secret scan and release gate (push) Successful in 11s
Build and deploy / Publish images (push) Successful in 1m28s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 13:27:19 -03:00
Cauê Faleiros
3204ec4368 ci: run again (run 371: the cancelled run left the test Site pointing at the old API, 502)
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 7m22s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m27s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 12:40:11 -03:00
Cauê Faleiros
00261af931 fix: the repair of the missing parts raises each order's version, so the board and the folders see them at once
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Failing after 51s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Has been skipped
Tested on Postgres 17: only the orders before Imprimindo whose Prumo approved
part of a film get the rest; orders approved by a person, printing, treated
or with an old final are left alone.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 12:37:15 -03:00
Cauê Faleiros
6a8855504f fix: a busy Tiny retries the whole delivery instead of sending the order without its seller
Some checks failed
Build and deploy / Validate source (push) Successful in 9s
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
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 12:33:39 -03:00
Cauê Faleiros
b027bb5013 fix: Prova OK approves every part of a film, and "Gerar de novo" names the new files with a version (#114, #128, #130)
Some checks failed
Build and deploy / Validate source (push) Successful in 16s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Integration suite on a real stack (push) Has been cancelled
Build and deploy / Secret scan and release gate (push) Has been cancelled
The proof's approval took the print file's first upload as the final, so the
other parts of a film in parts never reached Arte conferida or the hot folder
and were downloaded by hand. It now approves every part, and adds the missing
ones to a first part already approved. A one-off migration completes the
open orders still before Imprimindo. Generated again, the files are named
DTF-130-v2-item-1-p2.png, as Marcus asked, so the FlexiPRINT queue and the
Hoson list never take them for the first ones.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 12:25:23 -03:00
Cauê Faleiros
b8496b858f feat: a reprint sends only the items chosen to the machine (Marcus, 2026-11-26, #105)
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Integration suite on a real stack (push) Successful in 7m55s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m34s
An order the machine already printed, back in Arte conferida, sends again
only the items whose final changed since the machine took them; the panel's
"Vai para a máquina" shows and changes the choice, and the card says
"Reimpressão". The order stays one card. The pass to Revisão keeps the
items printed, so the machine's metres count only those.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 10:00:54 -03:00
Cauê Faleiros
47f3251d3e feat: "Enviar nova versão" keeps each item's current final, ticked, so only the corrected file is sent (Marcus, 2026-11-26, #105)
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
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
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 09:55:53 -03:00
Cauê Faleiros
5dc4135562 fix: an HTML page from the proxy is a passing outage, a full machine and a proof card in Finalizado are said before the move (DTF-WEB-1Z, 20, 21)
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 7m42s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m20s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 09:26:48 -03:00
Cauê Faleiros
ffc7d3153a feat: a Tiny order goes with the seller in the customer's registration (Marcus, 2026-11-26)
Some checks failed
Build and deploy / Validate source (push) Successful in 7s
Build and deploy / Integration suite on a real stack (push) Successful in 8m24s
Build and deploy / Secret scan and release gate (push) Successful in 11s
Build and deploy / Publish images (push) Has been cancelled
Tiny does not fill the seller on an order created through its API, and it
cannot be set afterwards (order 151250). The existing contact's seller, from
its dados complementares, now goes in the order; it wins over who assembled a
montador Venda. No seller in the registration: the assembler's, or none for a
Site order. A failed reading never holds the order.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 09:16:53 -03:00
Cauê Faleiros
70837e2e06 fix: a PNG the phone cannot open whole is read in bands, not charged as a manual check
Some checks failed
Build and deploy / Validate source (push) Successful in 1m17s
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
A 57 MB sheet failed to decode on a phone (out of memory), so the Site took it
for a file the browser cannot read: +R$ 2,00 a metre and "O navegador não abre
PNG". Its size was already known; it now goes the large-file way.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 09:15:23 -03:00
Cauê Faleiros
8af6d576e9 fix: a quote this session no longer owns sends the customer back to the cart, not to an error (DTF-WEB-1Y)
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Integration suite on a real stack (push) Successful in 8m18s
Build and deploy / Secret scan and release gate (push) Successful in 12s
Build and deploy / Publish images (push) Successful in 2m2s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 16:42:11 -03:00
Cauê Faleiros
f58b0701b4 fix: a Site script the network dropped is said at once, with a reload, and reported (DTF-WEB-1W)
All checks were successful
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 8m36s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m13s
On an Android phone site-upload.js never arrived, so recusa() was the page's
#recusa element and the product did not open. The last script now checks each
module, shows "Uma parte do site não carregou" with Atualizar, and tells
Sentry which file is missing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 15:43:30 -03:00
Cauê Faleiros
64a017e0a4 feat: a ready sheet's pieces under 5 mm show on the Kanban card (Marcus, 2026-11-26, #81)
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 7m52s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m29s
The Site already counted them and warned the customer; the count now travels
with the item (close_pieces) to the card's flags, the order panel and the
quote review, so the room sees it before printing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 14:43:25 -03:00
Cauê Faleiros
3b9575b94b fix: declining "Outra pessoa está nesta máquina" just leaves the chooser open (DTF-WEB-1V)
All checks were successful
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 8m17s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 2m5s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 14:10:47 -03:00
Cauê Faleiros
617868945a fix: the Montar's form checks (code, size, quantity, customer, freight) are guidance, not errors (DTF-WEB-1T)
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 7m22s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m6s
Real failures, the server's refusals and unreadable files, stay red and reach Sentry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 13:25:41 -03:00
Cauê Faleiros
8ba30e057c feat: 8 mm of clear film between the copies and sheets of a ready sheet, billed (Marcus, 2026-11-26)
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 7m43s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m23s
The Site stacked a ready sheet's copies with nothing between them (#81's were
0,3 mm apart). Now 8 mm separates each copy and each sheet from the next, and
the metres include it, as Marcus confirmed. A new cart without the gap is
refused with the reason; a quote made before is still reviewed.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 12:53:11 -03:00
Cauê Faleiros
2fcec0b809 test: wait for Pagar to open instead of reading it once (CI run 356)
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 7m58s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m31s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 12:16:10 -03:00
Cauê Faleiros
6d8dbf24ff feat: the proof samples the file's colours too, up to 30 cm (Marcus, 2026-11-26)
Some checks failed
Build and deploy / Validate source (push) Successful in 8s
Build and deploy / Integration suite on a real stack (push) Failing after 8m7s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Has been skipped
The proof keeps its 15 cm window on the finest stroke and adds 5 cm samples of
the colours that window lacks (12 hues, grey, white, black), 1 cm of clear film
between them, up to 30 cm. The colours are read from the small picture the
Site sends of each file, so a long film is scanned in a moment; without
pictures (a proof cut from a prepared final) it stays the stroke window. #100's
proof caught only its white art.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 12:05:45 -03:00
Cauê Faleiros
4c6e2aac4a feat: a user may have more than one profile, and may do what any of them may (Marcus, 2026-11-26)
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 8m1s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m32s
operators.roles holds every profile, the main one first; permissions, moves,
the column order and the machine question are the sum. The operator's machine
rules apply only to the moves Operador alone allows, so an Operador who is also
Revisor releases any sheet (D-29 does not block, Marcus). Usuários gets
"Outros perfis" chips next to the main profile.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 10:57:20 -03:00
Cauê Faleiros
a88e7a3288 feat: one order, one machine: UV and textile never share an order (Marcus, 2026-11-26)
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 7s
Build and deploy / Publish images (push) Successful in 1m16s
The server refuses a cart (and a review) with UV and textile items; the Site
says so as soon as the customer opens a product of the other line, or adds it,
with "Finalizar este pedido" and "Trocar o carrinho por este item". Basic
and premium textile still go together. Proof cards copy their order's items,
so they follow.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 09:57:03 -03:00
Cauê Faleiros
5ed8109d50 fix: the Mercado Pago script is tried twice, and a card form the customer left for PIX shows no error (DTF-WEB-1S)
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 8m14s
Build and deploy / Secret scan and release gate (push) Successful in 16s
Build and deploy / Publish images (push) Successful in 1m28s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 09:26:17 -03:00
Cauê Faleiros
9c23654937 fix: choosing the machine with no network is a warning to try again, not an error (DTF-WEB-1Q)
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 6m57s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m8s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-25 18:50:34 -03:00
Cauê Faleiros
a5820eb147 fix: PRINT_PART_CM reaches the API and worker, 10 m by default (#81 came out in 15 m parts)
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 7m3s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m3s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-25 18:28:32 -03:00
Cauê Faleiros
3da1c9c11c fix: a receipt another computer took is no error, and a drop on a card now on another machine says so (DTF-WEB-1N, 1P)
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 8m22s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 2m1s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-25 18:06:29 -03:00
Cauê Faleiros
5db8661a1a fix: the Kanban says the proof machine before a pull, folder downloads cut by the network wait for the next pass, expected refusals stay out of Sentry (DTF-WEB-16..1K, DTF-API-C)
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 7m37s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m25s
- 19/1F: the board carries the approved proof's machine; the pull and the
  order's machine field keep to it and say why.
- 17/1E: a network drop while a download or an answer arrives counts as
  unreachable/offline, warned first like the others.
- 16: no folder picker (Safari): said in a line.
- 1A, 1J/1K, 1D, 18: guidance and expected refusals (pull to another machine,
  someone already on the machine, e-mail in use, coupon) are not errors.
- 1B: an empty file is refused on the page.
- API-C: the Tiny's rate limit reaches Sentry only if it repeats.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-25 09:46:26 -03:00
Cauê Faleiros
449b45b520 fix: the print file is written over twice as fast, and a file finished after Prova OK queues its order (#81)
Some checks failed
Build and deploy / Validate source (push) Successful in 1m41s
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
#81's 91,5 m took 6 hours to generate. The PNG writer ran Pillow's row filters
and then deflate at level 6; no filter at level 1 gives the same size in under
half the time, for the file and the viewer's strips alike (1 m: 34 s -> 13 s).

Its Prova OK came while the file was still being generated, so the order stayed
in Arte recebida. The approval now also runs when the file finishes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-25 09:40:13 -03:00
Cauê Faleiros
a1fad7698a fix: an interrupted upload stops holding the pending cap after 20 idle minutes; a dropped part goes again, quiet 429s, one Sentry report (DTF-WEB-13/14/15)
All checks were successful
Build and deploy / Validate source (push) Successful in 1m7s
Build and deploy / Integration suite on a real stack (push) Successful in 8m2s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m35s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-24 17:17:31 -03:00
Cauê Faleiros
242a56aae8 fix: an R2 blip no longer makes /health a 503; storage down for 5 minutes does, reported once (DTF-API-B)
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 8m1s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m27s
R2 answered HeadBucket with a 500 now and then (34 times from 20/11) and
/health answered "Database or storage unavailable" although the database
was fine. The database down is still a 503 at once. Storage is asked
twice, 0,3 s apart, within the container check's 3 s; failing, the
answer says "storage": "unavailable" with 200 and logs a warning; after
5 minutes in a row it is a 503 and one error for Sentry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-23 13:18:31 -03:00
Cauê Faleiros
d51fe24eea fix: before approving, the panel learns that a file cannot be a final and says to treat the art (DTF-WEB-11)
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 7m15s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 2m28s
The panel offered the customer's correction (or an original) as ready to
approve, and the server refused it as not a transparent 300 DPI PNG,
an error for Sentry. POST /orders/{id}/final-check reads the header of
the order's own files with the same check as the approval and answers
200 with the problems; "Aprovar arquivo final" asks it first and, when a
file cannot be a final, says why and to use "Tratar a arte".

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-23 11:52:01 -03:00
Cauê Faleiros
6e05dd93c2 fix: the card form opens with the order's document, so the card token and the Mercado Pago payer agree
Some checks failed
Build and deploy / Validate source (push) Successful in 15s
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
65f8dd2 made the order's document the payer of every card payment, which
could differ from the document inside the card token and raise refusals.
The card form now opens with the order's CPF or CNPJ (Card Payment Brick
initialization.payer.identification), so both carry it. A valid document
the customer types there instead (someone else's card) is the payer, as
the token says; a placeholder such as 999.999.999-99, or none, gives way
to the order's. The order's document always rides in the payment's
metadata for finance, and the order's name goes as first and last name.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-23 11:46:28 -03:00
Cauê Faleiros
65f8dd211e fix: the Mercado Pago payer is the order's customer, with document and name, for PIX and card (checkout item 2)
All checks were successful
Build and deploy / Validate source (push) Successful in 1m42s
Build and deploy / Integration suite on a real stack (push) Successful in 8m39s
Build and deploy / Secret scan and release gate (push) Successful in 12s
Build and deploy / Publish images (push) Successful in 2m12s
Marcus, 2026-11-18: finance reconciles the payment by the customer and
the invoice is issued to them; half the payments showed 999.999.999-99
and no name. The payer now always carries the order's CPF or CNPJ, the
first and last name from the order and the e-mail. The card form's
document is no longer sent by the Site nor used (the cardholder's data
travel in the card token); the field stays accepted for pages loaded
before.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-23 10:33:29 -03:00
Cauê Faleiros
177694edd3 fix: the worker waits out a short storage outage, and Sentry hears of one that outlasts the attempts once (DTF-API-A)
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 7m2s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m53s
R2 answered 503 while a print file tile of #53 was stored, and botocore's
two tries ran out. The worker's own reads and writes (store, fetch) now
use a client with up to 10 tries in standard mode, about two minutes of
backoff; requests a person waits on keep two. A storage failure that
still happens is a warning while the job has attempts left and an error
on the last one.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-19 09:52:25 -03:00
Cauê Faleiros
662d6f9c41 fix: a final that stopped counting is approved again, and a pull onto a machine that does not print the product is refused on the board (DTF-WEB-10, DTF-WEB-12)
All checks were successful
Build and deploy / Validate source (push) Successful in 1m49s
Build and deploy / Integration suite on a real stack (push) Successful in 8m41s
Build and deploy / Secret scan and release gate (push) Successful in 14s
Build and deploy / Publish images (push) Successful in 2m5s
- A generated file, or the customer's correction, that was this item's
  final and stopped counting (Correção, a step back) is turned back on
  when approved again, instead of "Este arquivo já está no pedido";
  other files keep that rule.
- A lane drop, or a machine chosen before, that does not print the
  order's product says "A <máquina> não imprime este produto." on the
  board and the card stays in Arte conferida, as the chooser filters.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-19 09:27:10 -03:00
Cauê Faleiros
29187e6c9f test: the trimmed sheet's film has its own name, so the viewer check keeps the first film
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 7m2s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m16s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 13:45:57 -03:00
Cauê Faleiros
378266afa2 test: the trimmed sheet in the print file test is 300 DPI, with no resolution note to confirm
Some checks failed
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Failing after 3m35s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Has been skipped
Between 96 and 199 DPI the server asks for the resolution note, as it
should; the test sheet is now at the normal 300 DPI.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 13:40:57 -03:00
Cauê Faleiros
9e31345cf7 test: the trimmed sheet in the print file test is 152 DPI, above the server's 96
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Failing after 3m30s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Has been skipped
The server refused the 25 DPI test sheet before payment ("abaixo do
mínimo de 96 DPI"), as it should.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 13:35:38 -03:00
Cauê Faleiros
70eb6947eb test: a paid ready sheet with its empty strips cut bills 1 m and prints only what is left
Some checks failed
Build and deploy / Validate source (push) Successful in 13s
Build and deploy / Integration suite on a real stack (push) Failing after 4m20s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Has been skipped
End to end on the real stack: a 27 x 30 cm UV PNG with 20 cm of art in
the middle, quoted with the 4,5 cm the Site cuts above and below, paid;
the worker's PNG is 21 cm plus the footer, transparent 0,5 cm above and
below the art, and the Prumo report says "Faixas vazias cortadas: 9,0 cm".

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 13:29:46 -03:00
Cauê Faleiros
b3ecba590b fix: customer credit reaches Tiny as CREDITO PRE-PAGO, with its own marcador beside SITE DTF (#42)
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 7m45s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m25s
Marcus, 2026-11-18: "Pago fora do site › Crédito do cliente" maps to the
forma de recebimento CREDITO PRE-PAGO (987762591), and the order also
gets the marcador CREDITO PRE-PAGO. CORREÇÃO DTF, refused by Tiny for
#42, is for correction orders only. A retry adds only the marcadores
the order is missing.

The outbox computes the forma when it delivers, so #42's queued sale
goes through on its next retry after the deploy.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 12:24:21 -03:00
Cauê Faleiros
a52856f3f6 fix: a Kanban form's own check shows as a notice, not as an error for Sentry (DTF-WEB-Z)
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
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 coupon form checks its code on save and throws a plain Error with
the reason; formDialog showed every error in red, so a typing mistake
became an issue. A plain Error without an API status is now a notice;
the API's refusals (already reported by apiError) and broken code stay
red and reach Sentry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 12:19:16 -03:00
Cauê Faleiros
9bbfa42cd4 test: the ready sheet's two copies count twice its trimmed metres
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 7m12s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m25s
The artwork browser test still expected 2 × 0,342 m for the test sheet
with 19 cm empty at the bottom; with the empty strips cut (2d8d7c7) each
copy is the trimmed height.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 12:09:20 -03:00
Cauê Faleiros
2d8d7c78b1 feat: the Site cuts the empty strips at the top and bottom of a ready PNG sheet from price and print
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Failing after 7m43s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Has been skipped
Step 2 of trimming empty strips (Marcus, 2026-11-18): the Site.

- The sheet check finds where the ink starts and ends (each map cell
  keeps its first and last ink row) and returns the empty strips.
- A ready PNG sheet whose strip passes 1 cm loses it but for 0,5 cm, as
  the layout keeps; its metres drop to what is left, and the cart sends
  trim_top_cm and trim_bottom_cm with the source, which the server prints
  without (06f4ec9). Spaces between artworks stay.
- The sheet's card says "Removemos N cm vazios do fim do arquivo.
  Cobrado: X m." (with several sheets or copies: "Esta folha fica com
  X m.").
- The thinnest stroke's place for the proof counts from where the cut
  starts.

Checked in Chromium against the page: a 100 cm UV sheet with art from 20
to 45 cm leaves 25,98 cm, a 3 m sheet (the tall-PNG path) 71 cm, two
sheets each say their own metres; the cart's production passes the
server model and prints 25,98 cm with the art whole.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 11:59:14 -03:00
Cauê Faleiros
06f4ec9f20 feat: a ready sheet can carry the empty strips cut from its top and bottom, and prints without them
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 7m49s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m23s
Step 1 of trimming empty strips (Marcus, 2026-11-18): the server side.

- ProductionSource has trim_top_cm and trim_bottom_cm (default 0); only
  a measured finished sheet may carry them, and length_cm is what is
  left, billed and printed.
- The generator leaves those file rows out (whole decode and banded PNG
  reading), and the proportion check compares the art with what is left.
  A PDF with a cut, or a cut that does not match the file, goes to hand
  preparation.
- The Prumo report says "Faixas vazias cortadas: N cm".

The Site does not send the cut yet (step 2).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 11:44:48 -03:00
Cauê Faleiros
ad3a966ae2 fix: a cart with a quality note to confirm guides the customer to it instead of an error (DTF-WEB-Y)
All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 6m49s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m13s
Enter in the coupon field sends the cart like "Aplicar" and "Pagar"; with
a quality note still unconfirmed, the guard's expected message was red
and reached Sentry. It is now a warning, and the page scrolls to the
first note to confirm.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 11:20:10 -03:00
Cauê Faleiros
a28cd165c4 fix: a delivery Tiny refuses reaches Sentry on its first failure and every tenth (order #42)
All checks were successful
Build and deploy / Validate source (push) Successful in 16s
Build and deploy / Integration suite on a real stack (push) Successful in 8m46s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m27s
Tiny refused #42 fourteen times ("Forma de recebimento não está
habilitada": the customer-credit forma, CORREÇÃO DTF, is disabled in
Dropstar's Tiny) and only Integrações showed it. The outbox now logs the
refusal as an error on the first failure and every tenth retry, one
message template so Sentry keeps one issue per kind.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 10:56:29 -03:00
Cauê Faleiros
2f67fdc123 fix: a Site upload that never reached the server tries once more, then says the connection is down (DTF-WEB-X)
All checks were successful
Build and deploy / Validate source (push) Successful in 1m46s
Build and deploy / Integration suite on a real stack (push) Successful in 7m52s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m56s
A customer's POST /api/uploads failed with "Failed to fetch" before any
part was sent (05:07 UTC): their network, not the Site. The upload now
tries again three seconds later; if that fails too, the file shows
"sem conexão com o servidor. Confira a internet e tente de novo" with
the "Tentar de novo" button, and Sentry hears of it as before.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 09:29:23 -03:00
Cauê Faleiros
d76288c335 feat: "Gerar de novo" also from Imprimindo, taking the file out of the hot folder (order #36)
All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 7m9s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m30s
#36 is already in Imprimindo. From there the order goes back to Arte
recebida like a card leaving Imprimindo: what Flexi has not taken is
withdrawn from the machine's hot folder (hotfolder.stop), and the step
back is recorded as "Arquivo gerado de novo".

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-17 17:38:02 -03:00
Cauê Faleiros
27b26cd1ae feat: "Gerar de novo" makes a ready print file again for the part size of now (order #36)
Some checks failed
Build and deploy / Validate source (push) Successful in 9s
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 first film over 15 m (#36) left a 15 m part of 4,8 GB decoded, which
the FlexiPRINT refuses (#30, 12,3 m and 3,9 GB, printed). PRINT_PART_CM
already sets the part size; an order already generated had no way to get
its new parts.

- POST /orders/{id}/print-files/again (produce): in Arte recebida or Arte
  conferida, without a customer correction, the finals that were the
  generated files stop counting, the order is back in Arte recebida (a
  step back recorded as "Arquivo gerado de novo") and every item is
  generated again; one rendering now is left alone.
- The order's "Próximo passo" offers "Gerar de novo" there, with a
  confirmation that the final must be approved again.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-17 17:34:23 -03:00
Cauê Faleiros
e8931c2818 fix: the sellers list names the Tiny permission our user lacks and shows Tiny's answer
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 6m30s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m21s
Tiny refused GET /vendedores with 403 in production; the message blamed
the app's Contatos scope, which already works for the Venda customer
search. Tiny checks the connected user's module permissions: the message
now asks for "ver Vendedores" on our user and carries Tiny's own reply.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-17 14:30:32 -03:00
Cauê Faleiros
aaa6090642 feat: places per machine, drops on Imprimindo go to your machine, a Venda carries its seller to Tiny (DTF-WEB-V)
All checks were successful
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 7m38s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m19s
Marcus, 2026-11-17:
- Each machine has its own places (machines.places, 1 to 6, three to
  start): orders at once in Imprimindo and files at once in its hot
  folder. Admin sets it in the machine dialog; Admin and Gestão in the
  machine sheet's Dados da máquina. A third order shows as "Na vez".
- Whoever is signed in on a machine drops a card anywhere in Imprimindo
  and it goes to that machine; without one, the lane under the pointer.
- Each Kanban user may name their Tiny seller (Usuários, read from
  Tiny's own list); a montador Venda reaches Tiny with the seller of who
  assembled it. Every other order still sends no seller.
- A folder download that never reached storage (a network drop) waits
  for the next pass as a warning and is reported only if it keeps
  failing (Sentry DTF-WEB-V).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-17 14:18:19 -03:00
Cauê Faleiros
c61ac27ca4 feat: the proof's photo or video opens beside Prova OK and from its order, also after the answer
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 6m43s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m11s
Marcus could not reach the review photo of the proof of #30 (card #31):
in Revisão it sat at the end of the card's Pedido tab, away from the
answer, and once the seller answered, the card left the board and the
photo with it.

- The board sends each order's proof card with its photos and videos.
- "Responder a prova" has "Ver foto" / "Ver vídeo" beside Prova OK, or
  says the Revisor has not sent one yet.
- The parent shows a Prova section (the card, its answer, who and when)
  with the same buttons, and "Aguardando prova" offers them too.
- The viewer drops the print-file line for a review photo and reports a
  photo it could not load, in red and to Sentry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-17 10:37:33 -03:00
Cauê Faleiros
5d9a78b63c fix: a card form still mounting when the customer picks PIX is dropped quietly (DTF-WEB-T)
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 6m47s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m9s
Clicking PIX while Mercado Pago's card form was still mounting removed its
holder; the mount went on, found no fields and its onError showed "Erro no
formulário do cartão". Each mount now has its own number and holder id;
a stale mount's callbacks are ignored and the late form is unmounted when
it arrives. A mount that fails on the current form says so in red.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-17 10:11:23 -03:00
Cauê Faleiros
b6837023bf fix: the Kanban writes each file in _tmp and moves it in whole, so the FlexiPRINT never sees a temporary file (order #30)
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 6m28s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m3s
Chrome writes a .crswap working copy beside the file it writes. In the
hot folder the FlexiPRINT took each one as it appeared, the write failed
and every 30 s try left another; when the rename failed, the copy fallback
created the final name empty first and never removed it (0 KB files in
Arte conferida and maquina5\C2, Marcus 2026-11-17).

- Every file is written in _tmp, at the root of the chosen folder, under
  its own name, then moved under its final name into its folder.
- An empty file, or one shorter than the download's length, is deleted
  and reported in red (so in Sentry); the pass goes on and the next one
  tries it again.
- In the hot folders and Recibos a failed move is tried again; nothing
  is ever copied there. Elsewhere the copy stays, removes the final file
  if it fails, and reports to Sentry that it was used.
- Each page load clears the old .baixando and .crswap leftovers from the
  flow's folders; each pass clears tries over an hour old from _tmp.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-17 09:38:47 -03:00
Cauê Faleiros
bd25cb9c1c fix: the drag to Arte conferida without approved finals guides instead of reporting an error (DTF-WEB-R)
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 6m33s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m11s
The drop already opens the order on the approval step (DTF-WEB-F); its
line is guidance, like the review photo's in DTF-WEB-B, so it is no
longer red and no longer reaches Sentry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-17 09:26:13 -03:00
Cauê Faleiros
9630baa970 fix: a file the hot folder touches mid-write, a folder away at start-up and a moment without network are warnings first (DTF-WEB-S, DTF-WEB-P, DTF-WEB-Q)
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 7m42s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m57s
- InvalidStateError (the FlexiPRINT's watcher changed a part while the
  browser wrote it) joins the files held by another program: the pass goes
  on and the next one tries again; it reaches Sentry if it lasts.
- A NotFoundError with the main folder not answering (the server's share
  not up yet in the morning) says the folder is away and retries every
  30 s; it reaches Sentry after 5 minutes. A file that vanished mid-pass
  keeps reporting at once, now in Portuguese.
- A refresh that never reached the server (the computer waking up) says
  so and tries again; it reaches Sentry after 3 minutes offline. The
  folders' pass leaves that to the refresh.
- "Liberar pasta" no longer creates the folders itself, where a failure
  was swallowed; the pass right after does it and reports.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-17 09:13:13 -03:00
Cauê Faleiros
2439948249 fix: one file the worker may not delete no longer stops the cleanup of every other file
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Integration suite on a real stack (push) Successful in 7m23s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m34s
CI run 318 failed in retention_test: an expired upload outside the
storage policy's prefixes (originals/, videos/) made delete_object raise
AccessDenied, and the cleanup stopped there on every tick, so no file
behind it was ever deleted. The worker now logs it as an error (so it
reaches Sentry), tries that file again a day later and goes on with the
rest; retention_test covers it. The test fixtures that wrote keys under
test/, machine-test/, machine-log-test/ and reset-test/ now use
originals/, where the worker may delete them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 17:41:49 -03:00
Cauê Faleiros
0e7b6eb019 fix: an ended session or a server restart no longer shows the folders' pass as an error (DTF-WEB-N)
Some checks failed
Build and deploy / Validate source (push) Successful in 7s
Build and deploy / Integration suite on a real stack (push) Failing after 5m49s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Has been skipped
After 8 hours the session ends and the 30 s folders pass got "Entre no
Kanban." (401), reported in red and so to Sentry. A 401 or the restart's
503 now ends the pass quietly, since load() already shows the sign-in,
and no pass runs while the sign-in is showing. Real folder failures stay
red.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 16:58:27 -03:00
Cauê Faleiros
8cc35c100f fix: the launch cleanup leaves the Site videos' files alone
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
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
Marcus, 2026-11-16: the whole Site tab stays. The cleanup marked every
upload expired, the files behind the Site's videos and captions too; it
now skips the uploads site_videos points at, and counts only what it
removes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 16:53:21 -03:00
Cauê Faleiros
5ca4872e79 test: the test client starts the sign-in count again when the suite reaches the API's limit
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 6m37s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m14s
CI run 315 failed in label_test with the API's own 429 on
/operator/login: the whole suite signs in from one address and crossed
the 60 sign-ins per 15 min of app/core/auth.py. A test that did not ask
for the limit now clears login_attempts once and signs in again; tests
that expect the 429 still get it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 16:31:14 -03:00
Cauê Faleiros
5cf8cd1d54 fix: a pull on a card changed elsewhere tries once more, and a file held by the FlexiPRINT is a warning (DTF-WEB-K, DTF-WEB-M)
Some checks failed
Build and deploy / Validate source (push) Successful in 7s
Build and deploy / Integration suite on a real stack (push) Failing after 2m51s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Has been skipped
Pull: on "O pedido mudou" the board reloads; a card still in Arte
conferida is pulled again with the fresh version, one already printing
on that machine is left as it is, anything else reports the conflict.

Folders: a file another program holds open is expected while the
FlexiPRINT reads it. The first pass warns without the error flag, so it
no longer reaches Sentry; only a file still held after 10 passes (about
5 minutes) is an error.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 16:18:19 -03:00
Cauê Faleiros
9de9b6abe1 feat: Montar takes Dropstar's dotted codes and reads the size from the file name
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
Codes like NX.226 and NX.1003 are allowed in the page, the API and the
stamps table (a dot anywhere but first). A file's own size is a dot and
its letter before .png (Marcus, 2026-11-16): NX.226.C.png is NX.226 in C,
so nobody renames the library. Montar takes the size asked for, else the
code without a size, else another size of it scaled (the closest larger
one, else the largest) and says which file it was made from; the DPI
warning still applies. The <code>-<size>.png form is no longer read.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 16:14:49 -03:00
Cauê Faleiros
c799fd9be4 feat: the Kanban asks for the folder again on the first click after a reload
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 7m35s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m12s
After a reload the browser forgets the folder's permission and the
machines stopped writing until someone opened Integrações and clicked
"Liberar pasta" (Marcus, 2026-11-16). The first click or key anywhere in
the signed-in Kanban now makes that request; refused, the next click
asks again, and the "Liberar pasta" button shares the same request.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 15:54:46 -03:00
Cauê Faleiros
aa0ba92b68 fix: the video dialog names a wrong video or caption file before sending it (DTF-WEB-J)
All checks were successful
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 7m52s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m25s
The picker's accept list does not stop a dropped file, so a .mov or a
file over the limit reached the server and was refused with one message
for both fields. The dialog now checks extension and size with the
server's limits as soon as a file is chosen or dropped, says under the
field which file cannot be sent, and Salvar stays in the dialog.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 15:13:57 -03:00
Cauê Faleiros
4cba424149 fix: the video dialog marks the products that already have a published video (DTF-WEB-G, DTF-WEB-H)
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Integration suite on a real stack (push) Successful in 7m20s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m40s
"Onde aparece" names the products another published video holds and
closes them while this one is published; turning Publicar on over a
taken product stays off and says which video holds it. The server checks
before copying any file and its refusal names that video too.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 15:01:33 -03:00
Cauê Faleiros
66bc2b9b03 fix: Números shows no pace for under a quarter of an hour in Imprimindo
All checks were successful
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Integration suite on a real stack (push) Successful in 6m29s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m5s
A machine whose only finished order passed through Imprimindo in seconds
showed 110671,5 m per hour. The pace (per machine and month by month) now
needs at least 15 minutes of printing time and shows a dash below that.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 14:10:29 -03:00
Cauê Faleiros
4f584fed8a fix: a file another program holds open no longer stops the folders' pass
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 6m38s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m9s
Marcus's photo of 16/11: "Failed to execute 'createWritable' ... modifications
are not allowed". A file in use by another program (FlexiPRINT reading it, an
editor) made the whole pass fail, so every other file waited too, and a
target name held open left a half-written .baixando behind. Now that file is
skipped and retried 30 s later while the rest is written, the warning names
it in Portuguese, the .baixando is removed, and only one Kanban tab per
computer writes the folders (Web Locks), so two tabs never lock each other
out. The warning reaches Sentry like every red message.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 13:49:08 -03:00
Cauê Faleiros
050a823bcb fix: approving finals on an order changed elsewhere tries once more with the fresh version (DTF-WEB-7)
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 5m55s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Has been skipped
The first fix stays quiet when the finals were already approved or the order
left Arte recebida/Correção. Order #28 changed in another tab while the
panel was open and still waited for its finals, so the 409 came back. The
person had already confirmed those files: the Kanban now reloads and sends
them once more with the fresh version (the server checks everything again),
and only reports if that fails too or the order was cancelled.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 13:41:19 -03:00
Cauê Faleiros
f2b825b652 feat: every error shown in red reaches Sentry, also the ones the page handled itself
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
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
Until now only failed API calls and uncaught exceptions reached Sentry. An
error the page caught and showed, like the folders' "A última tentativa
falhou" Marcus photographed on 16/11, or an upload that failed on the Site,
never did. Now every red message in the Kanban, the Site's checkout, the
customer's account page and every failed upload is sent, one issue per kind
of message; the same text an API error already sent, or a 401 / restart 503
it skips on purpose, is not sent twice.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 13:40:59 -03:00
Cauê Faleiros
8daf3084aa fix: a drag to Arte conferida without approved finals opens the order on that step (DTF-WEB-F)
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 6m26s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m14s
The panel only offers Arte conferida once every item's final is approved, but
the board's drop sent the move and the server refused it. The drop now says
what is missing and opens the order on "Aprovar o arquivo final", the same
pattern as the review photo guard for Finalizado (DTF-WEB-B).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 13:26:56 -03:00
Cauê Faleiros
397e55c81d fix: Pedido pago fora do site no longer offers Faturado, and a 422 names its field (DTF-WEB-E)
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 7m16s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m16s
The register dialog offered Faturado, which the API refuses there: an
invoiced sale goes through the montador's Venda (front 7a.3). The choices are
now Pix, Cartão, Dinheiro and Crédito do cliente, as the API accepts. A
validation error in the Kanban now shows its first field and message instead
of the bare "Confira os campos (422)".

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 13:12:02 -03:00
Cauê Faleiros
52b8bb368f test: the test client waits out the gateway's rate limit instead of failing
All checks were successful
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Integration suite on a real stack (push) Successful in 6m32s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m17s
upload_limits_test sends about 300 requests in a few seconds (70 upload starts
and deletes, a 30-upload burst, 66 sheets), past nginx's 20 r/s with a burst
of 100 per address. On a busy runner the gateway answered 429 and the suite
failed (runs 298, 301, 302, and 303 twice). The shared client now waits a
second and retries when the 429 is nginx's HTML page; the API's own 429s, which
the suites check with expected=429, are unchanged, and so is the production
limit.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 12:53:30 -03:00
Cauê Faleiros
08b822104c Merge new layout phases E, F step 2 and G (order panel, Ficha, Números, phone)
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Failing after 1m27s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Has been skipped
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 12:45:21 -03:00
Cauê Faleiros
3d01b81a31 feat: new layout phase G, the phone as on the canvas
The bottom bar keeps Produção, Cotações, Pagamentos and Números; Mais opens
a sheet with the other sections (Montar, Site, Integrações, Usuários, as the
role allows, with the rail's icons) and the account (theme, password, Sair)
under their own headings, as in Ph1 and Ph2. Stage chips drop their icons and
keep the fade at the edge; the contraction fields take the full width in the
order page (Ph3). Números on the phone names each stage's limit, overruns and
waiting orders, and Por origem fits its five columns.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 12:45:21 -03:00
Cauê Faleiros
b3daed649a fix: new layout phase E review, the art preview stays and the live camera is not covered
The item keeps its Arte / Montagem preview, folded under the facts as
"Prévia da arte", so an item without a picture still has no empty column.
The Prumo, preview and Originais disclosures share one row style with a
turning chevron; Originais is hidden when there are none. In Revisão the
camera label no longer sits over the live video, a live camera takes the
whole row, and the no-camera line is a plain note as in D2.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 12:33:45 -03:00
Cauê Faleiros
ccdd72c4ce Merge new layout phase F step 2 (Ficha, Números) 2026-11-16 11:52:56 -03:00
Cauê Faleiros
9a0efb3b41 Merge new layout phase E (order panel) 2026-11-16 11:52:55 -03:00
Cauê Faleiros
fb23b63090 feat: new layout phase E, the order panel and Revisão as on the canvas
Roadmap Novo Layout, phase E (canvas P2, D2, Ph3): the panel without the
empty column (the item preview stays in Cotações and Abrir e conferir),
Próximo passo with its actions together and the primary last, the item
facts in a four-column grid (the secondary facts kept in a second row),
the Cliente, Entrega and Máquina blocks, and the Revisão dialog with the
camera card and the drop area. Every nextBox branch, action and
permission is unchanged. Built by Prensa.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 11:52:54 -03:00
Cauê Faleiros
a34d8e1888 feat: new layout phase F, Ficha da máquina and Números as on the canvas
Roadmap Novo Layout, phase F step 2 (canvas U2, N1): the machines list as
compact rows with their status line; the machine sheet in the shared
dialog with a fixed head and the tabs Situação, Lançamentos and Dados da
máquina (launch rule unchanged); Números as one scrolling page with the
four headline cards, Metros por dia, Produção, Vendas and Consulta
groups. The people list and roles matrix are untouched. Built by Bobina.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 11:52:39 -03:00
Cauê Faleiros
243138fea1 Merge test-order quote message (DTF-WEB-D)
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 6m35s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m22s
2026-11-16 11:52:36 -03:00
Cauê Faleiros
e8423bec45 fix: a quote held by a test order says so, and its panel closes
Sentry DTF-WEB-D: after "Criar pedido de teste" the quote panel kept
offering "Pedido pago fora do site", and the register answered "Esta
cotação já virou o pedido #N" without saying it was the test order.
The message now names the test order and says to delete it to register
the payment; creating the test order closes the quote panel.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 11:28:48 -03:00
Cauê Faleiros
392a21082e feat: new layout phase F, Montar as on the canvas
Some checks failed
Build and deploy / Validate source (push) Successful in 12s
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
Roadmap Novo Layout, phase F step 1 (canvas M1, M2, M3): the header with
the folder chip and Ajustes; "Adicionar estampa" by code with the found
card; the sheet list with steppers, metres and the live packed preview;
the side panel with Interno/Venda by role, the Tiny customer card,
delivery as real radio choices, brand per stamp and sticky totals; the
"Escolha a pasta dos pedidos" state; and Ajustes (sizes and the internal
customer) in the shared dialog with one save. Same reads, packing,
permissions and API calls. Built by Bobina.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 11:05:06 -03:00
Cauê Faleiros
040ef46f94 Merge review photo checks (DTF-WEB-B, C)
All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 7m11s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m10s
2026-11-16 10:37:44 -03:00
Cauê Faleiros
9e5811d58f Merge new layout phase D (production board, stage times) 2026-11-16 10:37:44 -03:00
Cauê Faleiros
92ffb679d6 fix: the review photo is measured before sending, and a drag to Finalizado without it opens Revisão
Sentry DTF-WEB-C and DTF-WEB-B (order #24, 16/11): a review photo under
1600 px on its longer side was refused only after the upload (a 1280x720
webcam always is), and dragging the card to Finalizado without the photo
got the server's 409. The dialog now says the minimum, the camera shot
and a chosen photo are measured in the browser with the same message,
and the drop opens Revisão instead of a refused move.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 10:37:44 -03:00
Cauê Faleiros
2c740da4c1 feat: new layout phase D, the production board and stage times as on the canvas
Roadmap Novo Layout, phase D step 2 (canvas A1, D1): a late card gets
the red border and red time (warn colour for a warn late) instead of the
Atrasados strip, which is no longer shown (renderLatebar kept for later);
machine lanes with name, blocking-alert dot, free places and dashed free
slots; compact Finalizado cards; the phone stage chips fade at the edge.
"Tempo aceitável de cada etapa" is a table (Etapa, Aceitável, Responde
pela etapa) with the same API. Built by Prensa.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 10:17:20 -03:00
Cauê Faleiros
d6c80ff447 Merge 503 during a database restart (DTF-API-8, 9)
All checks were successful
Build and deploy / Validate source (push) Successful in 1m22s
Build and deploy / Integration suite on a real stack (push) Successful in 7m6s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m44s
2026-11-16 09:46:37 -03:00
Cauê Faleiros
4e6f96bfe2 Merge board and order panel files (plan 007e) 2026-11-16 09:46:37 -03:00
Cauê Faleiros
ee772a43ff refactor: the production board and the order panel in files of their own
Plan 007e (Critical Corrections 7, last step; layout Phase D step 1):
web/kanban-board.js holds the board and the phone screens, and
web/kanban-order.js the order panel, its dialogs, the final files and
Abrir e conferir, moved verbatim from kanban.js (now 952 lines). The
browser test also walks the phone board. Built by Prensa.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 09:46:36 -03:00
Cauê Faleiros
bcba1fbe67 fix: a request during a database restart answers 503, and the logs stay quiet
Sentry DTF-API-8/9 (stack restart, 16/11 09:15): the startup retry kept
the API up, but a board request in the ~7 s without the database got a
500, and the render thread logged its error every 2 s. A request that
hits psycopg.OperationalError now answers 503 "O servidor está
reiniciando" with Retry-After (the web does not report it); the render
thread warns once per outage and backs off; the worker's first outage
line and the audit's connection outage are warnings.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-16 09:32:50 -03:00
Cauê Faleiros
00c7fa3dfa Merge new layout phase B (Site tab)
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 6m57s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m16s
2026-11-13 16:39:06 -03:00
Cauê Faleiros
2478c05ae6 Merge new layout phase C (Cotações) 2026-11-13 16:39:06 -03:00
Cauê Faleiros
70bdaf1a8d feat: new layout phase B, the Site tab as on the canvas
Roadmap Novo Layout, phase B (canvas S1 to S6): tabs Produtos e preços,
Cupons, Nota da arte and Vídeos; the products table with the on/off
switch, bands and next change; the price dialog with Agora/Agendar on
the Kanban calendar (calendar() takes options, Números unchanged), bands
and the live "O cliente vê" line; coupons, grade rules and videos in
tables with their dialogs; stacked rows and full-screen dialogs on the
phone. Same API calls and rules as before. Built by Prensa.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-13 16:39:06 -03:00
Cauê Faleiros
0e247e6b4c feat: new layout phase C, Cotações as on the canvas
Roadmap Novo Layout, phase C (canvas C1, C2): list rows with thumb,
product line, total and expiry; the "Tudo revisado" empty state with one
action to the quotes waiting for payment; the open quote with header,
total, facts in three columns, notes, Originais and the footer actions.
"Pedido pago fora do site" is now a dialog from the footer. Nothing
removed; the e-mail stays in the header. Built by Bobina.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-13 16:22:01 -03:00
Cauê Faleiros
8fa76b7819 Merge redeploy database retry (DTF-API-2..7)
All checks were successful
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 7m0s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m23s
2026-11-13 15:31:39 -03:00
Cauê Faleiros
fe224cfc9c Merge new layout phase A (Phosphor icons, shared pieces) 2026-11-13 15:31:39 -03:00
Cauê Faleiros
034f3bfbb5 feat: new layout phase A, Phosphor icons and shared pieces
Roadmap Novo Layout, phase A: every icon (IC, the stage marks, the rail
and the inline icons in kanban.html, the theme toggle and the select
chevrons) is Phosphor regular, filled at 256. Shared pieces from the
canvas for the next phases: switch, tag, data table, dialog scoping,
two- and three-column grids, tab counts in the lighter grey, and 44 px
controls on the phone. Built by Prensa.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-13 15:31:38 -03:00
Cauê Faleiros
445d686f43 fix: a redeploy's short database outage no longer takes the API down
Sentry DTF-API-2..7 (redeploy of 5a7fc0f, 13/11): the name db did not
resolve for about 12 s; the new API exited at startup and the worker and
audit() logged the error every second. The API now waits up to 90 s with
a backoff, the worker reports an outage once and backs off to 15 s, the
audit persistence error is logged at most once a minute, and api, site
and kanban update start-first so the old container serves meanwhile.

Built by Bobina.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-13 15:25:29 -03:00
Cauê Faleiros
5a7fc0f378 Merge Abrir e conferir fix for paid Ajuste Fino (DTF-WEB-A)
All checks were successful
Build and deploy / Validate source (push) Successful in 1m4s
Build and deploy / Integration suite on a real stack (push) Successful in 7m11s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m54s
2026-11-13 14:38:49 -03:00
Cauê Faleiros
9ae865619e fix: Abrir e conferir sends a paid Ajuste Fino order to Tratar a arte
DTF-WEB-A: closing the viewer on an order with Ajuste Fino or Redesenho
paid approved the original as the final and then tried the move, which
the server refused (the queue needs the treated PNG). The dialog now says
the treated art is missing and opens Tratar a arte, approving nothing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-13 14:24:51 -03:00
Cauê Faleiros
6be7e15f9f Merge Kanban fixes for Sentry DTF-WEB-4..7 and the Site tab price
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 6m57s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m15s
2026-11-12 16:05:26 -03:00
Cauê Faleiros
eef899e838 fix: Site tab, an empty Novo preço keeps the current price
The grey 9,90 in Novo preço is only a hint; saving a band with the field
empty refused with "Informe o preço em reais". Empty now keeps the current
price, and Salvar sits below the bands it saves with the price.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 15:48:42 -03:00
Cauê Faleiros
d0ec629c4e fix: Kanban pulls and final approvals stop failing on stale or missing context
Sentry DTF-WEB-4..7 (12/11):
- Pulling a card with no machine asks which machine takes it (gestão and
  admins); an operator always pulls to the machine of their session.
- The alert before a pull only offers Feito/Adiar to the machine's own
  operator or management, as the machine sheet does.
- A final-file approval from a dialog opened before the same approval
  went through reloads and says it was already approved, instead of the
  409 "O pedido mudou".

Built by Prensa; machine cards shared between the two choosers.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 15:48:41 -03:00
Cauê Faleiros
7abd215d13 Merge timings fix (DTF-WEB-9)
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 6m48s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m12s
2026-11-12 15:34:41 -03:00
Cauê Faleiros
e80f376d91 fix: an out-of-range cart timing is dropped, never refuses the quote
DTF-WEB-9: a cart left open for about 6 hours sent upload_ms 23556292,
above the 1 h limit, and POST /quotes answered 422: the customer could
not pay. The timings only feed Números, so a value out of range is now
dropped; an unknown field is still refused.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 15:34:41 -03:00
Cauê Faleiros
b8ee3fb35a Merge approve fix for reviewed quotes (DTF-WEB-8)
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 6m51s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m15s
2026-11-12 15:20:12 -03:00
Cauê Faleiros
057643e167 fix: approving a reviewed quote no longer sends the acceptance stamps back
A quote held for review whose customer accepted the residue or the
stroke warning failed with "Confira os campos (422)" (DTF-WEB-8): the
server stamps residue_accepted_at and stroke_choice_at on the draft's
items, the Kanban sent the items back whole, and the item model forbids
extra fields. The metres field also showed the float noise of the draft
(212,32800000000012); it now shows up to three decimals.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 15:20:12 -03:00
Cauê Faleiros
9cf4da0dea Merge render limit per part (order #20)
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 7m38s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m29s
2026-11-12 15:03:17 -03:00
Cauê Faleiros
a17287a118 fix: a long film's print file gets a render limit per 15 m part
Order #20 (23.6 m, 24 pieces) failed with "Falhou ao gerar": the whole
film had one 15 min limit, and two parts at 300 DPI take longer on the
server. The limit is now PRINT_RENDER_TIMEOUT_SECONDS (default 20 min)
for each part, and each claim records its deadline, so the stale-claim
check and the card's "Tempo limite" follow the same limit. A timeout, or
a final failed attempt, is logged as an error so Sentry sees it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 15:03:16 -03:00
Cauê Faleiros
c42e273c5b Merge Ajuste Fino Redesenho in the cart (slice R1)
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 7m15s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m16s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 11:27:59 -03:00
Cauê Faleiros
57851abffc fix: the designer's extra hours come from the order's own record
designer_hours ignored the hours stored with the order's treatment; an order
keeps the hours it was sold with, 48/24 only when none are recorded.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 11:25:09 -03:00
Cauê Faleiros
461bd6bbcc refactor: the Redesenho line reads its SKU through the shared setting constants
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 11:09:49 -03:00
Cauê Faleiros
912bab0278 Merge branch 'main' into redesenho 2026-11-12 11:09:14 -03:00
Cauê Faleiros
0964cdae1f Merge Tiny details of 12/11: Boleto account, Ajuste Fino by SKU
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 6m53s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m15s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 11:09:11 -03:00
Cauê Faleiros
38f947d632 feat: Ajuste Fino Redesenho in the cart (Marcus 12/11, slice R1)
Under each art the Prumo warns about, the customer can choose Ajuste Fino
or Ajuste Fino Redesenho (vectorize or redraw, per art, +48 h, no batch
price). It is a disabled product until Gestão prices it in the Site tab;
the server charges it per chosen art, Tiny gets a DTFIMP.AJF.RED line and
two more business days, the card shows 'Redesenho · N artes' and the
designer gate applies. The preview loop is slice R2.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 11:05:17 -03:00
Cauê Faleiros
973cd87b36 feat: Boleto with its bank account and Ajuste Fino by SKU in Tiny (Marcus, 12/11)
A faturado montador order's installments carry the bank account set in
TINY_BOLETO_ACCOUNT as their meioPagamento (Tiny v3 parcelas[]), so Tiny
does not pick another account. The Ajuste Fino line resolves the product
from its code (TINY_SKU_TREATMENT, default DTFIMP.AJF.UN) unless a numeric
TINY_PRODUCT_TREATMENT is set; the connection check verifies it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 10:52:46 -03:00
133 changed files with 8563 additions and 3600 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_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 -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 -v
- name: Runtime and retention regressions
run: |

View File

@@ -198,6 +198,16 @@ class FakeTiny:
{'id': 1002, 'name': 'Maria Souza', 'document': '123.456.789-09',
'email': 'maria.souza@example.test', 'phone': '16988887777'},
]
# The code's SKUs, so a payload can be built on the local stack without
# asking Tiny: the modes' defaults and the designer services (front 1b).
SKUS = {
'DTFIMP.TX.100CM': 8001,
**{f'DTFIMP.TX.{cm:04d}CM': 8000 + cm // 10 for cm in range(10, 100, 10)},
'DTFIMP.UV.1MT': 8101, 'DTFIMP.UV.010CM': 8102,
'DTFIMP.TXP.100CM': 8201,
**{f'DTFIMP.TXP.{cm:04d}CM': 8200 + cm // 10 for cm in range(10, 100, 10)},
'DTFIMP.AJF.UN': 9001, 'DTFIMP.AJF.RED': 9002,
}
def deliver(self, event_key: str, payload: dict) -> dict:
return {'provider': 'fake-tiny', 'reference': f"LOCAL-{payload['number']}",
@@ -206,13 +216,23 @@ class FakeTiny:
def search_contacts(self, query: str) -> list:
return [dict(contact) for contact in self.CONTACTS]
# Tiny's sellers, for the Kanban users' "Vendedor no Tiny".
SELLERS = [{'id': 2001, 'name': 'Lais'}, {'id': 2002, 'name': 'Marcus'}]
def list_sellers(self) -> list:
return [dict(seller) for seller in self.SELLERS]
def product_id(self, code: str) -> int:
"""The fake Tiny product id for a SKU code, as the real catalogue does."""
return self.SKUS[code]
class ObjectStorage(Protocol):
def begin(self, key: str) -> str: ...
def parts(self, key: str, upload_id: str) -> list: ...
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): ...
@@ -226,6 +246,12 @@ class LocalS3Storage:
connect_timeout=3, read_timeout=10, retries={'max_attempts': 2})
self.client = boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'], config=config)
self.public = boto3.client('s3', endpoint_url=os.environ['S3_PUBLIC_ENDPOINT'], config=config)
# The worker's own reads and writes wait out a short storage outage
# (an R2 503, Sentry DTF-API-A): up to 10 tries with growing backoff,
# about two minutes. Requests a person waits on keep the 2 tries.
patient = Config(signature_version='s3v4', s3={'addressing_style': 'path'},
connect_timeout=3, read_timeout=30, retries={'max_attempts': 10, 'mode': 'standard'})
self.patient = boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'], config=patient)
self.bucket = os.environ['S3_BUCKET']
def initialize(self):
@@ -267,18 +293,18 @@ class LocalS3Storage:
def fetch(self, key, path):
"""Copy a stored object to a local file (the worker's scratch space)."""
self.client.download_file(self.bucket, key, path)
self.patient.download_file(self.bucket, key, path)
def store(self, key, path, content_type):
"""Upload a file the service generated itself, such as a print file."""
self.client.upload_file(path, self.bucket, key, ExtraArgs={'ContentType': content_type})
self.patient.upload_file(path, self.bucket, key, ExtraArgs={'ContentType': content_type})
def download(self, key, name):
def download(self, key, name, expires=300):
from urllib.parse import quote
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

@@ -6,13 +6,15 @@ one transport serves both and there is only one place where parts are signed.
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException
from pydantic import Field
from ..core import db
from .. import proof
from ..artwork import submit_files
from ..core.auth import can, can_any, operator
from ..core.models import ArtworkSubmission, UploadStart
from ..runtime import file_rows, operator_identity
from ..core.models import ArtworkSubmission, StrictModel, UploadStart
from ..printpng_validate import final_png_problem
from ..runtime import file_rows, operator_identity, storage
from .uploads import begin_upload, cancel_upload, complete_upload, part_url, upload_status
router = APIRouter()
@@ -54,6 +56,35 @@ def operator_files(oid: UUID, user=Depends(operator)):
with db.connect() as c:
return file_rows(c,oid)
class FinalCheck(StrictModel):
uploads: list[UUID] = Field(min_length=1, max_length=400)
@router.post('/api/operator/orders/{oid}/final-check')
def final_check(oid: UUID, body: FinalCheck, user=Depends(can('produce'))):
"""Whether these files of the order can be approved as its finals, asked
before approving (Sentry DTF-WEB-11): a customer's correction or an
original may not be the transparent 300 DPI PNG a final must be. The
answer lists the problems with 200, so a file to treat is guidance in
the panel, not a refusal. Only the order's own files are read."""
with db.connect() as c:
order = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
originals = {uid for item in order['snapshot']['items'] for uid in item['uploads']}
rows = c.execute('''SELECT u.id,u.name,u.object_key FROM dtf_local.uploads u WHERE u.id=ANY(%s) AND (
u.id::text=ANY(%s)
OR EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=%s AND f.upload_id=u.id)
OR EXISTS (SELECT 1 FROM dtf_local.print_parts p WHERE p.order_id=%s AND p.upload_id=u.id))''',
(body.uploads, list(originals), oid, oid)).fetchall()
problems = []
for row in rows:
issue = final_png_problem(storage, row)
if issue:
problems.append({'upload_id': str(row['id']), 'name': row['name'], 'message': issue})
return {'problems': problems}
@router.post('/api/operator/orders/{oid}/final-files')
def final_files(oid: UUID, body: ArtworkSubmission, user=Depends(can('produce'))):
with db.connect() as c:

View File

@@ -1,6 +1,8 @@
"""Health, session bootstrap, freight quoting and the address of a CEP."""
import logging
import os
import re
import time
import httpx
from fastapi import APIRouter, HTTPException, Request, Response
@@ -16,17 +18,53 @@ from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, delivery_se
router = APIRouter()
# Since when storage has failed the check, and whether Sentry heard of it.
# R2 answers HeadBucket with a 500 now and then (Sentry DTF-API-B, 34 times
# from 20/11): a blip is not the API being down.
STORAGE_DOWN_AFTER = 300
_storage = {'down_since': None, 'reported': False}
def storage_answers():
"""Whether storage answers, trying twice in well under the 3 s the
container's health check allows."""
for attempt in range(2):
try:
storage.health()
return True
except Exception as exc:
error = exc
if attempt == 0:
time.sleep(0.3)
logging.warning('Storage health check failed: %s', error)
return False
@router.get('/health')
@router.get('/api/health')
def health():
"""The database down is the API down: 503 at once. Storage failing is
reported in the answer and is a 503, with one error for Sentry, only when
it has lasted STORAGE_DOWN_AFTER seconds."""
try:
with db.connect() as c:
c.execute('SELECT 1')
storage.health()
except Exception:
raise HTTPException(503, 'Database or storage unavailable')
return {'status': 'ok', 'environment': ENVIRONMENT,
'storage': 'minio' if ENVIRONMENT == 'local' else 'r2', 'integrations': 'fake'}
raise HTTPException(503, 'Database unavailable')
if storage_answers():
_storage.update(down_since=None, reported=False)
state = 'minio' if ENVIRONMENT == 'local' else 'r2'
else:
if _storage['down_since'] is None:
_storage['down_since'] = time.monotonic()
since = _storage['down_since']
if time.monotonic() - since >= STORAGE_DOWN_AFTER:
if not _storage['reported']:
_storage['reported'] = True
logging.error('Storage has failed the health check for %d minutes', STORAGE_DOWN_AFTER // 60)
raise HTTPException(503, 'Storage unavailable')
state = 'unavailable'
return {'status': 'ok', 'environment': ENVIRONMENT, 'storage': state, 'integrations': 'fake'}
@router.get('/api/session')
def session(request: Request, response: Response):
@@ -42,6 +80,7 @@ def session(request: Request, response: Response):
products = catalog.current(c)
rules = grade_rules.current_rules(c)
treatment = products['tratamento']
redesign = products['redesenho']
return {'environment': ENVIRONMENT, 'cart_scope': str(session_id), 'part_bytes': PART_BYTES,
'max_upload_bytes': upload_limit_bytes(), 'payment_provider': payment.name,
'password_recovery': mail.configured(),
@@ -53,6 +92,9 @@ def session(request: Request, response: Response):
'treatment_bands': [{'from_metres': float(band['from_metres']),
'unit_cents': band['unit_cents']}
for band in treatment['bands']] if treatment['enabled'] else [],
# Zero keeps Redesenho hidden, as an off product does. One price
# per art, never a band (front 1b).
'redesign_cents': redesign['unit_cents'] if redesign['enabled'] else 0,
# The grade rules the Site needs for the treatment requirement
# (front 8.5): {} when nothing is configured.
'grade_rules': rules,

View File

@@ -5,7 +5,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request
from .. import machine_log, machine_stats
from ..core import db
from ..core.auth import audit, can, operator
from ..core.auth import audit, can, operator, operator_only, roles_of
from ..core.models import MachineEntry, MachineSheet
router = APIRouter()
@@ -25,7 +25,7 @@ def machine_row(c, mid):
def own_machine(request, mid):
"""An operator enters only on the machine of their session; management, anywhere."""
account = request.state.operator
if account['role'] != 'operador':
if not operator_only(account, 'print'):
return
session_machine = account['machine']
if not session_machine or str(session_machine['id']) != str(mid):
@@ -127,7 +127,7 @@ def snooze_alert(mid: UUID, key: str, request: Request, user=Depends(can('print'
@router.get('/api/operator/stats/machines')
def machine_stats_month(request: Request, month: str | None = None, user=Depends(operator)):
"""Números per machine, month by month (Fase 2, front 1b)."""
if request.state.operator['role'] not in STATS_ROLES:
if not set(roles_of(request.state.operator)) & set(STATS_ROLES):
raise HTTPException(403, 'Seu perfil não permite esta ação.')
try:
start, _ = machine_stats.month_bounds(month)

View File

@@ -8,6 +8,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response
from pydantic import Field
from ... import hotfolder, machines, mail, payments, prumo, receipt, reviews
from ...cart_pricing import designer_hours
from ...core import db
from ...core.auth import audit, can, operator
from ...core.models import StrictModel
@@ -66,7 +67,7 @@ def board(user=Depends(operator)):
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
'finished_shown': len(finished), 'finished_total': finished_total,
# Who is on each machine now, for the machine question (item 12).
'machines': machines.rows(c, with_operators=True), 'printing_cap': machines.PRINTING_CAP,
'machines': machines.rows(c, with_operators=True), 'printing_cap': machines.DEFAULT_PLACES,
'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
'names': company_names(c, orders, quotes),
'pending_total': pending_total, 'approved_total': approved_total,
@@ -138,10 +139,10 @@ def assign_late(c, orders, limits):
since = since or order['created_at']
hours = max(0.0, (now - since).total_seconds() / 3600)
limit_hours = float(limit['hours'])
# A paid treatment gives Art received its extra hours to prepare the art.
treatment = (order.get('snapshot') or {}).get('treatment') or {}
if order['state'] == 'rec' and treatment:
limit_hours += float(treatment.get('hours', 24))
# Paid designer work gives Art received its extra hours to prepare the
# art: 48 h for a Redesenho, 24 h for the basic Ajuste Fino.
if order['state'] == 'rec':
limit_hours += designer_hours(order.get('snapshot') or {})
order['state_hours'] = round(hours, 2)
order['limit_hours'] = limit_hours
order['limit_by'] = limit['responsible']
@@ -172,8 +173,8 @@ def with_print_files(c, orders):
ids = [o['id'] for o in orders]
generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,p.claimed_at,p.finished_at,
p.created_at,
(p.status='rendering' AND p.claimed_at<now()-%s) AS timed_out,
p.claimed_at+%s AS timeout_at,u.name
(p.status='rendering' AND COALESCE(p.deadline_at,p.claimed_at+%s)<now()) AS timed_out,
COALESCE(p.deadline_at,p.claimed_at+%s) AS timeout_at,u.name
FROM dtf_local.print_files p LEFT JOIN dtf_local.uploads u ON u.id=p.upload_id
WHERE p.order_id=ANY(%s) ORDER BY p.item_index''', (CLAIM_TIMEOUT, CLAIM_TIMEOUT, ids)).fetchall()
upload_ids = sorted({str(uid) for order in orders for item in order['snapshot']['items']
@@ -208,20 +209,30 @@ def with_print_files(c, orders):
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()}
# Where a printing order's files are in its machine's hot folder (item 10).
hot = hotfolder.progress(c, [o['id'] for o in orders if o['state'] == 'imp'])
# Orders the machine already printed: a reprint chooses which items go
# again (#105), the ones whose final changed suggested.
taken = hotfolder.printed(c, [o['id'] for o in orders if o['state'] in ('rec', 'tra', 'cor')])
# Each parent's latest proof card, and each card's parent (app/proof.py).
children = {r['parent_id']: r for r in c.execute('''SELECT DISTINCT ON (parent_id) parent_id,id,number,state,
proof_result,proof_decided_at,proof_decided_by,proof_reason FROM dtf_local.orders
proof_result,proof_decided_at,proof_decided_by,proof_reason,machine_id FROM dtf_local.orders
WHERE parent_id=ANY(%s) AND cancelled_at IS NULL ORDER BY parent_id, created_at DESC''', (ids,)).fetchall()}
parents = {r['id']: r for r in c.execute('SELECT id,number,state FROM dtf_local.orders WHERE id=ANY(%s)',
([o['parent_id'] for o in orders if o.get('parent_id')],)).fetchall()}
# Every order's review photos and videos, in one query like the print files.
review_rows = reviews.by_order(c, ids)
# The proof card's go on its order too: an answered card leaves the board,
# and the photo the seller answered on must stay a click away (Marcus,
# 2026-11-17, the proof of #30).
proof_reviews = reviews.by_order(c, [r['id'] for r in children.values()])
for order in orders:
order['hot'] = hot.get(order['id'])
order['reviews'] = review_rows.get(str(order['id']), [])
child = children.get(order['id'])
order['proof_card'] = child and {k: child[k] for k in ('id', 'number', 'state', 'proof_result',
'proof_decided_at', 'proof_decided_by', 'proof_reason')}
# Its machine: an order prints where its approved proof did (Dropstar, 2026-11-05).
order['proof_card'] = child and {**{k: child[k] for k in ('id', 'number', 'state', 'proof_result',
'proof_decided_at', 'proof_decided_by', 'proof_reason',
'machine_id')},
'reviews': proof_reviews.get(str(child['id']), [])}
parent = parents.get(order.get('parent_id'))
order['proof_parent'] = parent and {'id': parent['id'], 'number': parent['number'], 'state': parent['state']}
order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None
@@ -231,6 +242,11 @@ def with_print_files(c, orders):
order['final_items'] = sorted({row['item_index'] for row in approved})
# The approved finals themselves: "Tratar a arte" keeps those it does not replace.
order['finals'] = [{'item_index': row['item_index'], 'upload_id': row['upload_id']} for row in approved]
if order['id'] in taken:
order['printed_before'] = True
order['print_suggested'] = hotfolder.reprint_default(
[(f['item_index'], f['upload_id']) for f in order.get('finals') or []], taken[order['id']],
len(order['snapshot']['items']))
mine = [row for row in treated if row['order_id'] == order['id']]
order['treated'] = {'items': [row['item_index'] for row in mine], 'by': mine[0]['created_by']} if mine else None
order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')}

View File

@@ -5,6 +5,7 @@ from fastapi import APIRouter, HTTPException
from ... import cnpj
from ...core import db
from ...finals import FINAL_OK, TREATED # noqa: F401 (the board, files and stats use them)
router = APIRouter()
@@ -40,20 +41,6 @@ def company_names(c, *groups):
for rows in groups for row in rows])
# An item's final counts while its file is still there and scanned clean: the
# same rule that lets an order into the print queue.
FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'"""
# "Arte tratada" (Dropstar, 2026-10-27): a final someone prepared, not the
# customer's own artwork. It is neither the file the system generated from
# their art, nor one of their originals, nor a correction they sent. `f` is
# the final in dtf_local.order_files, `o` its order.
TREATED = """f.kind='final'
AND NOT EXISTS (SELECT 1 FROM dtf_local.print_parts p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id)
AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(o.snapshot->'items') i WHERE i->'uploads' ? f.upload_id::text)
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files k WHERE k.order_id=f.order_id AND k.upload_id=f.upload_id
AND k.kind='correction')"""
def person(column):
"""SQL: the team member's name for the e-mail in `column`, or the e-mail."""
return f'COALESCE((SELECT op.name FROM dtf_local.operators op WHERE op.email={column}), {column})'

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
@@ -28,7 +32,8 @@ def named_files(rows):
name = row['name']
if name.startswith(older):
name = prefix + name[len(older):]
elif not name.startswith(prefix):
# DTF-23-item-1 or, generated again, DTF-23-v2-item-1: already named.
elif not name.startswith(f"DTF-{row['number']}-"):
name = f"{prefix}-{name}"
stem, dot, ext = name.rpartition('.')
copy = 2
@@ -38,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
@@ -49,14 +54,16 @@ def print_ready(c, states, only=None, paid_after=None):
these orders, `paid_after` to the orders paid since then."""
ids = None if only is None else list(only)
rows = c.execute(f'''SELECT o.id AS order_id,o.state,o.number,f.item_index,f.upload_id,u.object_key,u.name,
COALESCE(o.queue_key, extract(epoch FROM o.created_at)) AS position
COALESCE(o.queue_key, extract(epoch FROM o.created_at)) AS position, pp.part
FROM dtf_local.orders o
JOIN dtf_local.order_files f ON f.order_id=o.id JOIN dtf_local.uploads u ON u.id=f.upload_id
LEFT JOIN dtf_local.print_parts pp ON pp.order_id=f.order_id AND pp.item_index=f.item_index
AND pp.upload_id=f.upload_id
WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s))
AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.cancelled_at IS NULL AND {FINAL_OK}
UNION ALL
SELECT o.id,o.state,o.number,p.item_index,pp.upload_id,u.object_key,u.name,
COALESCE(o.queue_key, extract(epoch FROM o.created_at))
COALESCE(o.queue_key, extract(epoch FROM o.created_at)), pp.part
FROM dtf_local.orders o
JOIN dtf_local.print_files p ON p.order_id=o.id
JOIN dtf_local.print_parts pp ON pp.order_id=p.order_id AND pp.item_index=p.item_index
@@ -67,7 +74,7 @@ def print_ready(c, states, only=None, paid_after=None):
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='final'
AND f.active AND f.item_index=p.item_index)
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='correction')
ORDER BY position,order_id,item_index,name''',
ORDER BY position,order_id,item_index,part NULLS LAST,name''',
(list(states), ids, ids, paid_after, paid_after, list(states), ids, ids, paid_after, paid_after)).fetchall()
return rows
@@ -160,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

@@ -149,6 +149,28 @@ def tiny_contacts(q: str = Query(min_length=1, max_length=120), user=Depends(can
raise HTTPException(409, 'O Tiny não está conectado.')
@router.get('/api/operator/tiny/sellers')
def tiny_sellers(user=Depends(can('users'))):
"""Tiny's sellers, for the "Vendedor no Tiny" of each Kanban user: a
Venda they assemble reaches Tiny with that seller (Marcus, 2026-11-17)."""
if os.environ.get('TINY_ADAPTER') != 'tiny':
from ...adapters import FakeTiny
return FakeTiny().list_sellers()
if not tiny.configured():
raise HTTPException(409, 'O Tiny não está conectado.')
try:
return tiny.list_sellers(tiny.TinyOrders())
except tiny.TinyNotConnected:
raise HTTPException(409, 'O Tiny não está conectado.')
except tiny.TinyError as exc:
# Tiny checks the connected user's module permissions on every call:
# our user needs to see Vendedores (app/tiny.py, 2026-10-27).
if ': 403 ' in str(exc) or ': 401 ' in str(exc):
raise HTTPException(409, 'O Tiny recusou a leitura dos vendedores: o usuário do Kanban no Tiny precisa da '
'permissão de ver Vendedores. Resposta do Tiny: ' + str(exc).split(': ', 1)[-1][:200])
raise
@router.post('/api/operator/tiny/connect')
def tiny_connect(user=Depends(can('integrations'))):
"""Start the one-time authorisation of this system in the client's Tiny."""

View File

@@ -9,11 +9,13 @@ from pydantic import Field
from psycopg.types.json import Jsonb
from ... import hotfolder, machine_log, machines, payments, proof, receipt, reviews
from ...cart_pricing import needs_designer
from ...core import db
from ...core.auth import MOVERS, audit, can, may_move, may_reorder, operator
from ...core.auth import (MOVERS, audit, can, machine_bound, may_move, may_reorder, operator, operator_only,
reorder_machine_bound, roles_of)
from ...core.models import Contraction, Move, Resolution, StrictModel, UploadStart
from ...payments import release_files
from ...printjobs import queue as queue_print_files
from ...printjobs import queue as queue_print_files, requeue as requeue_print_files
from ...runtime import BACK, STATES, TRANSITIONS, enqueue, operator_identity, upload_row
from ...scanning import require_clean
from ..uploads import begin_upload
@@ -48,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',
@@ -71,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()
@@ -88,7 +102,7 @@ class MachineChoice(StrictModel):
@router.post('/api/operator/orders/{uid}/machine')
def choose_machine(uid: UUID, body: MachineChoice, request: Request, user=Depends(can('print'))):
"""Exceptional manual choice before printing; the operator's pull is final."""
if request.state.operator['role'] == 'operador':
if operator_only(request.state.operator, 'print'):
raise HTTPException(403, 'A máquina do pedido é a de quem puxa para Imprimindo.')
with db.connect() as c:
current = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
@@ -204,35 +218,9 @@ def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
VALUES(%s,'rev','fin',%s,%s)''', (uid, user, label))
if body.result == 'ok':
# A prova aprovada é a conferência do pai: os arquivos completos
# que o Prumo gerou entram como finais, e o pai segue para a fila.
# Itens que ainda dependem de preparo manual continuam em Arte
# recebida, com o botão de final disponível.
if parent['state'] == 'rec' and not parent['snapshot'].get('treatment'):
generated = c.execute('''SELECT p.item_index,p.upload_id FROM dtf_local.print_files p
WHERE p.order_id=%s AND p.status='ready' AND p.upload_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f
WHERE f.order_id=p.order_id AND f.item_index=p.item_index
AND f.kind='final' AND f.active)
ORDER BY p.item_index''', (parent['id'],)).fetchall()
for row in generated:
c.execute('''INSERT INTO dtf_local.order_files
(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,%s,'final',%s,'Prumo')''',
(uuid4(), parent['id'], row['upload_id'], row['item_index'],
f'Aprovado pela prova do #{card["number"]}'))
treatment_clause = f'AND {TREATED}' if parent['snapshot'].get('treatment') else ''
ready = parent['state'] == 'rec' and all(c.execute(f'''SELECT 1 FROM dtf_local.order_files f
JOIN dtf_local.orders o ON o.id=f.order_id
JOIN dtf_local.uploads u ON u.id=f.upload_id
WHERE f.order_id=%s AND f.item_index=%s AND {FINAL_OK}
{treatment_clause} LIMIT 1''', (parent['id'], i)).fetchone()
for i in range(len(parent['snapshot']['items'])))
c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1, updated_at=now(),
state=CASE WHEN %s THEN 'tra' ELSE state END WHERE id=%s''', (user, ready, parent['id']))
if ready:
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
VALUES(%s,'rec','tra',%s,'Prova OK')''', (parent['id'], user))
c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1,
updated_at=now() WHERE id=%s''', (user, parent['id']))
proof.approve_parent(c, parent, user)
elif parent['state'] in ('rec', 'tra') and not parent['cancelled_at']:
# Back to Arte recebida with the reason; its final is approved again.
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (parent['id'],))
@@ -404,10 +392,10 @@ def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(oper
if not row:
raise HTTPException(404, 'Order not found')
proof.require_unlocked(c, row)
if not may_reorder(request.state.operator['role'], row['state']):
if not may_reorder(roles_of(request.state.operator), row['state']):
raise HTTPException(403, 'Seu perfil não muda a ordem dos pedidos desta etapa.')
mine = request.state.operator['machine']
if (request.state.operator['role'] == 'operador' and row['state'] != 'tra'
if (reorder_machine_bound(request.state.operator, row['state']) and row['state'] != 'tra'
and (not mine or str(row['machine_id'] or '') != mine['id'])):
raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.')
keys = {}
@@ -431,7 +419,7 @@ def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(oper
@router.post('/api/operator/orders/{uid}/move')
def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
if request.state.operator['role'] not in MOVERS:
if not set(roles_of(request.state.operator)) & set(MOVERS):
raise HTTPException(403, 'Seu perfil não permite esta ação.')
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
@@ -447,7 +435,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
back = BACK.get(row['state']) == body.state
if body.state not in TRANSITIONS[row['state']] and not back:
raise HTTPException(409, f"Não dá para ir de {STATES[row['state']]} para {STATES[body.state]}.")
if not may_move(request.state.operator['role'], row['state'], body.state, back):
if not may_move(roles_of(request.state.operator), row['state'], body.state, back):
raise HTTPException(403, 'Só o Revisor manda o pedido para Finalizado.' if body.state == 'fin' and not back
else f"Seu perfil não move pedidos de {STATES[row['state']]} para {STATES[body.state]}.")
if body.state == 'cor' and not body.reason.strip():
@@ -459,7 +447,9 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
account = request.state.operator
session_machine = account['machine']
pulling = row['state'] == 'tra' and body.state == 'imp'
if account['role'] == 'operador':
# The operator's machine rules, when only the Operador profile allows the move.
bound = machine_bound(account, row['state'], body.state, back)
if bound:
if not session_machine:
raise HTTPException(409, 'Escolha a máquina em que você está.')
if not pulling and str(row['machine_id'] or '') != session_machine['id']:
@@ -468,7 +458,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
chosen = body.machine_id or (UUID(session_machine['id']) if session_machine else row['machine_id'])
if not chosen:
raise HTTPException(409, 'Escolha a máquina que está puxando este card.')
if account['role'] == 'operador' and str(chosen) != session_machine['id']:
if bound and str(chosen) != session_machine['id']:
raise HTTPException(409, f"Você está na {session_machine['name']}: o que você puxa vai para ela.")
target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (chosen,)).fetchone()
if not target or not target['active']:
@@ -495,16 +485,16 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=%s AND {FINAL_OK}''', (uid,)).fetchall()
if {r['item_index'] for r in coverage} != set(range(len(row['snapshot']['items']))):
raise HTTPException(409, 'Aprove os arquivos finais de todos os itens antes de mandar para Arte conferida.')
if row['snapshot'].get('treatment') and not row['parent_id']:
if needs_designer(row['snapshot']) and not row['parent_id']:
treated = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
JOIN dtf_local.orders o ON o.id=f.order_id
JOIN dtf_local.uploads u ON u.id=f.upload_id
WHERE f.order_id=%s AND {FINAL_OK} AND {TREATED}''', (uid,)).fetchall()
if {r['item_index'] for r in treated} != set(range(len(row['snapshot']['items']))):
raise HTTPException(409, 'Ajuste Fino pago: envie e aprove a arte do Ajuste Fino de todos os itens antes de entrar na fila.')
# Two at most per machine in Imprimindo (app/machines.py).
if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)):
raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.')
# The machine's places in Imprimindo (app/machines.py).
if body.state == 'imp' and (full := machines.full(c, row['machine_id'], uid)):
raise HTTPException(409, f'{full[0]} já tem {full[1]} em Imprimindo.')
# A proof card ends with its answer, not in Finalizado; its order waits
# for that answer outside the queue (app/proof.py).
if row.get('parent_id') and body.state == 'fin':
@@ -526,14 +516,40 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
if body.state == 'imp' and row['machine_id']:
machine_name = (c.execute('SELECT name FROM dtf_local.machines WHERE id=%s',
(row['machine_id'],)).fetchone() or {}).get('name')
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,machine)
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid,row['state'],body.state,user,body.reason,back,machine_name))
# A pass from Imprimindo to Revisão keeps the items it printed, when
# only some went again (machine_log counts their metres).
printed_items = row.get('print_items') if row['state'] == 'imp' and body.state == 'rev' and not back else None
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,machine,items)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)''', (uid,row['state'],body.state,user,body.reason,back,machine_name,printed_items))
# Back in the queue after a print: only the items whose final changed
# go to the machine again, unless the team already chose (#105).
if body.state == 'tra' and not back and row.get('print_items') is None:
taken = hotfolder.printed(c, [uid]).get(uid)
if taken:
finals = [(r['item_index'], r['upload_id']) for r in c.execute('''SELECT item_index,upload_id
FROM dtf_local.order_files WHERE order_id=%s AND kind='final' AND active''', (uid,)).fetchall()]
default = hotfolder.reprint_default(finals, taken, len(row['snapshot']['items']))
if default:
c.execute('UPDATE dtf_local.orders SET print_items=%s WHERE id=%s', (default, uid))
# Printed (its items kept on the movement above) or finished: the
# choice is done with, and the next pass to the queue works it out
# again from what changed since.
if printed_items is not None or (body.state == 'fin' and not back):
c.execute('UPDATE dtf_local.orders SET print_items=NULL WHERE id=%s', (uid,))
# Back to Imprimindo from Revisão (a mistaken move undone): the items
# that pass printed are the choice again, and only what Flexi had not
# taken goes back to the folder, never the whole order.
if body.state == 'imp' and back:
undone = c.execute('''SELECT items FROM dtf_local.movements WHERE order_id=%s
AND from_state='imp' AND to_state='rev' AND NOT back ORDER BY id DESC LIMIT 1''', (uid,)).fetchone()
if undone and undone['items'] is not None:
c.execute('UPDATE dtf_local.orders SET print_items=%s WHERE id=%s', (undone['items'], uid))
# Pulled to Imprimindo, its files go to its machine's hot folder; out
# of it, what Flexi did not take leaves (item 10).
if row['state'] == 'imp':
hotfolder.stop(c, uid)
if body.state == 'imp':
hotfolder.start(c, uid)
(hotfolder.resume if back else hotfolder.start)(c, uid)
# A pickup reaching Finalizado has its receipt due (item 14), once.
due = body.state == 'fin' and not back and receipt.is_pickup(row['snapshot'])
changed = c.execute('''UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(),
@@ -542,23 +558,38 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
WHERE id=%s RETURNING *''', (body.state, body.state, due, uid)).fetchone()
# Entering the queue (Arte conferida) is Tiny's "Preparando envio";
# Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23).
events = {'tra':'production_started','cor':'correction_needed','fin':'ready'}
if body.state in events and not back and payments.in_tiny(row):
# "Production started" and "ready" reach the customer once per order,
# even if a mistaken move is undone and made again. Each correction
# is a new request, so it keeps one message per movement.
once = body.state in ('tra','fin')
event = {'order_id':str(uid), 'number':row['number'], 'event':events[body.state], 'reason':body.reason,
'customer_path': f'/portal.html?order={uid}'}
# Tiny needs the order (customer, pickup or delivery) and, once the
# sale reached it, its id, to set the situação without a search.
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
(f'{uid}:paid:tiny',)).fetchone()
tiny = {**event, 'order': row['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')}
key = f'{uid}:{events[body.state]}:tiny' if once else f'{uid}:{changed["version"]}:tiny'
enqueue(c, key, 'tiny', tiny)
if not back:
payments.stage_event(c, row, body.state, body.reason, changed['version'])
return changed
class PrintItems(StrictModel):
items: list[int] = Field(min_length=1, max_length=200)
@router.post('/api/operator/orders/{uid}/print-items')
def choose_print_items(uid: UUID, body: PrintItems, user=Depends(can('produce'))):
"""Which items go to the machine this time (Marcus, 2026-11-26, #105):
a reprint sends only those. Every item: all go, as on the first print."""
with db.connect() as c:
row = c.execute('SELECT id,number,state,snapshot,cancelled_at FROM dtf_local.orders WHERE id=%s FOR UPDATE',
(uid,)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
if row['cancelled_at'] or row['state'] not in ('rec', 'tra', 'cor'):
raise HTTPException(409, 'Os itens que vão para a máquina são escolhidos antes de Imprimindo.')
count = len(row['snapshot']['items'])
items = sorted(set(body.items))
if any(i < 0 or i >= count for i in items):
raise HTTPException(422, 'Item do pedido inválido.')
# Every item is kept as the whole list, not NULL: NULL is "not chosen
# yet", which the pass to the queue would replace with the suggestion.
chosen = items
c.execute('UPDATE dtf_local.orders SET print_items=%s, version=version+1, updated_at=now() WHERE id=%s',
(chosen, uid))
audit('order_print_items', order=row['number'], items=','.join(str(i + 1) for i in items), operator=user)
return {'ok': True, 'print_items': chosen}
@router.post('/api/operator/orders/{uid}/print-files')
def regenerate(uid: UUID, user=Depends(can('produce'))):
"""Queue generation again for items that failed or went to manual preparation,
@@ -585,3 +616,42 @@ def regenerate(uid: UUID, user=Depends(can('produce'))):
queue_print_files(c, uid, len(row['snapshot']['items']), only_missing=True)
audit('print_file_requeued', order=str(uid), operator=user, c=c)
return c.execute('SELECT * FROM dtf_local.print_files WHERE order_id=%s ORDER BY item_index', (uid,)).fetchall()
@router.post('/api/operator/orders/{uid}/print-files/again')
def regenerate_ready(uid: UUID, user=Depends(can('produce'))):
"""Generate the print files again although they are ready, for the part
size of now (PRINT_PART_CM): a 15 m part is more than the FlexiPRINT
opens (order #36, 2026-11-17). The finals that were the generated files
stop counting, and an order in Arte conferida or Imprimindo goes back to
Arte recebida, where the new files are approved again; from Imprimindo
what Flexi has not taken leaves the hot folder (app/hotfolder.py)."""
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
if row['cancelled_at']:
raise HTTPException(409, 'Pedido cancelado.')
proof.require_unlocked(c, row)
if row['state'] not in ('rec', 'tra', 'imp'):
raise HTTPException(409, 'O arquivo é gerado de novo até Imprimindo.')
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1",
(uid,)).fetchone():
raise HTTPException(409, 'O cliente mandou uma correção: o arquivo final é preparado à mão.')
c.execute('''UPDATE dtf_local.order_files f SET active=false
WHERE f.order_id=%s AND f.kind='final' AND f.active AND (
EXISTS (SELECT 1 FROM dtf_local.print_parts p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id)
OR EXISTS (SELECT 1 FROM dtf_local.print_files p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id))''',
(uid,))
# The new version tells the board and the folders the files changed;
# every file is new, so any choice of items to reprint is over.
c.execute('''UPDATE dtf_local.orders SET state='rec', print_items=NULL, version=version+1, updated_at=now()
WHERE id=%s''', (uid,))
if row['state'] == 'imp':
hotfolder.stop(c, uid)
if row['state'] != 'rec':
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back)
VALUES(%s,%s,'rec',%s,'Arquivo gerado de novo',true)''', (uid, row['state'], user))
requeue_print_files(c, uid, len(row['snapshot']['items']))
audit('print_file_regenerated', order=str(uid), operator=user)
return {'ok': True}

View File

@@ -136,6 +136,11 @@ def register_order(uid: UUID, body: PaidOutside, user=Depends(can('enter'))):
'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user}
order, created = payments.create_order(c, quote, receipt, body.origin)
if not created:
# A test order holds the quote too (orders.quote_id is unique): say so,
# and how to free it (Sentry DTF-WEB-D).
if payments.is_test(order):
raise HTTPException(409, f"Esta cotação já virou o pedido de teste #{order['number']}. "
'Exclua o pedido de teste para registrar o pagamento.')
raise HTTPException(409, f"Esta cotação já virou o pedido #{order['number']}.")
audit('manual_order_registered', order=str(order['id']), origin=body.origin, operator=user)
return order

View File

@@ -5,6 +5,8 @@ from decimal import Decimal
from fastapi import APIRouter, Depends, HTTPException, Query
from ... import machines, payments, unpaid
from ...machine_stats import pace
from ...cart_pricing import designer_hours
from ...core import db
from ...core.auth import operator
from .common import ORIGINS, REAL_ORDER, TREATED, person
@@ -106,7 +108,7 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
late_rows = c.execute(f'''SELECT s.state,
extract(epoch FROM s.until-s.at) - {waited('s.id', 's.at', 's.until')} AS seconds,
(s.until AT TIME ZONE 'America/Sao_Paulo')::date AS day,
o.snapshot->'treatment' AS treatment
o.snapshot->'treatment' AS treatment, o.snapshot->'redesign' AS redesign
FROM ({spans}) s LEFT JOIN dtf_local.orders o ON o.id=s.id WHERE s.until IS NOT NULL''',
period + period).fetchall()
printed = machine_output(c, start, end)
@@ -214,9 +216,8 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
if not limit:
continue
hours = float(limit['hours'])
treatment = row.get('treatment') or {}
if row['state'] == 'rec' and treatment:
hours += float(treatment.get('hours', 24))
if row['state'] == 'rec':
hours += designer_hours({'treatment': row.get('treatment'), 'redesign': row.get('redesign')})
if row['seconds'] > hours * 3600:
late[row['state']]['count'] += 1
if row['day'] == today:
@@ -336,7 +337,7 @@ def machine_output(c, start, end):
made = float(sum(row['metres'] for row in mine))
result.append({'id': m['id'], 'name': m['name'], 'active': m['active'], 'orders': len(mine),
'metres': made, 'printing_hours': round(hours_in, 2),
'metres_per_hour': round(made / hours_in, 1) if hours_in > 0 else None,
'metres_per_hour': pace(made, hours_in),
'last_finished': last[m['id']].isoformat() if m['id'] in last else None,
'now': {state: m['states'].get(state, 0) for state in ('tra', 'imp')}})
loose = [row for row in done if row['machine_id'] is None]

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
@@ -57,7 +57,8 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
cart = cart_pricing.price_cart(
c, draft['items'], names, coupon_code=code,
customer_document=body.customer.cnpj,
wants_treatment=draft.get('treatment', False))
wants_treatment=draft.get('treatment', False),
wants_redesign=draft.get('redesign', []))
if reason is not None:
freight.quote(body.freight.service, body.freight.postal_code,
sum(Decimal(i['billed_metres']) for i in cart['items']),
@@ -78,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

@@ -95,8 +95,11 @@ def toggle_product(product: str, body: SiteProductToggle, user=Depends(can('mana
def schedule_price(product: str, body: SitePriceNew, user=Depends(can('manage'))):
if product not in catalog.PRODUCTS:
raise HTTPException(404, 'Produto não encontrado.')
if product != 'tratamento' and body.unit_cents <= 0:
if product not in ('tratamento', 'redesenho') and body.unit_cents <= 0:
raise HTTPException(422, 'O preço precisa ser maior que zero.')
# Redesenho is one price per art: its batch band belongs to the basic only.
if product == 'redesenho' and body.bands:
raise HTTPException(422, 'O Redesenho não tem faixas de preço.')
bands = checked_bands(product, body.bands)
now = datetime.now(timezone.utc)
starts_at = body.starts_at or now

View File

@@ -97,6 +97,14 @@ def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))):
with db.connect() as c:
previous = c.execute('SELECT upload_id,captions_id,video_key,captions_key FROM dtf_local.site_videos WHERE id=%s FOR UPDATE',
(video_id,)).fetchone() or {}
# One floating video per product page; checked before any copy, and
# the refusal names the video that holds the product (DTF-WEB-G).
if body.enabled and body.product:
other = c.execute('SELECT id FROM dtf_local.site_videos WHERE id<>%s AND product=%s AND enabled',
(video_id, body.product)).fetchone()
if other:
raise HTTPException(409, f'Este produto já tem o vídeo "{CATALOG.get(other["id"], other["id"])}" '
'publicado. Tire esse do Site antes, ou escolha outro lugar.')
identity = operator_identity(user)
keys = []
for uid, expected, previous_id, previous_key in (
@@ -113,11 +121,6 @@ def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))):
CopySource={'Bucket': storage.bucket, 'Key': upload['object_key']},
Key=key, ContentType=mime, MetadataDirective='REPLACE')
keys.append(key)
if body.enabled and body.product:
other = c.execute('SELECT id FROM dtf_local.site_videos WHERE id<>%s AND product=%s AND enabled',
(video_id, body.product)).fetchone()
if other:
raise HTTPException(409, 'Já existe um vídeo flutuante ativo para este produto.')
c.execute('''INSERT INTO dtf_local.site_videos(id,upload_id,captions_id,video_key,captions_key,product,enabled,updated_by)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)
ON CONFLICT (id) DO UPDATE SET upload_id=EXCLUDED.upload_id,captions_id=EXCLUDED.captions_id,

View File

@@ -10,7 +10,7 @@ from psycopg.types.json import Jsonb
from .. import payments, quote_review
from ..core import db
from ..core.auth import audit, can
from ..core.auth import audit, can, roles_of
from ..core.models import (Customer, Freight, MontadorOrder, QuoteRequest, StampBrand,
StampSizeTable, UploadStart)
from ..runtime import operator_identity
@@ -18,7 +18,8 @@ from .uploads import begin_upload
router = APIRouter()
CODE = re.compile(r'^[A-Za-z0-9_-]{1,40}$')
# Dropstar's codes carry dots (NX.226); not as the first character.
CODE = re.compile(r'^[A-Za-z0-9_-][A-Za-z0-9._-]{0,39}$')
INTERNAL_MISSING = 'Peça à Gestão para completar o cliente interno.'
# Who chooses which kind of order in the montador (Marcus, 2026-11-10): the
# Expedição only Interno, the Vendedor only Venda; Gestão and the
@@ -116,8 +117,8 @@ def montador_order(body: MontadorOrder, request: Request, user=Depends(can('asse
customer, origin atendimento, invoiced and sent to Tiny), at the Site's
table price. A Venda is picked up, travels with a clothing order or ships
with the Site's freight; approve quotes the freight again."""
role = request.state.operator['role']
if body.kind not in MONTADOR_KINDS.get(role, set()):
kinds = set().union(*(MONTADOR_KINDS.get(r, set()) for r in roles_of(request.state.operator)))
if body.kind not in kinds:
raise HTTPException(403, 'Seu perfil não permite este tipo de pedido.')
with db.connect() as c:
if body.kind == 'interno':
@@ -148,6 +149,13 @@ def montador_order(body: MontadorOrder, request: Request, user=Depends(can('asse
# card and in Tiny's internal note.
approved = {**approved, 'kind': body.kind,
**({'with_order': body.with_order} if body.with_order else {})}
# A Venda's seller in Tiny is who assembled it, when their user
# names one (Marcus, 2026-11-17, app/tiny.py order_payload).
if body.kind == 'venda':
seller = c.execute('''SELECT tiny_seller_id AS id, tiny_seller_name AS name
FROM dtf_local.operators WHERE email=%s AND tiny_seller_id IS NOT NULL''', (user,)).fetchone()
if seller:
approved['seller'] = dict(seller)
c.execute('UPDATE dtf_local.quotes SET approved=%s WHERE id=%s',
(Jsonb(approved), quote['id']))
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (quote['id'],)).fetchone()

View File

@@ -24,6 +24,10 @@ router = APIRouter()
# retrying must fit. The per-source bucket bounds abuse, not a real order.
UPLOAD_START_LIMIT = 1000
UPLOAD_START_IP_LIMIT = 3000
# A reservation counts toward the pending cap while its upload is alive: begun
# or given a part in the last 20 minutes (a part is 8 MB). One left behind by an
# interrupted upload stops holding a place long before its hour (DTF-WEB-14).
PENDING_IDLE_MINUTES = 20
def upload_ip_limit(request: Request):
@@ -44,9 +48,10 @@ def begin_upload(body: UploadStart, session_id=Depends(owner), _source=Depends(u
c.execute('SELECT pg_advisory_xact_lock(804208)')
usage = c.execute('''SELECT COALESCE(sum(size),0) AS total,
COALESCE(sum(size) FILTER(WHERE owner=%s),0) AS owned,
count(*) FILTER(WHERE owner=%s AND NOT complete) AS pending
count(*) FILTER(WHERE owner=%s AND NOT complete
AND expires_at > now() + interval '1 hour' - make_interval(mins => %s)) AS pending
FROM dtf_local.uploads WHERE purged_at IS NULL''',
(session_id,session_id)).fetchone()
(session_id,session_id,PENDING_IDLE_MINUTES)).fetchone()
storage_full = (usage['total']+body.size > int(os.environ.get('STORAGE_QUOTA_BYTES','53687091200')) or
usage['owned']+body.size > int(os.environ.get('OWNER_UPLOAD_QUOTA_BYTES','10737418240')))
pending_full = usage['pending'] >= int(os.environ.get('MAX_PENDING_UPLOADS','30'))

View File

@@ -16,23 +16,37 @@ from pydantic import Field, field_validator
from .. import machines, mail, observability
from ..core import db
from ..core.auth import (CAPABILITIES, MACHINE_QUESTION, audit, can, may_move, may_reorder, password_hash,
password_matches, signed_in)
from ..core.auth import (CAPABILITIES, audit, can, has, machine_bound, machine_question, may_move, may_reorder,
password_hash, password_matches, roles_of, signed_in)
from ..core.models import StrictModel
from ..runtime import BACK, ENVIRONMENT, STATES, TRANSITIONS
router = APIRouter()
class TinySeller(StrictModel):
id: int = Field(gt=0)
name: str = Field(min_length=1, max_length=120)
ASSIGNABLE = Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao']
class UserIn(StrictModel):
# The profiles an administrator may give; superadmin only comes from the console.
name: str = Field(min_length=1, max_length=80)
email: str = Field(min_length=3, max_length=254)
role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao']
# The main profile, and every other one the user has (Marcus, 2026-11-26):
# what they may do is the sum.
role: ASSIGNABLE
roles: list[ASSIGNABLE] = Field(default_factory=list, max_length=8)
password: str | None = Field(default=None, min_length=8, max_length=128)
active: bool = True
# No longer used: an operator's machine is the one chosen after signing in
# (item 12). Kept so a page loaded before still saves.
machines: list[UUID] = Field(default_factory=list, max_length=50)
# The Tiny seller this user is (app/tiny.py list_sellers): a Venda they
# assemble reaches Tiny with it. None: no seller.
tiny_seller: TinySeller | None = None
@field_validator('email')
@classmethod
@@ -42,6 +56,10 @@ class UserIn(StrictModel):
raise ValueError('Informe um e-mail válido.')
return value
def profiles(self):
"""The main profile first, then the others, each once."""
return [self.role] + [r for r in dict.fromkeys(self.roles) if r != self.role]
class MachineIn(StrictModel):
name: str = Field(min_length=1, max_length=60)
@@ -49,11 +67,18 @@ class MachineIn(StrictModel):
active: bool = True
# Metres open before the next order goes to another machine; None is no limit.
limit_metres: Decimal | None = Field(default=None, gt=0, le=99999, decimal_places=1)
# Orders at once in Imprimindo and files in its hot folder (app/machines.py);
# None keeps what it has, or machines.DEFAULT_PLACES for a new one.
places: int | None = Field(default=None, ge=1, le=machines.MAX_PLACES)
# No longer used (item 12): who is on a machine is who chose it after
# signing in. Kept so a page loaded before still saves.
operators: list[UUID] | None = Field(default=None, max_length=200)
class MachinePlaces(StrictModel):
places: int = Field(ge=1, le=machines.MAX_PLACES)
class PasswordChange(StrictModel):
current: str = Field(min_length=1, max_length=128)
new: str = Field(min_length=8, max_length=128)
@@ -65,19 +90,22 @@ def me(request: Request):
their profile makes (forward, and the step back) and the columns whose
order they set."""
account = signed_in(request)
role = account['role']
moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(role, a, b)]
moves += [[a, b] for a, b in BACK.items() if may_move(role, a, b, back=True)]
return {'email': account['email'], 'name': account['name'], 'role': role,
role, roles = account['role'], roles_of(account)
moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(roles, a, b)]
moves += [[a, b] for a, b in BACK.items() if may_move(roles, a, b, back=True)]
return {'email': account['email'], 'name': account['name'], 'role': role, 'roles': list(roles),
# Public by design: the Kanban browser initialises Sentry with these.
'sentry_dsn_web': os.environ.get('SENTRY_DSN_WEB', '').strip(),
'sentry_environment': os.environ.get('SENTRY_ENVIRONMENT') or ENVIRONMENT,
'sentry_release': observability.release() or '',
# The machine this session is on, and whether to ask (item 12).
'machine': account['machine'], 'machine_question': MACHINE_QUESTION.get(role),
'machine': account['machine'], 'machine_question': machine_question(account),
'machine_answered': account['machine_answered'],
'can': sorted(cap for cap, roles in CAPABILITIES.items() if role in roles),
'moves': moves, 'reorder': [state for state in STATES if may_reorder(role, state)]}
'can': sorted(cap for cap in CAPABILITIES if has(account, cap)),
'moves': moves, 'reorder': [state for state in STATES if may_reorder(roles, state)],
# The moves only the Operador profile allows: kept to the session's machine.
'machine_moves': [[a, b] for a, b in moves
if machine_bound(account, a, b, back=BACK.get(a) == b)]}
class MachineAnswer(StrictModel):
@@ -94,7 +122,7 @@ def choose_session_machine(body: MachineAnswer, request: Request):
person runs two machines from two computers. Someone else already on it is
a warning, not a refusal: shifts overlap for a few minutes."""
account = signed_in(request)
question = MACHINE_QUESTION.get(account['role'])
question = machine_question(account)
if not question:
raise HTTPException(403, 'Seu perfil não trabalha em máquina.')
with db.connect() as c:
@@ -133,7 +161,8 @@ def change_password(body: PasswordChange, request: Request):
def user_rows(c):
"""Every account, with the machines its open sessions are on now (item 12)."""
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at,
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.roles,o.active,o.last_login_at,o.created_at,
o.tiny_seller_id,o.tiny_seller_name,
COALESCE(array_agg(DISTINCT s.machine_id) FILTER (WHERE s.machine_id IS NOT NULL), '{}') AS machines,
-- The last use of any open session: "Ativo agora" in Usuários.
(SELECT max(x.seen_at) FROM dtf_local.operator_sessions x
@@ -143,6 +172,9 @@ def user_rows(c):
GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()
for row in rows:
row['machines'] = [str(m) for m in row['machines']]
row['roles'] = list(roles_of(row))
seller_id, seller_name = row.pop('tiny_seller_id'), row.pop('tiny_seller_name')
row['tiny_seller'] = {'id': seller_id, 'name': seller_name} if seller_id else None
return rows
@@ -170,10 +202,12 @@ def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.operators WHERE email=%s', (body.email,)).fetchone():
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active)
VALUES(%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
body.role, body.active))
audit('operator_created', operator=user, account=body.email, role=body.role)
seller = body.tiny_seller
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,roles,active,tiny_seller_id,tiny_seller_name)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
body.role, body.profiles(), body.active,
seller and seller.id, seller and seller.name))
audit('operator_created', operator=user, account=body.email, role='/'.join(body.profiles()))
return {'id': str(uid)}
@@ -184,13 +218,16 @@ def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('use
row = target(c, uid, request)
# A superadmin keeps that profile: the form offers only the assignable ones.
role = row['role'] if row['role'] == 'superadmin' else body.role
if str(row['id']) == str(me_['id']) and (not body.active or role != row['role']):
roles = list(roles_of(row)) if row['role'] == 'superadmin' else body.profiles()
if str(row['id']) == str(me_['id']) and (not body.active or role != row['role'] or roles != list(roles_of(row))):
raise HTTPException(409, 'Você não pode desativar a sua conta nem mudar o seu perfil.')
if body.email != row['email'] and c.execute(
'SELECT 1 FROM dtf_local.operators WHERE email=%s AND id<>%s', (body.email, uid)).fetchone():
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
c.execute('UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,active=%s WHERE id=%s',
(body.name.strip(), body.email, role, body.active, uid))
seller = body.tiny_seller
c.execute('''UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,roles=%s,active=%s,tiny_seller_id=%s,
tiny_seller_name=%s WHERE id=%s''', (body.name.strip(), body.email, role, roles, body.active,
seller and seller.id, seller and seller.name, uid))
if body.password:
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.password), uid))
if body.email != row['email']:
@@ -198,7 +235,7 @@ def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('use
if not body.active or body.password:
# Disabled, or given a new password: whoever was signed in signs in again.
c.execute('DELETE FROM dtf_local.operator_sessions WHERE username=%s', (body.email,))
audit('operator_updated', operator=user, account=body.email, role=role, active=body.active,
audit('operator_updated', operator=user, account=body.email, role='/'.join(roles), active=body.active,
password_reset=bool(body.password))
return {'ok': True}
@@ -232,10 +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) VALUES(%s,%s,%s,%s,%s)',
(mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres))
# 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)}
@@ -243,12 +284,13 @@ 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 not c.execute('''UPDATE dtf_local.machines SET name=%s,products=%s,active=%s,limit_metres=%s
WHERE id=%s RETURNING id''', (body.name.strip(), sorted(set(body.products)), body.active,
body.limit_metres, mid)).fetchone():
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,
body.places, mid)).fetchone():
raise HTTPException(404, 'Máquina não encontrada.')
if not body.active:
release_sessions(c, mid)
@@ -256,6 +298,20 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
return {'ok': True}
@router.post('/api/operator/machines/{mid}/places')
def machine_places(mid: UUID, body: MachinePlaces, user=Depends(can('manage'))):
"""How many orders the machine takes in Imprimindo, and files in its hot
folder: Admin and Gestão set it from the machine's sheet (Marcus,
2026-11-17). Orders already there stay; the next waits for a place."""
with db.connect() as c:
row = c.execute('UPDATE dtf_local.machines SET places=%s WHERE id=%s RETURNING name',
(body.places, mid)).fetchone()
if not row:
raise HTTPException(404, 'Máquina não encontrada.')
audit('machine_places', operator=user, machine=row['name'], places=body.places)
return {'ok': True}
@router.post('/api/operator/machines/{mid}/delete')
def delete_machine(mid: UUID, user=Depends(can('users'))):
"""Its orders lose that machine; its operators lose the session choice."""

View File

@@ -4,9 +4,13 @@ Configuration and shared helpers are in local.runtime; every route lives in a
router under local.api. This module creates the application, applies the
cross-cutting middleware, and includes them.
"""
import asyncio
import logging
import time
from contextlib import asynccontextmanager
from fastapi import FastAPI
import psycopg
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.middleware.trustedhost import TrustedHostMiddleware
@@ -19,17 +23,47 @@ from .api import artwork, customer, health, machine_log, operator, orders, payme
observability.init('api')
RETRY_SECONDS = (1, 2, 4, 8, 15)
STARTUP_BUDGET_SECONDS = 90
@asynccontextmanager
async def lifespan(app):
with db.connect() as c:
c.execute('SELECT 1 FROM dtf_local.operator_sessions LIMIT 1')
storage.health()
# A redeploy briefly removes the database name; wait it out, warning once
# per attempt (a warning, not an error: Sentry only takes errors).
deadline = time.monotonic() + STARTUP_BUDGET_SECONDS
attempt = 0
while True:
try:
with db.connect() as c:
c.execute('SELECT 1 FROM dtf_local.operator_sessions LIMIT 1')
storage.health()
break
except Exception:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise
delay = min(RETRY_SECONDS[min(attempt, len(RETRY_SECONDS) - 1)], remaining)
logging.warning('Database not reachable yet, retrying in %d s', max(1, round(delay)))
await asyncio.sleep(delay)
attempt += 1
yield
app = FastAPI(title='DTF Portal/API', lifespan=lifespan, docs_url=None, redoc_url=None)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=ALLOWED_HOSTS)
# The seconds a restart takes the database away (Sentry DTF-API-9): the
# request is answered "try again" instead of a 500, and only a warning is
# logged (Sentry takes errors). The page retries by itself or on reload.
RESTARTING = 'O servidor está reiniciando. Tente de novo em alguns segundos.'
@app.exception_handler(psycopg.OperationalError)
async def database_unavailable(request: Request, exc):
logging.warning('Database unavailable for %s %s: %s', request.method, request.url.path, exc)
return JSONResponse({'detail': RESTARTING}, status_code=503, headers={'Retry-After': '5'})
@app.middleware('http')
async def safe_headers(request, call_next):
if request.method not in ('GET','HEAD','OPTIONS'):

View File

@@ -74,22 +74,45 @@ 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.')
revived = set()
for ref in body.files:
if ref.upload_id in kept:
continue
corrected = correction_owner(c, order, ref, kind)
upload = upload_row(c, ref.upload_id, corrected or generated_owner(c, order, ref, kind) or identity, lock=True)
generated = None if corrected else generated_owner(c, order, ref, kind)
upload = upload_row(c, ref.upload_id, corrected or generated or identity, lock=True)
if not upload['complete']:
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar.')
require_clean(upload)
if kind == 'final':
require_final_png(storage, upload)
# Attached once, except a correction approved as its own final.
if c.execute('SELECT id FROM dtf_local.order_files WHERE upload_id=%s'+(" AND kind<>'correction'" if corrected else ''),
(ref.upload_id,)).fetchone():
# Attached once, except a correction approved as its own final, and a
# generated file or a correction that was this item's final and
# stopped counting (a step back, Correção): it is turned back on
# (Sentry DTF-WEB-10).
rows = c.execute('SELECT order_id,item_index,kind FROM dtf_local.order_files WHERE upload_id=%s'
+ (" AND kind<>'correction'" if corrected else ''), (ref.upload_id,)).fetchall()
if rows and (corrected or generated) and all(
r['order_id'] == order['id'] and r['kind'] == 'final' and r['item_index'] == ref.item_index for r in rows):
revived.add(ref.upload_id)
elif rows:
raise HTTPException(409, 'Este arquivo já está no pedido. Envie uma nova versão.')
# A new customer correction supersedes every final prepared from earlier
# artwork, including finals uploaded while this order was in correction.
@@ -97,8 +120,11 @@ def submit_files(c, order, body, identity, kind, actor):
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind IN ('correction','final')", (order['id'],))
else:
c.execute('UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind=%s', (order['id'],kind))
# A final changed: which items go to the machine again is worked out
# anew when the order enters the queue (#105).
c.execute('UPDATE dtf_local.orders SET print_items=NULL WHERE id=%s', (order['id'],))
for ref in body.files:
if ref.upload_id in kept:
if ref.upload_id in kept or ref.upload_id in revived:
c.execute("UPDATE dtf_local.order_files SET active=true WHERE order_id=%s AND upload_id=%s AND kind='final'",
(order['id'], ref.upload_id))
continue

View File

@@ -43,6 +43,35 @@ def treatment_price(items, choice, offer):
return {'cents': unit * count, 'hours': 24, 'arts': count, 'unit_cents': unit}
def redesign_price(items, choice, offer):
"""Ajuste Fino Redesenho for the chosen arts: one price per art, never a
band. {} when it is not offered or no art is chosen."""
if not offer or not offer.get('enabled') or offer.get('unit_cents', 0) <= 0:
return {}
arts = chosen_arts(items, choice)
if not arts:
return {}
count = len(arts)
unit = offer['unit_cents']
return {'cents': unit * count, 'hours': 48, 'arts': count, 'unit_cents': unit}
def designer_hours(snapshot):
"""The extra hours the paid designer work adds to the deadline: 48 h when
any art was sent to Redesenho, else 24 h for the basic Ajuste Fino."""
# The hours recorded with the order win (an order keeps what it was sold
# with); 48 and 24 are the defaults for snapshots that carry none.
hours = [int((snapshot[key] if isinstance(snapshot.get(key), dict) else {}).get('hours') or default)
for key, default in (('redesign', 48), ('treatment', 24)) if snapshot.get(key)]
return max(hours, default=0)
def needs_designer(snapshot):
"""Whether a designer must prepare the final PNG before the print queue:
a paid Ajuste Fino or Redesenho on any art."""
return bool(snapshot.get('treatment') or snapshot.get('redesign'))
def price_items(items, names, catalog_now, manual_extra):
"""Price the items without a database: price() per item with the product's
base price and the manual extra, bill_splits, then the band of each mode's
@@ -70,13 +99,15 @@ def price_items(items, names, catalog_now, manual_extra):
def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
wants_treatment=False, treatment_rule=True):
wants_treatment=False, wants_redesign=(), treatment_rule=True):
"""Price a cart exactly as an order is charged. Returns
{'items': [priced item dicts], 'items_total': int, 'coupon': dict|None,
'treatment': dict, 'treatment_cents': int, 'grade_flags': dict}.
Raises HTTPException(422) for a product switched off, a required Ajuste
Fino the cart did not ask for, or a refused coupon.
`treatment_rule=False` is for the montador, which assembles the sheet."""
'treatment': dict, 'treatment_cents': int, 'redesign': dict,
'redesign_cents': int, 'grade_flags': dict}.
Raises HTTPException(422) for a product switched off, a Redesenho not
offered, a required designer service the cart did not ask for, or a
refused coupon. `treatment_rule=False` is for the montador, which
assembles the sheet."""
from fastapi import HTTPException
catalog_now = catalog.current(c)
for item in items:
@@ -89,7 +120,12 @@ def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
if not treatment_rule:
flags.pop('tratamento', None)
treatment = treatment_price(items, wants_treatment, offer)
if 'tratamento' in flags and not treatment:
redesign = redesign_price(items, wants_redesign, catalog_now['redesenho'])
if chosen_arts(items, wants_redesign) and not redesign:
raise HTTPException(422, 'O Redesenho não está disponível agora.')
# The grade rule wants a designer on the art: the stronger Redesenho
# satisfies it just as the basic Ajuste Fino does.
if 'tratamento' in flags and not treatment and not redesign:
raise HTTPException(422, grade_rules.treatment_message(flags['tratamento']))
coupon = None
if coupon_code:
@@ -99,4 +135,6 @@ def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
'coupon': coupon,
'treatment': treatment,
'treatment_cents': treatment.get('cents', 0),
'redesign': redesign,
'redesign_cents': redesign.get('cents', 0),
'grade_flags': flags}

View File

@@ -9,7 +9,8 @@ and an approved quote keeps the price it was approved with.
`tratamento` is Ajuste Fino (front 1a): a price per art, with an optional band
by the order's number of arts (front 8.2). It counts as offered only when it is
switched on and priced above zero.
switched on and priced above zero. `redesenho` is Ajuste Fino Redesenho (front
1b): one price per art, no bands, and the same rule for being offered.
A price row may carry bands by the order's quantity of that product (metres, or
arts for Ajuste Fino): below the first band the base price, then the highest
@@ -20,9 +21,9 @@ from decimal import Decimal
from .core import pricing
# The modes sold by the metre, and the treatment sold per order.
# The modes sold by the metre, and the services sold per art.
MODES = ('file', 'avulsa', 'uvfile', 'uv', 'premium')
PRODUCTS = (*MODES, 'tratamento')
PRODUCTS = (*MODES, 'tratamento', 'redesenho')
TITLES = {
'file': 'Têxtil folha pronta',
@@ -31,14 +32,21 @@ TITLES = {
'uv': 'UV artes avulsas',
'premium': 'Têxtil Premium · 8 passadas',
'tratamento': 'Ajuste Fino',
'redesenho': 'Ajuste Fino Redesenho',
}
UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro',
'premium': 'metro', 'tratamento': 'arte'}
'premium': 'metro', 'tratamento': 'arte', 'redesenho': 'arte'}
def fallback_cents(product: str) -> int:
"""The price in the code, used until a row in the database takes over."""
return pricing.treatment_cents() if product == 'tratamento' else pricing.PRICES[product]
"""The price in the code, used until a row in the database takes over.
Redesenho has no price in the code: it starts disabled and unpriced, and
Gestão sets both in the Site tab."""
if product == 'tratamento':
return pricing.treatment_cents()
if product == 'redesenho':
return 0
return pricing.PRICES[product]
def band_price(base_cents: int, bands: list, quantity: Decimal) -> int:

View File

@@ -4,6 +4,9 @@ import os
import secrets
import logging
import json
import psycopg
import sys
import time
from uuid import UUID, uuid4
from fastapi import HTTPException, Request
from ..core.db import connect
@@ -71,10 +74,14 @@ def transfer_guest(c, previous, identity):
c.execute(f'UPDATE dtf_local.{table} SET owner=%s WHERE owner=%s', (identity,previous['owner']))
c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s', (previous['owner'],))
_persistence_error_at = None
def audit(event, c=None, **fields):
"""Record a security event. `c` is the caller's open connection, when there
is one, so the event commits with that transaction instead of opening a
second connection."""
global _persistence_error_at
# Only explicit metadata: never cookies, passwords, signed URLs or request bodies.
logging.getLogger('dtf.security').warning(json.dumps({'event':event, **fields}, sort_keys=True))
try:
@@ -85,8 +92,14 @@ def audit(event, c=None, **fields):
with connect() as c:
c.execute('INSERT INTO dtf_local.security_events(event,details) VALUES(%s,%s)',(event,Jsonb(fields)))
except Exception:
# Logging must still work during a DB outage without recursively auditing itself.
logging.getLogger('dtf.security').error('Security event persistence unavailable')
# Logging must still work during a DB outage without recursively auditing
# itself; the error is reported once per minute, not on every event.
now = time.monotonic()
if _persistence_error_at is None or now-_persistence_error_at >= 60:
_persistence_error_at = now
log = logging.getLogger('dtf.security')
(log.warning if isinstance(sys.exc_info()[1], psycopg.OperationalError) else log.error)(
'Security event persistence unavailable')
def rate_limit(scope, identity, limit, seconds=900):
key = hashlib.sha256((scope+'|'+identity).encode()).hexdigest()
@@ -194,9 +207,19 @@ MACHINE_QUESTION = {'operador': 'required', 'gestao': 'optional', 'admin': 'opti
MOVERS = MANAGERS + tuple(MOVES)
def _profiles(role):
"""One profile or several: a user with more than one profile may do what
any of them may (Marcus, 2026-11-26: operador/revisor, gestor/operador)."""
return (role,) if isinstance(role, str) else tuple(role)
def may_move(role, from_state, to_state, back=False):
"""Whether this profile may move a card; `back` is the step back that
undoes the move to_state -> from_state."""
"""Whether this profile (or any of these) may move a card; `back` is the
step back that undoes the move to_state -> from_state."""
return any(_may_move(r, from_state, to_state, back) for r in _profiles(role))
def _may_move(role, from_state, to_state, back):
if back:
return role in MANAGERS or (to_state, from_state) in MOVES.get(role, ())
if to_state == 'fin':
@@ -209,7 +232,44 @@ def may_move(role, from_state, to_state, back=False):
def may_reorder(role, state):
"""Changing a card's place in its column, the order it is worked in: for
whoever takes cards forward out of it."""
return role in MANAGERS or any(a == state and b != 'cor' for a, b in MOVES.get(role, ()))
return any(r in MANAGERS or any(a == state and b != 'cor' for a, b in MOVES.get(r, ()))
for r in _profiles(role))
def roles_of(account):
"""Every profile of a signed-in user, the main one first. Rows written
before profiles became a list have only `role`."""
return tuple(account.get('roles') or ()) or (account['role'],)
def has(account, capability):
return any(r in CAPABILITIES[capability] for r in roles_of(account))
def machine_bound(account, from_state, to_state, back=False):
"""Whether only the Operador profile allows this move, so the operator's
machine rules apply to it: an operator who is also Revisor releases any
machine's sheet, as a Revisor does."""
roles = roles_of(account)
return 'operador' in roles and not may_move([r for r in roles if r != 'operador'], from_state, to_state, back)
def reorder_machine_bound(account, state):
roles = roles_of(account)
return 'operador' in roles and not may_reorder([r for r in roles if r != 'operador'], state)
def operator_only(account, capability):
"""Whether this capability comes to the user only through Operador."""
roles = roles_of(account)
return 'operador' in roles and not any(r in CAPABILITIES[capability] for r in roles if r != 'operador')
def machine_question(account):
""""Em qual máquina você está?": optional for management, required for an
operator who is nothing more, never for the others."""
answers = {MACHINE_QUESTION.get(r) for r in roles_of(account)}
return 'optional' if 'optional' in answers else 'required' if 'required' in answers else None
def signed_in(request: Request):
@@ -220,7 +280,7 @@ def signed_in(request: Request):
raise HTTPException(401, 'Entre no Kanban.')
digest = hashlib.sha256(token.encode()).hexdigest()
with connect() as c:
row = c.execute('''SELECT o.id,o.email,o.name,o.role,s.machine_answered,m.id AS machine_id,m.name AS machine_name
row = c.execute('''SELECT o.id,o.email,o.name,o.role,o.roles,s.machine_answered,m.id AS machine_id,m.name AS machine_name
FROM dtf_local.operator_sessions s
JOIN dtf_local.operators o ON o.email=s.username AND o.active
LEFT JOIN dtf_local.machines m ON m.id=s.machine_id
@@ -245,7 +305,7 @@ def can(capability):
returns the operator's e-mail, as the routes record it."""
def check(request: Request):
account = signed_in(request)
if account['role'] not in CAPABILITIES[capability]:
if not has(account, capability):
raise HTTPException(403, 'Seu perfil não permite esta ação.')
return account['email']
return check
@@ -256,7 +316,7 @@ def can_any(*capabilities):
and returns the operator's e-mail, as the routes record it."""
def check(request: Request):
account = signed_in(request)
if not any(account['role'] in CAPABILITIES[capability] for capability in capabilities):
if not any(has(account, capability) for capability in capabilities):
raise HTTPException(403, 'Seu perfil não permite esta ação.')
return account['email']
return check

View File

@@ -127,6 +127,11 @@ class ProductionSource(StrictModel):
rotation_degrees: Literal[0, 90] = 0
mirrored: bool = False
measurement: Literal['file', 'customer']
# The fully transparent strips the Site cut from the top and the bottom of
# a ready sheet (Marcus, 2026-11-18): length_cm is what is left, billed
# 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)
class ProductionPlacement(StrictModel):
source_index: int = Field(ge=0, le=199, strict=True)
@@ -160,6 +165,37 @@ class Split(StrictModel):
of: int = Field(ge=2, le=10, strict=True)
UV_MODES = ('uvfile', 'uv')
SHEET_MODES = ('file', 'uvfile', 'premium')
# Clear film between the copies of a ready sheet, and between its sheets, for
# cutting; billed like the rest (Marcus, 2026-11-26).
SHEET_GAP_CM = Decimal('0.8')
SHEET_GAP_CHANGED = ('O espaço entre as cópias da folha pronta passou a ser de 8 mm. '
'Remova este item do carrinho e adicione de novo.')
def check_sheet_gaps(items):
"""A ready sheet's copies and sheets are SHEET_GAP_CM apart. Only a new
cart is held to it: a quote made before still goes through review."""
for item in items:
if item.mode not in SHEET_MODES:
continue
placements = sorted(item.production.placements, key=lambda p: p.y_cm)
for above, below in zip(placements, placements[1:]):
if below.y_cm < above.y_cm + above.length_cm + SHEET_GAP_CM - Decimal('0.02'):
raise ValueError(SHEET_GAP_CHANGED)
ONE_MACHINE = ('Esse produto é impresso em outra máquina e precisa de um pedido separado. '
'Finalize este pedido e faça um novo com ele.')
def check_one_machine(items):
"""One order, one machine (Marcus, 2026-11-26): UV and textile never share
an order, since its card goes to one machine. Basic and premium textile
print on the same machines and may."""
if len({item.mode in UV_MODES for item in items}) > 1:
raise ValueError(ONE_MACHINE)
def check_splits(items):
"""Every split group has each of its parts once, of one product."""
groups = {}
@@ -184,6 +220,10 @@ class Item(StrictModel):
# Residue dots under 2 mm the customer accepted printing on a ready sheet,
# rather than erasing them (Dropstar, 2026-10-29): 0 when none.
residue_accepted: int = Field(default=0, ge=0, le=1000000, strict=True)
# Pieces of a ready sheet under 5 mm from another, as the Site measured
# them: shown on the Kanban card so the room sees it before printing
# (Marcus, 2026-11-26, #81). 0 when none.
close_pieces: int = Field(default=0, ge=0, le=1000000, strict=True)
# The thinnest stroke the browser measured, in pixels at 300 DPI, and its
# contraction class (Dropstar, 2026-10-30): up to 4 C1, 5 to 19 C2, 20+ C3.
stroke_px: int | None = Field(default=None, ge=1, le=10000, strict=True)
@@ -224,6 +264,8 @@ class Item(StrictModel):
raise ValueError('Production source does not fit the selected product')
if is_sheet and (source.rotation_degrees or source.mirrored):
raise ValueError('Finished sheets cannot be rotated or mirrored by the layout')
if (source.trim_top_cm or source.trim_bottom_cm) and (not is_sheet or source.measurement != 'file'):
raise ValueError('Only a measured finished sheet has its empty strips cut')
# A textile transfer is pressed face down: mirrored, it prints backwards.
if self.mode == 'avulsa' and source.mirrored:
raise ValueError('Textile artwork cannot be mirrored')
@@ -249,21 +291,46 @@ 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
TIMING_MAX = {'page_ms': 600000, 'upload_ms': 3600000, 'upload_bytes': 10**12,
'analysis_ms': 3600000, 'montage_ms': 3600000}
class ClientTimings(StrictModel):
"""What the browser measured on the way to a quote (item 0.12).
They are only numbers for Números; a cart may send none of them, and the
server never uses them to price or accept an order.
server never uses them to price or accept an order: a value out of range
(a cart left open for hours, DTF-WEB-9) is dropped, never refused.
"""
page_ms: int | None = Field(default=None, ge=0, le=600000)
upload_ms: int | None = Field(default=None, ge=0, le=3600000)
upload_bytes: int | None = Field(default=None, ge=0, le=10**12)
analysis_ms: int | None = Field(default=None, ge=0, le=3600000)
montage_ms: int | None = Field(default=None, ge=0, le=3600000)
page_ms: int | None = None
upload_ms: int | None = None
upload_bytes: int | None = None
analysis_ms: int | None = None
montage_ms: int | None = None
@model_validator(mode='before')
@classmethod
def drop_out_of_range(cls, data):
if not isinstance(data, dict):
return data
return {name: value for name, value in data.items()
if name not in TIMING_MAX or (isinstance(value, int) and not isinstance(value, bool)
and 0 <= value <= TIMING_MAX[name])}
class QuoteRequest(StrictModel):
@@ -277,6 +344,9 @@ class QuoteRequest(StrictModel):
# Ajuste Fino (front 1a): true selects every art of the cart (old carts and
# the grade rule), a list selects [item_index, source_index] arts.
treatment: bool | list[tuple[int, int]] = False
# Ajuste Fino Redesenho (front 1b): the arts sent to be redrawn, in the
# same [item_index, source_index] identifiers. One service per art.
redesign: list[tuple[int, int]] = Field(default_factory=list)
# A coupon code typed at checkout (front 8.3); the server prices it.
coupon: str | None = Field(default=None, max_length=30)
# What the browser measured while the customer built the cart (item 0.12).
@@ -285,6 +355,8 @@ class QuoteRequest(StrictModel):
@model_validator(mode='after')
def splits_complete(self):
check_splits(self.items)
check_one_machine(self.items)
check_sheet_gaps(self.items)
return self
@model_validator(mode='after')
@@ -300,6 +372,24 @@ class QuoteRequest(StrictModel):
seen.add((item_index, source_index))
return self
@model_validator(mode='after')
def redesign_arts_exist(self):
seen = set()
for item_index, source_index in self.redesign:
if (item_index < 0 or source_index < 0 or item_index >= len(self.items)
or source_index >= len(self.items[item_index].production.sources)):
raise ValueError('Redesenho: arte não encontrada no pedido.')
if (item_index, source_index) in seen:
raise ValueError('Redesenho: cada arte aparece uma vez.')
seen.add((item_index, source_index))
# The customer chooses one service per art: basic or Redesenho.
if self.treatment is True:
if seen:
raise ValueError('Escolha Ajuste Fino ou Redesenho para cada arte, não os dois.')
elif isinstance(self.treatment, list) and seen & {(i, s) for i, s in self.treatment}:
raise ValueError('Escolha Ajuste Fino ou Redesenho para cada arte, não os dois.')
return self
@model_validator(mode='after')
def destination_matches_freight(self):
if self.freight.service == 'pickup':
@@ -357,6 +447,7 @@ class Review(StrictModel):
@model_validator(mode='after')
def splits_complete(self):
check_splits(self.items)
check_one_machine(self.items)
return self
class Pay(StrictModel):
@@ -371,8 +462,8 @@ class PaymentMethod(StrictModel):
# Up to 3, as Dropstar sells; the card form offers no more.
installments: int = Field(default=1, ge=1, le=3, strict=True)
issuer_id: str | None = Field(default=None, max_length=40)
# The cardholder's document from the card form: for a card, the payer is
# the cardholder, not necessarily the company on the invoice.
# The document in the card form, which opens with the order's: the payer
# when it is a valid CPF or CNPJ (app/mercadopago.py payer).
payer_document_type: Literal['CPF', 'CNPJ'] | None = None
payer_document: str | None = Field(default=None, pattern=r'^[0-9]{11,14}$')

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

14
app/finals.py Normal file
View File

@@ -0,0 +1,14 @@
"""Which of an order's finals count: shared by the board, the proof and the worker."""
# An item's final counts while its file is still there and scanned clean: the
# same rule that lets an order into the print queue.
FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'"""
# "Arte tratada" (Dropstar, 2026-10-27): a final someone prepared, not the
# customer's own artwork. It is neither the file the system generated from
# their art, nor one of their originals, nor a correction they sent. `f` is
# the final in dtf_local.order_files, `o` its order.
TREATED = """f.kind='final'
AND NOT EXISTS (SELECT 1 FROM dtf_local.print_parts p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id)
AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(o.snapshot->'items') i WHERE i->'uploads' ? f.upload_id::text)
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files k WHERE k.order_id=f.order_id AND k.upload_id=f.upload_id
AND k.kind='correction')"""

View File

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

View File

@@ -4,9 +4,10 @@ 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, never more than two in
the folder at once. The third is written when Flexi takes the first.
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.
Only the server knows what each folder should get, and the Kanban's
computers write it: a part is claimed by one computer, so two never write
@@ -14,7 +15,8 @@ the same file and Flexi never prints it twice. A claim that did not finish
goes back to the queue. A written part that is gone from its folder was
taken by Flexi, and is never written again. A card that leaves Imprimindo
(Revisão, Correção, a step back, a cancellation) withdraws what Flexi has not
taken yet, and its computer deletes it.
taken yet, and its computer deletes it. A step back from Revisão to
Imprimindo writes again only what Flexi had not taken (resume()).
Each part's life is one row of dtf_local.hot_parts:
queued -> claimed -> written -> consumed, or withdraw -> gone.
@@ -23,8 +25,6 @@ from datetime import timedelta
# The machines' folders, inside the Kanban's main folder (Dropstar, 2026-10-30).
PRINTING_FOLDER = '3. Imprimindo'
# Two parts at most in a machine's folder (Dropstar, 2026-10-30).
IN_FOLDER = 2
# A computer that claimed a part and never said it was written.
CLAIM_TIMEOUT = timedelta(minutes=10)
CLASSES = ('C1', 'C2', 'C3')
@@ -53,10 +53,17 @@ def folder_class(order, index):
def start(c, order_id):
"""The order entered Imprimindo: its approved finals queue for its
machine's folder, item by item, part by part."""
machine's folder, item by item, part by part; on a reprint only the items
chosen to go again (orders.print_items)."""
# A film's parts in their own order, p2 before p10: by name, a 91 m film
# would print p10 second.
files = c.execute('''SELECT f.item_index, f.upload_id, u.name FROM dtf_local.order_files f
JOIN dtf_local.uploads u ON u.id=f.upload_id
WHERE f.order_id=%s AND f.kind='final' AND f.active ORDER BY f.item_index, u.name''', (order_id,)).fetchall()
JOIN dtf_local.uploads u ON u.id=f.upload_id JOIN dtf_local.orders o ON o.id=f.order_id
LEFT JOIN dtf_local.print_parts pp ON pp.order_id=f.order_id AND pp.item_index=f.item_index
AND pp.upload_id=f.upload_id
WHERE f.order_id=%s AND f.kind='final' AND f.active
AND (o.print_items IS NULL OR f.item_index = ANY(o.print_items))
ORDER BY f.item_index, pp.part NULLS LAST, length(u.name), u.name''', (order_id,)).fetchall()
round_ = c.execute('SELECT COALESCE(max(round), 0) + 1 AS r FROM dtf_local.hot_parts WHERE order_id=%s',
(order_id,)).fetchone()['r']
for seq, row in enumerate(files, 1):
@@ -64,6 +71,40 @@ def start(c, order_id):
VALUES(%s,%s,%s,%s,%s,%s)''', (order_id, round_, seq, row['item_index'], row['upload_id'], row['name']))
def resume(c, order_id):
"""A step back from Revisão to Imprimindo, undoing a move made by
mistake: the parts of the last round Flexi had not taken go back to the
folder, in their order; what it took was printed and is never written
again (start() would send the whole order to the machine once more)."""
last = c.execute('SELECT max(round) AS r FROM dtf_local.hot_parts WHERE order_id=%s', (order_id,)).fetchone()['r']
if last is None:
return
c.execute('''INSERT INTO dtf_local.hot_parts(order_id,round,seq,item_index,upload_id,name)
SELECT order_id, round + 1, row_number() OVER (ORDER BY seq), item_index, upload_id, name
FROM dtf_local.hot_parts WHERE order_id=%s AND round=%s AND state<>'consumed' ''', (order_id, last))
def printed(c, order_ids):
"""The files each order's machine has already taken, {order id: {upload
ids}}: an order in it was printed before."""
rows = c.execute('''SELECT order_id, upload_id FROM dtf_local.hot_parts
WHERE order_id=ANY(%s) AND state IN ('written','consumed')''', (list(order_ids),)).fetchall()
out = {}
for row in rows:
out.setdefault(row['order_id'], set()).add(row['upload_id'])
return out
def reprint_default(finals, taken, count):
"""The items to print again: those whose current final the machine has
not taken. `finals` is [(item, upload id)]; None when all go (never printed,
or nothing new)."""
if not taken:
return None
changed = sorted({item for item, upload in finals if upload not in taken})
return changed if changed and len(changed) < count else None
def stop(c, order_id):
"""The order left Imprimindo or was cancelled: what is not written stays
unwritten, and what Flexi has not taken is withdrawn from the folder."""
@@ -75,15 +116,15 @@ def stop(c, order_id):
def claim(c, user):
"""The parts due in the folders now, claimed for this computer to write:
for each machine, the next parts of its orders in Imprimindo, in the order
they entered it, until the machine has two in its folder."""
they entered it, until the machine has its places' worth in its folder."""
c.execute('''UPDATE dtf_local.hot_parts SET state='queued', claimed_at=NULL, claimed_by=NULL
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,
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']
@@ -95,10 +136,12 @@ def claim(c, user):
continue
cls = folder_class(row, row['item_index'])
# A part without its class waits, and the parts after it with it.
if busy.get(machine, 0) >= IN_FOLDER or not cls:
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
@@ -58,27 +59,56 @@ def one_decimal(value):
return f'{Decimal(str(value)):.1f}'.replace('.', ',')
# A pass to Revisão undone at once (a mistaken move, back to Imprimindo):
# the pass after the undo counts the film, so this one must not, or the
# machine's metres count it twice. `m` is the pass in dtf_local.movements.
NOT_UNDONE = """NOT EXISTS (SELECT 1 FROM dtf_local.movements u WHERE u.order_id=m.order_id AND u.back
AND u.from_state='rev' AND u.to_state='imp'
AND u.id=(SELECT min(n.id) FROM dtf_local.movements n WHERE n.order_id=m.order_id AND n.id>m.id))"""
# Each proof sheet's stretches of film, {item index: [[top, bottom], ...]},
# from its print file (app/printpng.py); `o` is the order.
PROOF_WINDOWS = """(SELECT jsonb_object_agg(p.item_index::text, p.detail->'proof_windows')
FROM dtf_local.print_files p WHERE p.order_id=o.id AND p.detail ? 'proof_windows') AS windows"""
def film_metres(snapshot, items=None, windows=None):
"""The film one pass to Revisão printed, in metres, as Decimal: each
item's metres, on a reprint only the `items` that went again (#105). A
proof card's item is its sheet: the finest stroke's window and the colour
samples with the clear film between them, up to 30 cm (Marcus,
2026-11-26), from `windows` ({item index: [[top, bottom], ...]} in cm);
PROOF_SHEET_CM for a sheet made before the samples."""
from .printpng import PROOF_GAP_CM
from .proof import PROOF_SHEET_CM
snapshot = snapshot or {}
proof = bool(snapshot.get('proof_of'))
total = Decimal(0)
for index, item in enumerate(snapshot.get('items') or []):
if items is not None and index not in items:
continue
if proof:
stretches = (windows or {}).get(str(index)) or []
cm = (sum((Decimal(str(b)) - Decimal(str(a)) for a, b in stretches), Decimal(0))
+ PROOF_GAP_CM * (len(stretches) - 1)) if stretches else PROOF_SHEET_CM
total += cm / 100
else:
value = item.get('metres')
if value is None:
value = item.get('billed_metres')
total += Decimal(str(value or 0))
return total
def printed_since(c, machine_id, since):
"""Film metres the machine printed after `since` (None: ever), as Decimal."""
from .proof import PROOF_SHEET_CM
rows = c.execute('''SELECT o.snapshot 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
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 item in snapshot.get('items') or []:
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):

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 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.
@@ -41,6 +41,17 @@ INK_ITEMS = tuple(item for item in SUPPLIES if item.startswith('ink_'))
# Average month, for the monthly contribution since installation.
_MONTH_SECONDS = Decimal('30.4375') * 86400
# Below a quarter of an hour in Imprimindo the pace is noise: an order moved
# through in seconds made a machine show 110671,5 m/h (16/11). No pace then.
MIN_PACE_HOURS = 0.25
def pace(metres, hours):
"""Metres per hour, one decimal; None below MIN_PACE_HOURS of printing."""
if not hours or float(hours) < MIN_PACE_HOURS:
return None
return round(float(metres) / float(hours), 1)
def month_bounds(month):
"""'2026-11' (None: the current month, local) -> (first day, first day of
@@ -79,8 +90,7 @@ def ratios(printed, hours_running=None, supplies_cents=0, parts_cents=0, rolls=N
return int((Decimal(cents) / printed).quantize(Decimal('1'), rounding=ROUND_HALF_UP))
result = {
'metres_per_hour': (round(float(printed) / float(hours_running), 1)
if hours_running else None),
'metres_per_hour': pace(printed, hours_running),
'metres_per_roll': round(float(printed / Decimal(str(rolls))), 1) if rolls else None,
'ink_per_100m': {
item: (None if quantity is None or not printed
@@ -109,27 +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('''SELECT o.id, o.snapshot, o.parent_id, o.cancelled_at, o.payment
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
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):
"""The film printed for one order (machine_log's rule), as Decimal."""
from .proof import PROOF_SHEET_CM
snapshot = snapshot or {}
proof = bool(snapshot.get('proof_of'))
total = Decimal(0)
for item in snapshot.get('items') or []:
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):
@@ -144,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']) 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))
@@ -176,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']) 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 (
@@ -265,9 +263,9 @@ def report(c, month=None):
'''SELECT DISTINCT machine_id FROM dtf_local.machine_entries
WHERE created_at>=%s AND created_at<%s''', (start, end)).fetchall()}
printed = {str(row['machine_id']) for row in c.execute(
'''SELECT DISTINCT o.machine_id FROM dtf_local.movements m
f'''SELECT DISTINCT o.machine_id FROM dtf_local.movements m
JOIN dtf_local.orders o ON o.id=m.order_id
WHERE m.from_state='imp' AND m.to_state='rev' AND NOT m.back
WHERE m.from_state='imp' AND m.to_state='rev' AND NOT m.back AND {NOT_UNDONE}
AND m.created_at>=%s AND m.created_at<%s''', (start, end)).fetchall()}
result = []
for machine in machines:

View File

@@ -1,14 +1,17 @@
"""The print machines, their load and the two printing places on each one."""
"""The print machines, their load and the printing places on each one."""
from decimal import Decimal
from . import machine_log
# Not finished: the work still ahead of a machine.
OPEN = ('rec', 'tra', 'imp', 'cor')
# Two orders at most in Imprimindo per machine (Dropstar, 2026-10-29): one
# printing, the next being ripped by FlexiPRINT meanwhile. A third would
# make the RIP choke; two mean the next sheet is ready when one ends.
PRINTING_CAP = 2
# Orders at most in Imprimindo per machine, and files in its hot folder at
# once: dtf_local.machines.places, set per machine by Admin and Gestão
# (Marcus, 2026-11-17). It was two for all (Dropstar, 2026-10-29): one
# printing, the next ripped by FlexiPRINT meanwhile; three keeps one more
# waiting in the folder. A new machine starts with DEFAULT_PLACES.
DEFAULT_PLACES = 3
MAX_PLACES = 6
def product_family(order):
@@ -36,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 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 = {}
@@ -52,8 +56,9 @@ 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'],
'alerts': machine_log.alerts(c, m['id'])}
if with_operators:
@@ -63,22 +68,23 @@ def rows(c, with_operators=False):
def full(c, machine_id, order_id):
"""The machine's name when it already has PRINTING_CAP other orders in
Imprimindo, so this one cannot join them; None when it has room. The
machine's row is locked, so two pulls at once cannot both take the last
place."""
"""(name, places) when the machine already has its places' worth of
other orders in Imprimindo, so this one cannot join them; None when it
has room. The machine's row is locked, so two pulls at once cannot both
take the last place."""
if machine_id is None:
return None
machine = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s FOR UPDATE', (machine_id,)).fetchone()
machine = c.execute('SELECT name, places FROM dtf_local.machines WHERE id=%s FOR UPDATE', (machine_id,)).fetchone()
printing = c.execute('''SELECT count(*) AS n FROM dtf_local.orders WHERE machine_id=%s AND state='imp'
AND cancelled_at IS NULL AND id<>%s''', (machine_id, order_id)).fetchone()['n']
return machine['name'] if machine and printing >= PRINTING_CAP else None
return (machine['name'], machine['places']) if machine and printing >= machine['places'] else None
def printing_slots(c):
"""Per order in Imprimindo: 'imprimindo' for the first to enter it on its
machine (ripped, running), 'ripando' for the one after it."""
return {row['id']: 'imprimindo' if row['place'] == 1 else 'ripando' for row in c.execute('''
machine (ripped, running), 'ripando' for the one after it, 'aguardando'
for those after that, waiting in the hot folder."""
return {row['id']: {1: 'imprimindo', 2: 'ripando'}.get(row['place'], 'aguardando') for row in c.execute('''
SELECT o.id, row_number() OVER (PARTITION BY o.machine_id ORDER BY m.at, o.number) AS place
FROM dtf_local.orders o, LATERAL (SELECT max(created_at) AS at FROM dtf_local.movements
WHERE order_id=o.id AND to_state='imp') m

View File

@@ -28,6 +28,7 @@ from typing import Mapping
import httpx
from .adapters import PaymentEvent
from .core.models import cnpj_ok, cpf_ok
API = 'https://api.mercadopago.com'
# How old a signed timestamp may be. Mercado Pago retries a failed delivery
@@ -41,6 +42,29 @@ PIX_MINUTES = 30
BRASILIA = timezone(timedelta(hours=-3))
def payer(customer, method=None):
"""Who pays, as Dropstar's finance reconciles it and the invoice is issued
(Marcus, 2026-11-18): a real CPF or CNPJ, never a placeholder such as
999.999.999-99, with the order's name and e-mail.
The card form opens with the order's document already in it (web/
checkout.js), so the card token and the payer agree. A valid document
the customer typed there instead (someone else's card) is the payer, as
the token says; anything else, and PIX, is the order's own."""
document = customer['cnpj']
identification = {'type': 'CPF' if len(document) == 11 else 'CNPJ', 'number': document}
typed = ''.join(ch for ch in str((method or {}).get('payer_document') or '') if ch.isdigit())
kind = (method or {}).get('payer_document_type')
if (kind == 'CPF' and cpf_ok(typed)) or (kind == 'CNPJ' and cnpj_ok(typed)):
identification = {'type': kind, 'number': typed}
who = {'email': customer['mail'], 'identification': identification}
names = (customer.get('name') or '').split()
if names:
who['first_name'] = names[0]
who['last_name'] = ' '.join(names[1:]) or names[0]
return who
class MercadoPagoPayment:
name = 'mercadopago'
@@ -76,9 +100,10 @@ class MercadoPagoPayment:
body = {'transaction_amount': float(Decimal(total_cents) / 100),
'description': f'DTF - cotação {quote_id[:8]}',
'external_reference': quote_id,
'payer': {'email': customer['mail'],
'identification': {'type': 'CPF' if len(customer['cnpj']) == 11 else 'CNPJ',
'number': customer['cnpj']}}}
'payer': payer(customer, method if method['type'] == 'card' else None),
# The order's own document, kept on the payment for finance
# even when the card's holder is someone else.
'metadata': {'documento_pedido': customer['cnpj']}}
if self.notification_url:
body['notification_url'] = self.notification_url
expires_at = None
@@ -93,9 +118,6 @@ class MercadoPagoPayment:
# it; asking it of every card was refused as a rule (10113).
if method['payment_method_id'].startswith('deb'):
body['three_d_secure_mode'] = 'optional'
if method.get('payer_document_type') and method.get('payer_document'):
body['payer']['identification'] = {'type': method['payer_document_type'],
'number': method['payer_document']}
# No issuer_id: Mercado Pago takes the issuer from the card number.
# The form's suggestion was refused for its own test cards
# (10111, "the issuer does not have the BIN configured").

View File

@@ -0,0 +1,11 @@
-- Front 1b (Marcus, 2026-11-12): Ajuste Fino Redesenho, a per-art service
-- beside the basic Ajuste Fino. Created switched OFF and without a price:
-- Gestão sets both in the Site tab. The products CHECK is the inline
-- constraint of dtf_local.products.id (products_id_check); widening a list is
-- a new migration that drops and adds that one constraint (never schema.sql).
ALTER TABLE dtf_local.products DROP CONSTRAINT IF EXISTS products_id_check;
ALTER TABLE dtf_local.products ADD CONSTRAINT products_id_check
CHECK (id IN ('file','avulsa','uvfile','uv','premium','tratamento','redesenho'));
INSERT INTO dtf_local.products(id, enabled) VALUES ('redesenho', false)
ON CONFLICT (id) DO NOTHING;

View File

@@ -0,0 +1,3 @@
-- A print file's render limit grows with its film (RENDER_SECONDS per 15 m
-- part, app/printjobs.py): each claim records when it counts as abandoned.
ALTER TABLE dtf_local.print_files ADD COLUMN IF NOT EXISTS deadline_at timestamptz;

View File

@@ -0,0 +1,5 @@
-- Dropstar's stamp codes carry dots (NX.226, Marcus 2026-11-16); not as the
-- first character, as in app/api/stamps.py CODE.
ALTER TABLE dtf_local.stamps DROP CONSTRAINT IF EXISTS stamps_code_check;
ALTER TABLE dtf_local.stamps ADD CONSTRAINT stamps_code_check
CHECK (code ~ '^[A-Za-z0-9_-][A-Za-z0-9._-]{0,39}$');

View File

@@ -0,0 +1,5 @@
-- How many orders each machine takes in Imprimindo, and files in its hot
-- folder at once: three, set per machine by Admin and Gestão (Marcus,
-- 2026-11-17; it was two for every machine, app/machines.py).
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS places smallint NOT NULL DEFAULT 3
CHECK (places BETWEEN 1 AND 6);

View File

@@ -0,0 +1,5 @@
-- The Tiny seller (vendedor) each Kanban user is, so a Venda the user
-- assembles reaches Tiny with them as its seller (Marcus, 2026-11-17).
-- Tiny takes the seller by its id; the name is kept to show it.
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS tiny_seller_id bigint;
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS tiny_seller_name text;

View File

@@ -0,0 +1,13 @@
-- More than one profile per user (Marcus, 2026-11-26: operador/revisor,
-- gestor/operador/revisor): what a user may do is the sum of their profiles.
-- `role` stays the main one, shown first and kept for superadmin; `roles`
-- holds every profile, the main one included.
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS roles text[] NOT NULL DEFAULT '{}';
UPDATE dtf_local.operators SET roles=ARRAY[role] WHERE cardinality(roles)=0;
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='operators_roles'
AND conrelid='dtf_local.operators'::regclass) THEN
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_roles
CHECK (roles <@ ARRAY['superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao']::text[]);
END IF;
END $$;

View File

@@ -0,0 +1,5 @@
-- Reprinting some items of an order (Marcus, 2026-11-26, #105): the items
-- that go to the machine this time (NULL: all), and on each pass from
-- Imprimindo to Revisão the items that were printed, for the machine's metres.
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS print_items integer[];
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS items integer[];

View File

@@ -0,0 +1,24 @@
-- "Gerar de novo" names the new files with a version (Marcus, 2026-11-27,
-- #130): DTF-130-v2-item-1-p2.png, so neither the Kanban, the FlexiPRINT
-- queue nor the Hoson list mixes them up with the first ones.
ALTER TABLE dtf_local.print_files ADD COLUMN IF NOT EXISTS generation integer NOT NULL DEFAULT 1;
-- A Prova OK approved only the first part of a film in parts (the print
-- file's first upload), so the other parts never reached the folders (#114,
-- #128, #130). For the orders still before Imprimindo, the missing parts join
-- the parts the Prumo already approved.
-- The order's version goes up, so the board and the folders see the new finals.
WITH added AS (
INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
SELECT gen_random_uuid(), p.order_id, p.upload_id, p.item_index, 'final', 'Parte completada (prova)', 'Prumo'
FROM dtf_local.print_parts p JOIN dtf_local.orders o ON o.id=p.order_id
WHERE o.state IN ('rec','tra') AND o.cancelled_at IS NULL AND o.parent_id IS NULL
AND EXISTS (SELECT 1 FROM dtf_local.order_files f JOIN dtf_local.print_parts q
ON q.order_id=f.order_id AND q.item_index=f.item_index AND q.upload_id=f.upload_id
WHERE f.order_id=p.order_id AND f.item_index=p.item_index AND f.kind='final' AND f.active
AND f.created_by='Prumo')
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=p.order_id
AND f.item_index=p.item_index AND f.upload_id=p.upload_id)
RETURNING order_id
)
UPDATE dtf_local.orders SET version=version+1, updated_at=now() WHERE id IN (SELECT order_id FROM added);

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

@@ -45,10 +45,10 @@ def seed_from_environment(cursor):
'SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone()
if existing:
# The configured account is the system's own: it stays superadmin.
cursor.execute("UPDATE dtf_local.operators SET role='superadmin' WHERE email=%s", (email,))
cursor.execute("UPDATE dtf_local.operators SET role='superadmin',roles=ARRAY['superadmin'] WHERE email=%s", (email,))
return None
cursor.execute(
"INSERT INTO dtf_local.operators(id,email,name,password_hash,role) VALUES(%s,%s,%s,%s,'superadmin')",
"INSERT INTO dtf_local.operators(id,email,name,password_hash,role,roles) VALUES(%s,%s,%s,%s,'superadmin',ARRAY['superadmin'])",
(uuid4(), email, 'Operador', password_hash(password)))
return email
@@ -69,8 +69,8 @@ def add(email, name='', role='admin'):
with connect() as c:
if c.execute('SELECT id FROM dtf_local.operators WHERE email=%s', (email,)).fetchone():
raise SystemExit(f'{email} already exists. Use "password" or "enable".')
c.execute('INSERT INTO dtf_local.operators(id,email,name,password_hash,role) VALUES(%s,%s,%s,%s,%s)',
(uuid4(), email, name, password_hash(_ask_password(email)), role))
c.execute('INSERT INTO dtf_local.operators(id,email,name,password_hash,role,roles) VALUES(%s,%s,%s,%s,%s,%s)',
(uuid4(), email, name, password_hash(_ask_password(email)), role, [role]))
print(f'Added {email} as {role}.')
@@ -79,7 +79,8 @@ def set_role(email, role):
if role not in ROLES:
raise SystemExit('Role must be one of: ' + ', '.join(ROLES))
with connect() as c:
if not c.execute('UPDATE dtf_local.operators SET role=%s WHERE email=%s RETURNING id', (role, email)).fetchone():
if not c.execute('UPDATE dtf_local.operators SET role=%s,roles=%s WHERE email=%s RETURNING id',
(role, [role], email)).fetchone():
raise SystemExit(f'{email} does not exist.')
print(f'{email} is now {role}.')

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
@@ -77,6 +88,34 @@ def in_tiny(order):
return not is_test(order) and not order.get('parent_id')
# What a stage tells Tiny: entering the queue (Arte conferida) is its
# "Preparando envio", Finalizado its "Pronto para envio" (Dropstar's flow,
# 2026-10-23); a correction has no situação and is only recorded.
STAGE_EVENTS = {'tra': 'production_started', 'cor': 'correction_needed', 'fin': 'ready'}
def stage_event(c, order, state, reason, version):
"""Queue Tiny's event for an order that entered `state` (not by a step
back), whoever moved it: a card dragged, or the Prova OK that puts the
order in the queue (app/proof.py). `order` is its row before the move,
`version` its version after."""
if state not in STAGE_EVENTS or not in_tiny(order):
return
# "Production started" and "ready" reach the customer once per order,
# even if a mistaken move is undone and made again. Each correction is a
# new request, so it keeps one message per movement.
once = state in ('tra', 'fin')
event = {'order_id': str(order['id']), 'number': order['number'], 'event': STAGE_EVENTS[state],
'reason': reason, 'customer_path': f"/portal.html?order={order['id']}"}
# Tiny needs the order (customer, pickup or delivery) and, once the sale
# reached it, its id, to set the situação without a search.
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
(f"{order['id']}:paid:tiny",)).fetchone()
tiny = {**event, 'order': order['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')}
key = f"{order['id']}:{STAGE_EVENTS[state]}:tiny" if once else f"{order['id']}:{version}:tiny"
enqueue(c, key, 'tiny', tiny)
# How long a file is kept while nothing has been paid for it. A cart's files
# are uploaded before payment, so the price and the security check are done on
# the file itself; a cart that is never paid must not keep them for 30 days.
@@ -212,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}'
@@ -227,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):
@@ -245,7 +293,7 @@ def reconcile(connect, provider, quote_id=None, limit=20):
WHERE o.id IS NULL AND i.provider=%s AND i.status IN ('pending','approved')
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

@@ -2,11 +2,12 @@
A paid order queues one job per item. The worker claims a job, commits the
claim, and renders outside any transaction, so a long render never holds a row
lock or a database connection. A claim older than CLAIM_TIMEOUT is assumed to
belong to a worker that died and is taken again.
lock or a database connection. A claim past its deadline (the render limit
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
@@ -29,27 +30,48 @@ from decimal import Decimal
from zoneinfo import ZoneInfo
from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
import psycopg
from psycopg.types.json import Jsonb
from PIL import Image
from .cart_pricing import needs_designer
from .core.auth import audit
from .core.db import connect
from .printfile import Unsupported
from .printpng import render
from .printpng import part_cuts, render
from . import proof
from .proof import PROOF_SHEET_CM
from .tiny import purchase_order
LOCAL = ZoneInfo('America/Sao_Paulo')
# A 15 m part takes minutes to write; a long film, several parts.
RENDER_SECONDS = int(os.environ.get('PRINT_RENDER_TIMEOUT_SECONDS', '900'))
CLAIM_TIMEOUT = timedelta(minutes=18)
# A 15 m part takes about 7 min to write on a fast core; a long film, several
# parts. The limit is per part: order #20's 23.6 m film (2026-11-12) ran past a
# single 15 min limit for the whole film.
RENDER_SECONDS = int(os.environ.get('PRINT_RENDER_TIMEOUT_SECONDS', '1200'))
CLAIM_MARGIN = timedelta(minutes=3)
CLAIM_TIMEOUT = timedelta(seconds=RENDER_SECONDS) + CLAIM_MARGIN
# A claim is stale once past its deadline.
STALE = 'COALESCE({p}.deadline_at, {p}.claimed_at + %s) < now()'
MAX_ATTEMPTS = 3
LARGE_SOURCE_BYTES = int(os.environ.get('PRINT_DECODE_MAX_BYTES', str(300 * 1024 * 1024)))
# Read band by band, whatever their size.
STREAMED = ('.png', '.pdf')
def render_seconds(item):
"""The render limit of one item: RENDER_SECONDS for each part of its
film, and one more for a film in parts: a cut moved back to a clear band
(#136) can leave one part more than the layout alone counts."""
production = item.get('production') or {}
try:
parts = len(part_cuts(production)) - 1 if production.get('placements') else 1
except (KeyError, TypeError, ValueError, ArithmeticError):
parts = 1
parts = max(1, parts)
return RENDER_SECONDS * (parts + 1 if parts > 1 else 1)
def generated_identity(order_id):
return uuid5(NAMESPACE_URL, f'dtf-print-file:{order_id}')
@@ -92,17 +114,29 @@ def queue(c, order_id, items, only_missing=False):
ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0,
claimed_at=NULL, claim_token=NULL, finished_at=NULL, upload_id=NULL, detail='{}'
WHERE dtf_local.print_files.status IN ('failed','manual') OR
(dtf_local.print_files.status='rendering' AND dtf_local.print_files.claimed_at<now()-%s)''',
(dtf_local.print_files.status='rendering' AND '''
+ STALE.format(p='dtf_local.print_files') + ')',
(uuid4(), order_id, index, CLAIM_TIMEOUT))
else:
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
ON CONFLICT(order_id,item_index) DO NOTHING''', (uuid4(), order_id, index))
def requeue(c, order_id, items):
"""Generate every item again, a ready one too: after the part size
changed (PART_CM; order #36, 2026-11-17). One rendering now is left alone."""
for index in range(items):
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0,
claimed_at=NULL, claim_token=NULL, finished_at=NULL, upload_id=NULL, detail='{}',
generation=dtf_local.print_files.generation+1
WHERE dtf_local.print_files.status<>'rendering' ''', (uuid4(), order_id, index))
def claim(c):
return c.execute('''SELECT p.*, o.snapshot, o.number, o.parent_id, o.created_at AS ordered_at FROM dtf_local.print_files p
JOIN dtf_local.orders o ON o.id=p.order_id
WHERE p.status='pending' OR (p.status='rendering' AND p.claimed_at < now()-%s)
WHERE p.status='pending' OR (p.status='rendering' AND ''' + STALE.format(p='p') + ''')
ORDER BY CASE WHEN o.parent_id IS NOT NULL THEN 0 ELSE 1 END, p.created_at
FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
@@ -119,13 +153,13 @@ def _render_child(result_queue, job, item, uploads):
result_queue.put(('error', type(exc).__name__))
def render_with_timeout(job, item, uploads):
def render_with_timeout(job, item, uploads, seconds=RENDER_SECONDS):
ctx = multiprocessing.get_context('spawn')
result_queue = ctx.Queue()
process = ctx.Process(target=_render_child, args=(result_queue, job, item, uploads))
process.start()
try:
process.join(RENDER_SECONDS)
process.join(seconds)
if process.is_alive():
process.terminate()
process.join(5)
@@ -148,10 +182,12 @@ def render_one(storage):
if not job:
return False
token = uuid4()
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
attempts=attempts+1,claim_token=%s WHERE id=%s''', (token, job['id']))
job['claim_token'] = token
item = job['snapshot']['items'][job['item_index']]
seconds = render_seconds(item)
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
deadline_at=now()+%s, attempts=attempts+1,claim_token=%s WHERE id=%s''',
(timedelta(seconds=seconds) + CLAIM_MARGIN, token, job['id']))
job['claim_token'] = token
source_ids = [UUID(u) for u in item['uploads']]
# A format such as CDR needs a human to prepare the full-size final on
# the parent. The child still generates its own 15 cm proof from that PNG,
@@ -177,8 +213,14 @@ def render_one(storage):
source_ids = [source['id']]
item = {**item, 'uploads': [str(source['id'])]}
job['proof_fallback'] = True
elif job['snapshot'].get('treatment'):
elif needs_designer(job['snapshot']):
job['wait_for_treatment'] = True
# The small pictures the Site sent of each file: where a proof finds
# the colours to sample (app/printpng.py film_scan).
if job['snapshot'].get('proof_of') and not job.get('proof_fallback'):
job['pictures'] = {str(r['upload_id']): bytes(r['data']) for r in c.execute(
'SELECT upload_id,data FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s)',
(source_ids,)).fetchall()}
uploads = c.execute('''SELECT id,name,size,object_key,scan_state,purged_at,expires_at,
(expires_at<=now()) AS expired FROM dtf_local.uploads WHERE id=ANY(%s)''',
(source_ids,)).fetchall()
@@ -194,17 +236,23 @@ def render_one(storage):
'monte a folha a partir do original'})
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
return True
outcome, result = render_with_timeout(job, item, by_id)
outcome, result = render_with_timeout(job, item, by_id, seconds)
if outcome == 'manual':
finish(job, 'manual', {'reason': result})
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
return True
if outcome == 'timeout':
finish(job, 'failed', {'reason': f'Tempo limite de {RENDER_SECONDS // 60} min excedido. Gere de novo.'})
finish(job, 'failed', {'reason': f'Tempo limite de {seconds // 60} min excedido. Gere de novo.'})
audit('print_file_timeout', order=str(job['order_id']), item=job['item_index'])
# The card says so too, but Sentry (and the Vigia) hear of it first.
logging.error('Print file generation timed out after %s min: order #%s item %s',
seconds // 60, job['number'], job['item_index'] + 1)
return True
if outcome == 'error':
final = job['attempts'] + 1 >= MAX_ATTEMPTS
if final:
logging.error('Print file generation failed: order #%s item %s: %s',
job['number'], job['item_index'] + 1, result)
finish(job, 'failed' if final else 'pending', {'error': result,
'reason': 'A geração falhou. Gere de novo.' if final else ''})
return True
@@ -218,9 +266,17 @@ def render_one(storage):
stored.append((uid, name, os.path.getsize(path), key))
store_tiles(storage, os.path.join(scratch, 'tiles', name), uid)
except Exception as exc:
# Storage failing is an attempt like any other, not a claim held for an hour.
logging.exception('Storing the print file failed')
finish(job, 'failed' if job['attempts'] + 1 >= MAX_ATTEMPTS else 'pending', {'error': type(exc).__name__})
# Storage failing is an attempt like any other, not a claim held for an
# hour. The storage client already waited out a short outage; Sentry
# hears of one that outlasts every attempt, once, not of each retry
# (Sentry DTF-API-A).
final = job['attempts'] + 1 >= MAX_ATTEMPTS
if final:
logging.exception('Storing the print file failed: order #%s item %s', job['number'], job['item_index'] + 1)
else:
logging.warning('Storing the print file failed, retrying: order #%s item %s: %s',
job['number'], job['item_index'] + 1, exc)
finish(job, 'failed' if final else 'pending', {'error': type(exc).__name__})
return True
finally:
shutil.rmtree(scratch, ignore_errors=True)
@@ -252,6 +308,11 @@ def render_one(storage):
(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,%s,'final','Prova gerada automaticamente pelo Prumo','Prumo')''',
(uuid4(), job['order_id'], stored[0][0], job['item_index']))
elif not job['parent_id']:
# A Prova OK given while this file was still being generated.
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (job['order_id'],)).fetchone()
if order['proof_ok_at']:
proof.approve_parent(c, order, 'Prumo')
audit('print_file_ready', order=str(job['order_id']), item=job['item_index'], parts=len(stored))
return True
@@ -266,10 +327,13 @@ def store_tiles(storage, folder, upload_id):
storage.store(f'originals/tiles/{upload_id}/{level}/{strip}', os.path.join(folder, level, strip), 'image/png')
def file_prefix(number, item_index):
def file_prefix(number, item_index, generation=1):
"""How an order's files are named: DTF-23-item-1, the code the Kanban
copies, the footer prints and Tiny keeps (Dropstar, 2026-10-23)."""
return f'DTF-{number}-item-{item_index + 1}'
copies, the footer prints and Tiny keeps (Dropstar, 2026-10-23); after
"Gerar de novo", DTF-23-v2-item-1, so no one takes the new files for the
old ones (Marcus, 2026-11-27, #130)."""
version = f'-v{generation}' if generation and generation > 1 else ''
return f'DTF-{number}{version}-item-{item_index + 1}'
def footer(job, item):
@@ -293,6 +357,15 @@ def footer(job, item):
return ' · '.join(fields)
def pictures_by_source(item, pictures):
"""The small pictures by source index, as the proof's scan reads them."""
if not pictures:
return None
sources = item['production']['sources']
found = {i: pictures[str(s['upload_id'])] for i, s in enumerate(sources) if str(s['upload_id']) in pictures}
return found or None
def produce(storage, job, item, uploads):
"""Fetch the item's artwork and render it. Returns (folder, [(png path,
name)], evidence); the caller removes the folder."""
@@ -335,10 +408,11 @@ def produce(storage, job, item, uploads):
proof_of = job['snapshot'].get('proof_of')
# The child owns its final file; the class names its proof.
prefix = (f'DTF-{job["number"]}-prova-{item.get("stroke_class") or "C3"}' if proof_of
else file_prefix(job['number'], job['item_index']))
else file_prefix(job['number'], job['item_index'], job.get('generation')))
parts, detail = render(item, files, output, prefix, footer=footer(job, item), tiles=True,
limit_cm=PROOF_SHEET_CM if proof_of else None,
proof_fraction=item.get('proof_y_fraction') if proof_of else None)
proof_fraction=item.get('proof_y_fraction') if proof_of else None,
pictures=pictures_by_source(item, job.get('pictures')))
except BaseException:
shutil.rmtree(output, ignore_errors=True)
raise
@@ -354,10 +428,22 @@ def finish(job, status, detail):
def render_loop(storage):
down_since, delay = None, 2
while True:
try:
if render_one(storage):
continue
except psycopg.OperationalError as exc:
# A restart takes the database away for seconds: say so once.
if down_since is None:
down_since = time.monotonic()
logging.warning('Print render worker: database unavailable, retrying: %s', exc)
time.sleep(delay)
delay = min(delay * 2, 15)
continue
except Exception:
logging.exception('Print render worker tick failed')
if down_since is not None:
logging.info('Print render worker: database back after %s s', int(time.monotonic() - down_since))
down_since, delay = None, 2
time.sleep(2)

View File

@@ -19,10 +19,12 @@ 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
is. Loose artwork is cut where no piece crosses; a finished sheet is cut
between copies when it can be, and through the artwork when not.
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).
"""
import io
import math
@@ -40,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
@@ -68,8 +73,9 @@ class PngWriter:
def __init__(self, fp, width, height):
self.fp, self.width, self.height = fp, width, height
self.rows = 0
self.previous = None # the last row written, as an image
self.z = zlib.compressobj(6)
# Level 1 and no row filter: the same size as Pillow's filters at
# level 6, in under half the time. #81's 91,5 m took 6 hours (2026-11-25).
self.z = zlib.compressobj(1)
self.pending = []
fp.write(b'\x89PNG\r\n\x1a\n')
_chunk(fp, b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 6, 0, 0, 0))
@@ -83,18 +89,9 @@ class PngWriter:
rows = image.height
if self.rows + rows > self.height:
raise ValueError('more rows than the file has')
# The previous row on top, so each row's filter refers to the real row
# above it; that first filtered row is dropped.
lead = 1 if self.previous is not None else 0
framed = Image.new('RGBA', (self.width, rows + lead))
if lead:
framed.paste(self.previous, (0, 0))
framed.paste(image, (0, lead))
encoded = io.BytesIO()
framed.save(encoded, 'PNG', compress_level=0)
filtered = zlib.decompress(_idat(encoded.getvalue()))
self._write(filtered[lead * (1 + 4 * self.width):])
self.previous = image.crop((0, rows - 1, self.width, rows))
raw, stride = image.tobytes(), 4 * self.width
# Each row behind its filter byte, 0 (none).
self._write(b''.join(b'\x00' + raw[i * stride:(i + 1) * stride] for i in range(rows)))
self.rows += rows
def _write(self, data):
@@ -117,17 +114,6 @@ class PngWriter:
_chunk(self.fp, b'IEND', b'')
def _idat(png):
"""The concatenated IDAT data of an in-memory PNG."""
data, at = [], 8
while at < len(png):
size, kind = struct.unpack('>I4s', png[at:at + 8])
if kind == b'IDAT':
data.append(png[at + 8:at + 8 + size])
at += 12 + size
return b''.join(data)
# ---- Reading ----------------------------------------------------------------
class PngRows:
@@ -226,6 +212,8 @@ class Source:
def __init__(self, path, name):
self.path, self.name = path, name
# File rows left out at the top and the bottom (trim()).
self.cut = (0, 0)
with open(path, 'rb') as handle:
head = handle.read(1024)
self.pdf = b'%PDF-' in head
@@ -268,6 +256,58 @@ class Source:
pass
image.close()
def trim(self, spec):
"""Leave out the empty strips the Site cut from a ready sheet's top and
bottom (Marcus, 2026-11-18). From then on `size` is what is printed."""
top_cm = Decimal(str(spec.get('trim_top_cm') or 0))
bottom_cm = Decimal(str(spec.get('trim_bottom_cm') or 0))
if not (top_cm or bottom_cm):
return
if self.pdf:
raise Unsupported(f'"{self.name}": o corte das faixas vazias só vale para imagens')
full_cm = Decimal(str(spec['length_cm'])) + top_cm + bottom_cm
width, height = self.size
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:
@@ -325,7 +365,15 @@ class Piece:
key = (id(self.source), self.rotation, self.mirrored, self.w, self.h)
if key not in cache:
upright = (self.h, self.w) if self.rotation in (90, 270) else (self.w, self.h)
image = self.source.decoded(*upright)
top, bottom = self.source.cut
if top or bottom:
# A trimmed sheet (never turned): the file at the piece's scale,
# then the rows between the strips.
scale = self.h / self.source.size[1]
image = self.source.decoded(self.w, max(1, round((self.source.size[1] + top + bottom) * scale)))
image = image.crop((0, round(top * scale), self.w, round(top * scale) + self.h))
else:
image = self.source.decoded(*upright)
if self.mirrored:
image = ImageOps.mirror(image)
if self.rotation:
@@ -349,10 +397,13 @@ class Piece:
self.reader = PngRows(self.source.path)
self.buffer, self.buffer_top = None, 0
sw, sh = self.reader.width, self.reader.height
per_row = sh / self.h
# A trimmed sheet starts `skip` file rows down and stops `cut` rows short.
skip, cut = self.source.cut
per_row = (sh - skip - cut) / self.h
# The source rows behind [a, b), with room for the filter on each side.
margin = 0 if per_row == 1 and sw == self.w else math.ceil(3 * max(per_row, 1)) + 2
want_top, want_bottom = max(0, math.floor(a * per_row) - margin), min(sh, math.ceil(b * per_row) + margin)
want_top = max(0, math.floor(a * per_row) + skip - margin)
want_bottom = min(sh, math.ceil(b * per_row) + skip + margin)
while self.buffer_top + (self.buffer.height if self.buffer else 0) < want_bottom:
band = rgba(self.reader.band(BAND_ROWS))
if self.buffer is None:
@@ -366,8 +417,8 @@ class Piece:
self.buffer = self.buffer.crop((0, want_top - self.buffer_top, sw, self.buffer.height))
self.buffer_top = want_top
if per_row == 1 and sw == self.w:
return self.buffer.crop((0, a - self.buffer_top, sw, b - self.buffer_top))
box = (0, a * per_row - self.buffer_top, sw, b * per_row - self.buffer_top)
return self.buffer.crop((0, a + skip - self.buffer_top, sw, b + skip - self.buffer_top))
box = (0, a * per_row + skip - self.buffer_top, sw, b * per_row + skip - self.buffer_top)
return self.buffer.resize((self.w, b - a), Image.LANCZOS, box=box)
def close(self):
@@ -378,8 +429,16 @@ class Piece:
# ---- Parts and footer -------------------------------------------------------
def part_cuts(production, part_cm=None):
"""Where the film is cut into parts, in cm from its top: [0, ..., height]."""
# A cut needs this much clear film: it then falls in the middle of it.
CLEAR_CUT_CM = Decimal('0.3')
def part_cuts(production, part_cm=None, clear=None):
"""Where the film is cut into parts, in cm from its top: [0, ..., height].
A cut falls in a gap between pieces; where the layout has none, as inside
a ready sheet (one piece to it), `clear(from_cm, to_cm)` finds a clear band
in the film's own pixels, so no artwork is cut in two (Marcus, 2026-11-27,
#136). Only without one either is the cut at the part's length."""
limit = Decimal(str(part_cm or PART_CM))
height = Decimal(str(production['height_cm']))
spans = [(Decimal(str(p['y_cm'])), Decimal(str(p['y_cm'])) + Decimal(str(p['length_cm'])))
@@ -390,11 +449,46 @@ def part_cuts(production, part_cm=None):
free = [end for _, end in spans
if start + limit - CUT_SEARCH_CM <= end <= start + limit
and not any(top < end < bottom for top, bottom in spans)]
cuts.append(max(free) if free else start + limit)
# The search never goes back past half a part: no part comes out short.
found = clear(max(start + limit / 2, start + limit - CUT_SEARCH_CM), start + limit) if clear and not free else None
cuts.append(max(free) if free else found if found and found > start else start + limit)
cuts.append(height)
return cuts
def clear_band(pieces, width, from_cm, to_cm):
"""Where to cut the film between the two, in cm, so the artwork suffers
least (Marcus, 2026-11-27, #136): the middle of the clear band of at least
CLEAR_CUT_CM nearest `to_cm`; else of the widest clear band there is (a
sheet packed edge to edge may have only 2 mm between rows); else the row
with the least ink. None when the stretch is empty of rows."""
top = px(from_cm)
ink_rows, amounts = [], []
for _, band in film_bands(pieces, top, px(to_cm), width):
ink = band.getchannel('A').point(lambda a: 255 if a > 8 else 0)
ink_rows.extend(ink.getprojection()[1])
amounts.extend(ink.resize((1, ink.height), Image.BOX).tobytes())
if not ink_rows:
return None
runs, end = [], None # (length, last row, first row), clear rows only
for row in range(len(ink_rows) - 1, -2, -1):
if row >= 0 and not ink_rows[row]:
end = row if end is None else end
continue
if end is not None:
runs.append((end - row, end, row + 1))
end = None
to_cm_of = lambda row: Decimal(top + row) / Decimal(str(PX_PER_CM))
need = px(CLEAR_CUT_CM)
wide = [run for run in runs if run[0] >= need]
if wide or runs:
# runs go from the bottom up: the first wide one is the nearest the limit.
length, last, first = wide[0] if wide else max(runs, key=lambda run: (run[0], run[1]))
return to_cm_of((first + last) // 2)
least = min(amounts)
return to_cm_of(max(row for row, amount in enumerate(amounts) if amount == least))
def proof_cut(height_cm, limit_cm, fraction=None):
"""A proof's window, in cm from the film's top: `limit_cm` centred on the
thinnest stroke (fraction 0 at the top, 1 at the bottom), clamped inside
@@ -438,16 +532,136 @@ def footer_band(text, width):
return band
# ---- The proof's samples ----------------------------------------------------
#
# Marcus, 2026-11-26: a proof of the finest stroke alone missed the colours
# (#100's caught only white art). The proof keeps its window on the finest
# stroke and adds short samples of the colours that window lacks, up to
# PROOF_MAX_CM in all, each apart by PROOF_GAP_CM of clear film.
PROOF_MAX_CM = Decimal('30')
PROOF_SAMPLE_CM = Decimal('5')
PROOF_GAP_CM = Decimal('1')
# Colour groups: 12 hues, then grey, white and black; 15 is no ink.
GREY, WHITE, BLACK, CLEAR = 12, 13, 14, 15
# A colour counts when it is this share of the film's ink, and is in a stretch
# when it is this share of the stretch's ink.
COLOUR_SHARE, PRESENT_SHARE = 0.02, 0.03
def colour_counts(band):
"""The band's ink by colour group, read on a copy an eighth the size."""
small = band.reduce(8) if min(band.size) >= 8 else band
alpha = small.getchannel('A')
hue, sat, val = small.convert('RGB').convert('HSV').split()
groups = hue.point(lambda h: h * 12 // 256)
achromatic = sat.point(lambda s: 255 if s < 46 else 0)
groups.paste(GREY, mask=achromatic)
groups.paste(WHITE, mask=Image.composite(val.point(lambda v: 255 if v > 217 else 0),
Image.new('L', small.size), achromatic))
groups.paste(BLACK, mask=val.point(lambda v: 255 if v < 64 else 0))
groups.paste(CLEAR, mask=alpha.point(lambda a: 255 if a < 128 else 0))
return groups.histogram()[:CLEAR]
def present(counts):
ink = sum(counts)
return {k for k, n in enumerate(counts) if ink and n >= PRESENT_SHARE * ink}
SCAN_PX_CM = 4
def film_scan(production, pictures):
"""The film's colours a centimetre at a time, [(top_cm, bottom_cm,
counts)], drawn from each file's small picture (the one the Site sends
for the Kanban, at most 480 x 720 px), so a 100 m film is read in a
moment. `pictures` maps a source index to its image bytes; a file
without one leaves its place empty."""
k = SCAN_PX_CM
film = Image.new('RGBA', (max(1, round(float(production['film_width_cm']) * k)),
max(1, round(float(production['height_cm']) * k))))
images = {}
for index, data in pictures.items():
try:
image = rgba(ImageOps.exif_transpose(Image.open(io.BytesIO(data))))
except Exception:
continue
spec = production['sources'][index]
top, bottom = (float(spec.get('trim_top_cm') or 0), float(spec.get('trim_bottom_cm') or 0))
if top or bottom:
# The picture is of the whole file: the Site cut the empty strips.
full = float(spec['length_cm']) + top + bottom
image = image.crop((0, round(image.height * top / full), image.width,
round(image.height * (full - bottom) / full)))
images[index] = image
for placement in production['placements']:
image = images.get(placement['source_index'])
if image is None:
continue
w = max(1, round(float(placement['width_cm']) * k))
h = max(1, round(float(placement['length_cm']) * k))
if placement['mirrored']:
image = ImageOps.mirror(image)
if placement['rotation_degrees'] % 360:
image = image.rotate(-placement['rotation_degrees'], expand=True)
film.alpha_composite(image.resize((w, h), Image.BOX),
(round(float(placement['x_cm']) * k), round(float(placement['y_cm']) * k)))
return [(Decimal(y) / k, Decimal(min(film.height, y + k)) / k, colour_counts(film.crop((0, y, film.width, y + k))))
for y in range(0, film.height, k)]
def proof_windows(height_cm, limit_cm, fraction, scan):
"""The proof's stretches of film, [(top, bottom)] in cm, from the top: the
finest stroke's window, then a PROOF_SAMPLE_CM sample for each colour
still missing, the most missing first. `scan` is [(top_cm, bottom_cm,
counts)] over the film."""
first = proof_cut(height_cm, limit_cm, fraction)
windows = [tuple(first)]
height = Decimal(str(height_cm))
total = sum((b - a for a, b in windows), Decimal(0))
ink = [sum(c[k] for _, _, c in scan) for k in range(CLEAR)]
wanted = {k for k, n in enumerate(ink) if sum(ink) and n >= COLOUR_SHARE * sum(ink)}
def inside(a, b):
# Only the centimetres wholly in the stretch: one on its edge may hold
# a colour the proof does not show.
return [c for top, bottom, c in scan if top >= a and bottom <= b]
covered = set().union(*(present(c) for a, b in windows for c in inside(a, b)))
while total + PROOF_GAP_CM + PROOF_SAMPLE_CM <= PROOF_MAX_CM and wanted - covered:
best = None
for top, bottom, counts in scan:
gain = (wanted - covered) & present(counts)
if not gain:
continue
centre = (top + bottom) / 2
a = min(height - PROOF_SAMPLE_CM, max(Decimal(0), centre - PROOF_SAMPLE_CM / 2)).quantize(Decimal('0.1'))
b = a + PROOF_SAMPLE_CM
if any(a < wb + PROOF_GAP_CM and b > wa - PROOF_GAP_CM for wa, wb in windows):
continue
score = (len(gain), sum(counts[k] for k in gain))
if best is None or score > best[0]:
best = (score, a, b)
if best is None:
break
_, a, b = best
windows.append((a, b))
total += PROOF_GAP_CM + (b - a)
covered |= set().union(*(present(c) for c in inside(a, b)))
return sorted(windows)
# ---- The file ---------------------------------------------------------------
def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False, limit_cm=None,
proof_fraction=None):
proof_fraction=None, pictures=None):
"""Write the PNG part(s) of one approved order item into `out_dir`.
`files` maps each source index to (local path, original name). With
`tiles`, each part's pieces for the Kanban's viewer go in
out_dir/tiles/<part name>/<level>/<index>.png (app/printtiles.py).
A proof (`limit_cm`) is a free 15 cm window around `proof_fraction`.
A proof (`limit_cm`) is a free 15 cm window around `proof_fraction`,
and samples of the colours it lacks, found in `pictures` (film_scan).
Returns the parts, [(path, name)], and the evidence the Kanban shows.
"""
production = item['production']
@@ -455,23 +669,45 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False,
raise Unsupported('o item usa uma montagem antiga')
sources = [Source(*files[index]) for index in range(len(production['sources']))]
try:
for spec, source in zip(production['sources'], sources):
source.trim(spec)
vector = {index for index, source in enumerate(sources) if source.pdf}
lowest = check_layout(item, [source.size for source in sources], vector, proof=bool(limit_cm))
width = px(production['film_width_cm'])
pieces = sorted((Piece(placement, sources[placement['source_index']])
for placement in production['placements']), key=lambda piece: piece.y)
# A proof sheet is a 15 cm window around the finest stroke; a normal
# file is cut into parts (app/proof.py, item 0.1).
cuts = (proof_cut(production['height_cm'], limit_cm, proof_fraction) if limit_cm
else part_cuts(production, part_cm))
def laid_out():
return sorted((Piece(placement, sources[placement['source_index']])
for placement in production['placements']), key=lambda piece: piece.y)
windows = None
if limit_cm:
# A proof: the finest stroke's window and samples of the other
# colours, stacked in one sheet; a normal file is cut into parts.
windows = [tuple(proof_cut(production['height_cm'], limit_cm, proof_fraction))]
if pictures and Decimal(str(production['height_cm'])) > Decimal(str(limit_cm)):
windows = proof_windows(production['height_cm'], limit_cm, proof_fraction,
film_scan(production, pictures))
cuts = [windows[0][0], windows[-1][1]]
else:
def clear(from_cm, to_cm):
# Read on pieces of its own: the film is read forward only.
scanned = laid_out()
try:
return clear_band(scanned, width, from_cm, to_cm)
finally:
for piece in scanned:
piece.close()
cuts = part_cuts(production, part_cm, clear)
pieces = laid_out()
count = len(cuts) - 1
parts, manifests = [], []
for number in range(count):
name = f'{prefix}.png' if count == 1 else f'{prefix}-p{number + 1}.png'
path = os.path.join(out_dir, name)
line = footer and (footer + (f' · Parte {number + 1}/{count}' if count > 1 else ''))
ranges = ([(px(a), px(b)) for a, b in windows] if windows
else [(px(cuts[number]), px(cuts[number + 1]))])
with open(path, 'wb') as out:
manifests.append(write_part(out, pieces, px(cuts[number]), px(cuts[number + 1]), width, line,
manifests.append(write_part(out, pieces, ranges, width, line,
tiles=os.path.join(out_dir, 'tiles', name) if tiles else None))
parts.append((path, name))
finally:
@@ -484,6 +720,8 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False,
'parts': [{'name': name, 'from_cm': str(cuts[i]), 'to_cm': str(cuts[i + 1]),
**({'tiles': manifests[i]} if manifests[i] else {})}
for i, (_, name) in enumerate(parts)],
**({'proof_windows': [[f'{Decimal(a).normalize():f}', f'{Decimal(b).normalize():f}']
for a, b in windows]} if windows else {}),
'footer': footer,
'billed_metres': str(item['billed_metres']),
'placements': len(production['placements']),
@@ -492,20 +730,9 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False,
'min_dpi': round(lowest) if lowest else None}
def write_part(out, pieces, top, bottom, width, footer=None, tiles=None):
"""Rows [top, bottom) of the film, then the footer, as one PNG; with
`tiles`, a folder, also its pieces for the viewer. Returns their manifest."""
foot = footer_band(footer, width) if footer else None
height = bottom - top + (foot.height if foot else 0)
writer = PngWriter(out, width, height)
pyramid = None
if tiles:
def emit(level, index, data):
folder = os.path.join(tiles, str(level))
os.makedirs(folder, exist_ok=True)
with open(os.path.join(folder, f'{index}.png'), 'wb') as strip:
strip.write(data)
pyramid = Pyramid(width, height, emit)
def film_bands(pieces, top, bottom, width):
"""The film's rows [top, bottom) composed, BAND_ROWS at a time: (band top,
RGBA image). Pieces are read forward only, so ranges go down the film."""
cache = {}
for band_top in range(top, bottom, BAND_ROWS):
band_bottom = min(bottom, band_top + BAND_ROWS)
@@ -521,9 +748,7 @@ def write_part(out, pieces, top, bottom, width, footer=None, tiles=None):
if left or piece.x + rows.width > width:
rows = rows.crop((left, 0, min(rows.width, width - piece.x), rows.height))
band.alpha_composite(rows, (max(0, piece.x), a - band_top))
writer.band(band)
if pyramid:
pyramid.band(band)
yield band_top, band
# A piece the film has passed is done with: its pixels can go.
for piece in pieces:
if piece.y + piece.h <= band_bottom:
@@ -531,9 +756,36 @@ def write_part(out, pieces, top, bottom, width, footer=None, tiles=None):
live = {(id(p.source), p.rotation, p.mirrored, p.w, p.h) for p in pieces if p.y + p.h > band_bottom}
for key in [key for key in cache if key not in live]:
del cache[key]
if foot:
writer.band(foot)
def write_part(out, pieces, ranges, width, footer=None, tiles=None):
"""The film's rows in `ranges` [(top, bottom)], top to bottom and apart by
PROOF_GAP_CM of clear film when there are several (a proof's samples),
then the footer, as one PNG; with `tiles`, a folder, also its pieces for
the viewer. Returns their manifest."""
foot = footer_band(footer, width) if footer else None
gap = px(PROOF_GAP_CM)
height = (sum(b - a for a, b in ranges) + gap * (len(ranges) - 1) + (foot.height if foot else 0))
writer = PngWriter(out, width, height)
pyramid = None
if tiles:
def emit(level, index, data):
folder = os.path.join(tiles, str(level))
os.makedirs(folder, exist_ok=True)
with open(os.path.join(folder, f'{index}.png'), 'wb') as strip:
strip.write(data)
pyramid = Pyramid(width, height, emit)
def put(band):
writer.band(band)
if pyramid:
pyramid.band(foot)
pyramid.band(band)
for i, (top, bottom) in enumerate(ranges):
if i:
put(Image.new('RGBA', (width, gap)))
for _, band in film_bands(pieces, top, bottom, width):
put(band)
if foot:
put(foot)
writer.close()
return pyramid.close() if pyramid else None

View File

@@ -47,12 +47,18 @@ def final_png_issue(data):
return None
def require_final_png(storage, upload):
from fastapi import HTTPException
def final_png_problem(storage, upload):
"""Why this upload cannot be a final file, or None: its name and the
header chunks of the stored file."""
if not upload['name'].lower().endswith('.png'):
raise HTTPException(422, 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.')
return 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.'
response = storage.client.get_object(Bucket=storage.bucket, Key=upload['object_key'],
Range=f'bytes=0-{HEADER_BYTES - 1}')
issue = final_png_issue(response['Body'].read())
return final_png_issue(response['Body'].read())
def require_final_png(storage, upload):
from fastapi import HTTPException
issue = final_png_problem(storage, upload)
if issue:
raise HTTPException(422, issue)

View File

@@ -78,8 +78,13 @@ class Pyramid:
self._feed(level + 1, small)
def _strip(self, level, image):
# The print file's own writer, the fast one (imported here: printpng
# imports this module).
from .printpng import PngWriter
out = io.BytesIO()
image.save(out, 'PNG', compress_level=1)
writer = PngWriter(out, image.width, image.height)
writer.band(image)
writer.close()
self.emit(level, self.count[level], out.getvalue())
self.count[level] += 1

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
@@ -16,6 +17,9 @@ from uuid import NAMESPACE_URL, uuid4, uuid5
from psycopg.types.json import Jsonb
from fastapi import HTTPException
from .cart_pricing import needs_designer
from .finals import FINAL_OK, TREATED
PROOF_ABOVE_METRES = Decimal('10')
CUSTOMER_NOTE = ('O cliente pediu uma prova antes de imprimir: mande a foto da prova pelo WhatsApp '
'e espere o aceite.')
@@ -34,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
@@ -103,3 +109,55 @@ def require_unlocked(c, order):
if waiting(c, order):
child = open_child(c, order['id'])
raise HTTPException(409, f'Aguardando prova do #{child["number"]}: responda no card da prova.')
def approve_parent(c, parent, operator):
"""Prova OK is the parent's check: the full files the Prumo generated
become its finals, and with every item's final the parent enters the
queue. Items that still need a manual final stay in Arte recebida. Runs at
the answer, and again when a file finishes after it: #81's 91,5 m was
still being generated at its Prova OK and stayed behind (2026-11-24).
Returns whether the parent entered the queue."""
card = c.execute('''SELECT number FROM dtf_local.orders WHERE parent_id=%s AND proof_result='ok'
AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (parent['id'],)).fetchone()
if parent['state'] != 'rec' or parent['cancelled_at'] or not card:
return False
designer = needs_designer(parent['snapshot'])
if not designer:
generated = c.execute('''SELECT p.item_index,p.upload_id FROM dtf_local.print_files p
WHERE p.order_id=%s AND p.status='ready' AND p.upload_id IS NOT NULL
ORDER BY p.item_index''', (parent['id'],)).fetchall()
for row in generated:
# Every part of a film in parts, not only its first: the others
# never reached the folders (#114, #128, #130).
parts = [r['upload_id'] for r in c.execute('''SELECT upload_id FROM dtf_local.print_parts
WHERE order_id=%s AND item_index=%s ORDER BY part''', (parent['id'], row['item_index'])).fetchall()]
parts = parts or [row['upload_id']]
active = {r['upload_id'] for r in c.execute('''SELECT upload_id FROM dtf_local.order_files
WHERE order_id=%s AND item_index=%s AND kind='final' AND active''',
(parent['id'], row['item_index'])).fetchall()}
# A final someone prepared or approved stays as it is.
if active and not active <= set(parts):
continue
for upload_id in parts:
if upload_id not in active:
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,%s,'final',%s,'Prumo')''',
(uuid4(), parent['id'], upload_id, row['item_index'],
f'Aprovado pela prova do #{card["number"]}'))
treatment_clause = f'AND {TREATED}' if designer else ''
ready = all(c.execute(f'''SELECT 1 FROM dtf_local.order_files f
JOIN dtf_local.orders o ON o.id=f.order_id
JOIN dtf_local.uploads u ON u.id=f.upload_id
WHERE f.order_id=%s AND f.item_index=%s AND {FINAL_OK} {treatment_clause} LIMIT 1''',
(parent['id'], i)).fetchone() for i in range(len(parent['snapshot']['items'])))
if ready:
version = c.execute('''UPDATE dtf_local.orders SET state='tra', version=version+1, updated_at=now()
WHERE id=%s RETURNING version''', (parent['id'],)).fetchone()['version']
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
VALUES(%s,'rec','tra',%s,'Prova OK')''', (parent['id'], operator))
# Entering the queue this way is Tiny's "Preparando envio" too, as a
# card moved by hand: orders with a proof skipped it.
from .payments import stage_event
stage_event(c, parent, 'tra', 'Prova OK', version)
return ready

View File

@@ -103,6 +103,11 @@ 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 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 [])
if trimmed:
lines.append(f'{lead}Faixas vazias cortadas: {_cm(trimmed)} cm')
billed = item.get('billed_metres') or item.get('metres')
if billed:
lines.append(f'{lead}Cobrado {_m(billed)} m (height_cm {_cm(production.get("height_cm"))})')

View File

@@ -63,7 +63,7 @@ def approve(c, row, items, reviewer):
for item, original in zip(items, draft['items']):
if item.mode != original['mode'] or list(map(str, item.uploads)) != original['uploads']:
raise HTTPException(422, 'O produto e os arquivos não podem mudar na revisão.')
if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged'] or item.residue_accepted != original.get('residue_accepted', 0) or item.stroke_class != original.get('stroke_class') or item.stroke_px != original.get('stroke_px') or item.stroke_choice != original.get('stroke_choice') or (item.split and item.split.model_dump()) != original.get('split'):
if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged'] or item.residue_accepted != original.get('residue_accepted', 0) or item.close_pieces != original.get('close_pieces', 0) or item.stroke_class != original.get('stroke_class') or item.stroke_px != original.get('stroke_px') or item.stroke_choice != original.get('stroke_choice') or (item.split and item.split.model_dump()) != original.get('split'):
raise HTTPException(422, 'A montagem e a confirmação do cliente não podem mudar na revisão.')
for upload_id in item.uploads:
upload = upload_row(c, upload_id, row['owner'])
@@ -75,6 +75,7 @@ def approve(c, row, items, reviewer):
coupon_code=draft.get('coupon'),
customer_document=(draft.get('customer') or {}).get('cnpj'),
wants_treatment=draft.get('treatment', False),
wants_redesign=draft.get('redesign', []),
treatment_rule=not draft.get('montador'))
# Keep the review snapshot's own fields with each priced item.
priced = cart['items']
@@ -94,12 +95,14 @@ def approve(c, row, items, reviewer):
**({'proof_y_fraction': original['proof_y_fraction']}
if original.get('proof_y_fraction') is not None else {}),
**({'source_dpi': original['source_dpi']} if original.get('source_dpi') else {}),
**({'close_pieces': original['close_pieces']} if original.get('close_pieces') else {}),
**({'split': original['split']} if original.get('split') else {})})
items_total = cart['items_total']
coupon = cart['coupon']
discount = coupon['discount_cents'] if coupon else 0
flags = cart['grade_flags']
treatment = cart['treatment']
redesign = cart['redesign']
metres = sum(Decimal(i['billed_metres']) for i in priced)
try:
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
@@ -112,6 +115,8 @@ def approve(c, row, items, reviewer):
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
# Ajuste Fino: per art, with the row's band (front 1a).
**({'treatment': treatment} if treatment else {}),
# Ajuste Fino Redesenho: per art, one price, 48 h (front 1b).
**({'redesign': redesign} if redesign else {}),
# The art grade decision stored with the quote (front 8.5).
**({'grade_flags': flags} if flags else {}),
# The coupon used, for the order card, Números and Tiny (front 8.3).
@@ -119,7 +124,7 @@ def approve(c, row, items, reviewer):
# Browser timings are kept for Números, never for the price (0.12).
**({'timings': draft['timings']} if draft.get('timings') else {}),
'total_cents': items_total - discount + quoted_freight['total_cents']
+ treatment.get('cents', 0)}
+ treatment.get('cents', 0) + redesign.get('cents', 0)}
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
(Jsonb(approved), reviewer, row['id']))
# Approved and payable now: the files wait for the payment, not for ever.

View File

@@ -145,11 +145,17 @@ def quote_view(c, row, order=None, attempt=None, known=False):
from .cart_pricing import treatment_price
treatment = treatment_price(items, (row['draft'] or {}).get('treatment'),
catalog.current(c)['tratamento']) or None
redesign = (row['approved'] or {}).get('redesign')
if not redesign and (row['draft'] or {}).get('redesign'):
from .cart_pricing import redesign_price
redesign = redesign_price(items, (row['draft'] or {}).get('redesign'),
catalog.current(c)['redesenho']) or None
return {'id': row['id'], 'created_at': row['created_at'],
'draft': row['draft'], 'approved': row['approved'],
'expires_at': expires_at.isoformat() if expires_at else None,
'expired_at': row['expired_at'].isoformat() if row.get('expired_at') else None,
'prumo': prumo.customer_summary(items), 'treatment': treatment,
'redesign': redesign,
'status': 'paid' if order else 'discarded' if row.get('discarded_at') else 'expired' if expired
else 'approved' if row['approved'] else 'pending_review',
'auto_approved': row.get('reviewed_by') == 'auto',

View File

@@ -42,6 +42,7 @@ An order someone already moved further in Tiny is never moved back, and an
invoiced one is not cancelled here (its nota fiscal is cancelled in Tiny).
Pickup orders carry the client's "retirar pessoalmente" forma de envio.
"""
import logging
import os
import secrets
import time
@@ -51,9 +52,6 @@ from urllib.parse import urlencode
import httpx
from . import catalog
from .core import db
API = 'https://api.tiny.com.br/public-api/v3'
AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect'
# Not TINY_PRODUCT_<MODE>: app/core/secrets.py reads any variable ending in
@@ -82,6 +80,13 @@ METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_MET
SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX', 'premium': 'DTFIMP.TXP'}
STEP_DEFAULTS = {'uvfile': 'DTFIMP.UV.010CM', 'uv': 'DTFIMP.UV.010CM'}
METRE_DEFAULTS = {'uvfile': 'DTFIMP.UV.1MT', 'uv': 'DTFIMP.UV.1MT'}
# Ajuste Fino and Redesenho are sold per art by their own SKUs (Marcus,
# 2026-11-12). TINY_PRODUCT_TREATMENT, a numeric id, still replaces the
# treatment SKU; the Redesenho front will use its SKU later.
TREATMENT_SKU_SETTING = 'TINY_SKU_TREATMENT'
TREATMENT_SKU_DEFAULT = 'DTFIMP.AJF.UN'
REDESIGN_SKU_SETTING = 'TINY_SKU_REDESIGN'
REDESIGN_SKU_DEFAULT = 'DTFIMP.AJF.RED'
PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada',
'avulsa': 'DTF Têxtil 57 cm · artes avulsas',
'uvfile': 'DTF UV 27 cm · folha montada',
@@ -133,19 +138,20 @@ PICKUP_EXACT = 'retirar pessoalmente'
# Dropstar's own ids, read from its store orders with app.tiny_probe exemplo
# (2026-10-19). The app may not list formas de recebimento, so these are not
# looked up: Pix and credit card, as the store's orders are paid, and the
# DropStar carrier its pickup orders name. Dinheiro and, for the customer's
# credit, Dropstar's own "CORREÇÃO DTF" were sent by Marcus on 2026-10-27, for
# the orders the team registers as paid outside the site (D-35). "Boleto" is
# DropStar carrier its pickup orders name. Dinheiro was sent by Marcus on
# 2026-10-27, for the orders the team registers as paid outside the site
# (D-35). The customer's credit is "CREDITO PRE-PAGO" (Marcus, 2026-11-18);
# "CORREÇÃO DTF", used for it before, is for correction orders only. "Boleto" is
# for a montador Venda order (front 7a.3); no id is known yet, and while
# TINY_RECEIPT_BOLETO is empty the order goes without a forma de recebimento.
_BOLETO = os.environ.get('TINY_RECEIPT_BOLETO', '').strip()
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 977493654,
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 987762591,
**({'faturado': int(_BOLETO)} if _BOLETO.isdigit() else {})}
PICKUP_CARRIER = 761565838
# Dropstar's answers: the financial category "DTF SITE" (RECEITAS, id sent on
# 2026-10-26; it goes in pagamento.categoria, and replaced the store's
# "DUPLICADO DROP", 965775137), no seller (Tiny sets it from the contact,
# 2026-10-23), and the marcador SITE DTF, added after the order is created:
# 2026-10-23; a montador Venda carries who assembled it, 2026-11-17), and the marcador SITE DTF, added after the order is created:
# POST /pedidos does not take marcadores. Capitals, no accent, no extra
# space: the string Kondado reads for Power BI.
CATEGORY = 986932924
@@ -153,6 +159,15 @@ CATEGORY = 986932924
# the rules document (D-21) keeps the two channels apart in the financial.
CATEGORIES = {'dropflow': 987032506}
TAG = 'SITE DTF'
# An order paid with the customer's credit also carries this marcador
# (Marcus, 2026-11-18), beside SITE DTF.
CREDIT_TAG = 'CREDITO PRE-PAGO'
def order_tags(payload):
"""The marcadores an order gets in Tiny."""
paid = payload.get('payment') or {}
return [TAG] + ([CREDIT_TAG] if paid.get('method') == 'credit' else [])
# Freight is the sender's (CIF), as on the store's orders.
FREIGHT_PAID_BY = 'R'
# The forma de envio each delivery service uses, by name; a Correios service
@@ -174,6 +189,17 @@ class TinyError(Exception):
pass
class TinyRateLimit(TinyError):
"""Too many calls for the moment: the outbox's next try goes through
(Sentry DTF-API-C). `transient`: the worker reports it only if it repeats."""
transient = True
class TinyUnavailable(TinyError):
"""Tiny answered with a server error (5xx): down for a moment, so what
depends on the answer waits for the outbox's next try."""
class TinyNotConnected(TinyError):
"""No authorised connection yet: an operator must click "Conectar Tiny"."""
@@ -189,15 +215,8 @@ def configured():
def required_settings():
"""The OAuth application, and a product id for each mode not sold by SKU."""
required = ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'] + [
return ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'] + [
setting for mode, setting in PRODUCT_SETTINGS.items() if not (sku_prefix(mode) or step_sku(mode))]
# A paid treatment is a line of its own: missing, every treated order would
# fail at the Tiny, so ask for it with the rest of the settings.
with db.connect() as c:
treatment = catalog.current(c)['tratamento']
if treatment['enabled'] and treatment['unit_cents'] > 0:
required.append('TINY_PRODUCT_TREATMENT')
return required
# The stack passes every setting, empty when unset, so empty means "the
@@ -221,6 +240,11 @@ def metre_sku(mode):
return setting(METRE_SETTINGS[mode]) or ('' if setting(STEP_SETTINGS[mode]) else METRE_DEFAULTS.get(mode, ''))
def treatment_sku():
"""The Ajuste Fino SKU, the client's catalogue default when unset."""
return setting(TREATMENT_SKU_SETTING) or TREATMENT_SKU_DEFAULT
def mode_codes(mode):
"""Every SKU code a mode sold by SKU uses, or [] for a mode sold by product id."""
if step_sku(mode):
@@ -458,6 +482,24 @@ def search_forms(document):
return list(dict.fromkeys((punctuated(d), d)))
def list_sellers(orders, pages=10):
"""Tiny's sellers (vendedores) as [{id, name}], for the Kanban user a
Venda's seller comes from (Marcus, 2026-11-17). v3 names the seller on
the entry or on its contact; both are read."""
sellers = []
for page in range(pages):
found = orders.request('GET', '/vendedores', params={'limit': 100, 'offset': page * 100})
items = found if isinstance(found, list) else (found.get('itens') or [])
for entry in items:
contact = entry.get('contato') or {}
name = entry.get('nome') or contact.get('nome') or contact.get('fantasia') or ''
if entry.get('id'):
sellers.append({'id': entry['id'], 'name': name or f"Vendedor {entry['id']}"})
if len(items) < 100:
break
return sorted(sellers, key=lambda s: s['name'].lower())
def search_contacts(orders, query, limit=10):
"""Up to `limit` contacts matching what was typed (the montador's typeahead,
front 7a.3): by CPF/CNPJ when it is only digits and punctuation, else by
@@ -517,7 +559,7 @@ def business_days_after(day, days):
return day
def order_payload(payload, contact_id, today=None, product_id=None, shipping=None):
def order_payload(payload, contact_id, today=None, product_id=None, shipping=None, contact_seller=None):
"""The v3 'pedido' for a paid order's approved snapshot, filled in as the
store's own orders are: payment, carrier and expected date. product_id finds
a SKU's product id by its code; shipping(service) the forma de envio and de
@@ -537,27 +579,47 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
line['infoAdicional'] = note + f" · {item['billed_metres']} m"
items.append(line)
continue
setting = PRODUCT_SETTINGS[item['mode']]
product = os.environ.get(setting, '')
product_setting = PRODUCT_SETTINGS[item['mode']]
product = os.environ.get(product_setting, '')
if not product.isdigit():
raise TinyError(f'{setting} must be the Tiny product id')
raise TinyError(f'{product_setting} must be the Tiny product id')
items.append({'produto': {'id': int(product)},
'quantidade': float(Decimal(item['billed_metres'])),
'valorUnitario': money(item['unit_cents']),
'infoAdicional': note})
treatment = order.get('treatment') or {}
if treatment.get('cents'):
setting = os.environ.get('TINY_PRODUCT_TREATMENT', '')
if not setting.isdigit():
raise TinyError('TINY_PRODUCT_TREATMENT must be the Tiny product id')
# Per art (front 1a): the line carries the band unit price and the arts
# as its quantity. An old quote without those keeps one art at its total.
arts = int(treatment.get('arts') or 1)
unit = int(treatment.get('unit_cents') or treatment['cents'])
items.append({'produto': {'id': int(setting)}, 'quantidade': arts,
# The numeric product id the client gave still wins; otherwise the SKU
# Marcus registered is resolved in the catalogue.
legacy = os.environ.get('TINY_PRODUCT_TREATMENT', '')
if legacy.isdigit():
product = int(legacy)
else:
code = treatment_sku()
if product_id is None:
raise TinyError(f'{TREATMENT_SKU_SETTING} needs the SKUs looked up in Tiny')
product = product_id(code)
items.append({'produto': {'id': product}, 'quantidade': arts,
'valorUnitario': money(unit),
'infoAdicional': 'Ajuste Fino · '+str(arts)+
(' arte' if arts == 1 else ' artes')+' · +24 h'})
redesign = order.get('redesign') or {}
if redesign.get('cents'):
# Ajuste Fino Redesenho (front 1b): per art, resolved by its SKU code,
# one price (never a band), 48 h. Empty setting means the default code.
if product_id is None:
raise TinyError('TINY_SKU_REDESIGN needs the SKU looked up in Tiny')
code = setting(REDESIGN_SKU_SETTING) or REDESIGN_SKU_DEFAULT
arts = int(redesign.get('arts') or 1)
unit = int(redesign.get('unit_cents') or redesign['cents'])
items.append({'produto': {'id': product_id(code)}, 'quantidade': arts,
'valorUnitario': money(unit),
'infoAdicional': 'Ajuste Fino Redesenho · '+str(arts)+
(' arte' if arts == 1 else ' artes')+' · +48 h'})
freight = order['freight']
service = freight.get('service')
pickup = service == 'pickup'
@@ -569,6 +631,13 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
'valorFrete': money(freight['total_cents']),
'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''),
'observacoesInternas': internal_note(payload)}
# The seller in the customer's Tiny registration (dados complementares):
# Tiny does not fill it on an order made this way, and it cannot be set
# after (Marcus, 2026-11-26). Without one, a montador Venda goes with who
# assembled it (Marcus, 2026-11-17), a Site order without.
seller = contact_seller or (order.get('seller') or {}).get('id')
if seller:
pedido['vendedor'] = {'id': int(seller)}
coupon = order.get('coupon') or {}
if coupon:
# Tiny's v3 order has the order-level discount next to valorFrete.
@@ -579,16 +648,24 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
# The carrier's time already counts production; a pickup is ready after it.
days = freight.get('days') if not pickup else int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0)
if days is not None:
days = int(days) + (1 if treatment.get('cents') else 0)
# Redesenho adds 48 h (two working days); the basic adds one.
extra = 2 if redesign.get('cents') else 1 if treatment.get('cents') else 0
days = int(days) + extra
pedido['dataPrevista'] = business_days_after(day, days).isoformat()
# Paid at once, in full, as the store's orders: one parcel on the day.
pedido['pagamento'] = {'categoria': {'id': CATEGORIES.get(payload.get('origin'), CATEGORY)}}
received = RECEIPT_METHODS.get((payload.get('payment') or {}).get('method'))
method = (payload.get('payment') or {}).get('method')
received = RECEIPT_METHODS.get(method)
if received:
total = money(order['total_cents'])
pedido['pagamento'].update({'formaRecebimento': {'id': received},
'parcelas': [{'dias': 0, 'data': day.isoformat(), 'valor': total,
'formaRecebimento': {'id': received}}]})
parcela = {'dias': 0, 'data': day.isoformat(), 'valor': total,
'formaRecebimento': {'id': received}}
# A boleto installment names its bank account, so Tiny does not pick
# its preferred one ("NEXSTAR COBRANÇA", Marcus 2026-11-12).
account = setting('TINY_BOLETO_ACCOUNT')
if method == 'faturado' and account.isdigit():
parcela['meioPagamento'] = {'id': int(account)}
pedido['pagamento'].update({'formaRecebimento': {'id': received}, 'parcelas': [parcela]})
destination = order.get('destination')
if destination:
pedido['enderecoEntrega'] = {**address(destination), 'enderecoNro': destination['number'],
@@ -625,6 +702,19 @@ def configured_skus(orders, mode):
return 'ok' if not missing else 'SKU não encontrado entre os produtos ativos: ' + ', '.join(missing)
def configured_treatment(orders):
"""Whether Ajuste Fino's product is active: the numeric id when the client
gave one, else the SKU from the catalogue."""
value = os.environ.get('TINY_PRODUCT_TREATMENT', '')
if value.isdigit():
found = orders.request('GET', f'/produtos/{value}')
if found.get('situacao') != 'A':
return f"produto {value} não está ativo no Tiny ({found.get('situacao')})"
return 'ok'
orders.product_id(treatment_sku())
return 'ok'
def find_pickup(orders):
"""The forma de envio named "Retirar pessoalmente" (Dropstar's), else the one
named like "retirar", or why there is not one."""
@@ -689,9 +779,9 @@ def configured_pickup(orders):
def check(auth=None, transport=None, orders=None):
"""Read-only proof that the connection and permissions work: one order and
one contact listed, each product's SKUs found active and the pickup
forma de envio found, nothing created. Raises TinyNotConnected when there is no usable connection;
otherwise reports each read separately."""
one contact listed, each product's SKUs (and Ajuste Fino) found active and
the pickup forma de envio found, nothing created. Raises TinyNotConnected
when there is no usable connection; otherwise reports each read separately."""
orders = orders or TinyOrders(auth=auth or TinyAuth(), transport=transport)
def listed(path, **filters):
@@ -704,6 +794,7 @@ def check(auth=None, transport=None, orders=None):
reads = [('pedidos', lambda: listed('/pedidos', dataInicial=since)), ('contatos', lambda: listed('/contatos'))]
reads += [(PRODUCTS[mode], lambda mode=mode: configured_skus(orders, mode) if mode_codes(mode)
else configured_product(orders, mode)[1]) for mode in PRODUCT_SETTINGS]
reads.append(('Ajuste Fino', lambda: configured_treatment(orders)))
reads.append(('forma de envio de retirada', lambda: configured_pickup(orders)[1]))
results = {}
for name, read in reads:
@@ -735,7 +826,9 @@ class TinyOrders:
headers = {'Authorization': f'Bearer {self.auth.access_token()}'}
response = self.http.request(method, path, headers=headers, **kwargs)
if response.status_code == 429:
raise TinyError('Tiny rate limit reached; the outbox will retry')
raise TinyRateLimit('Tiny rate limit reached; the outbox will retry')
if response.status_code >= 500:
raise TinyUnavailable(f'{method} {path}: {response.status_code} {response.text[:300]}')
if response.status_code >= 400:
raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}')
return response.json() if response.content else {}
@@ -769,17 +862,34 @@ class TinyOrders:
return None
def contact(self, order):
"""The customer's contact id, and the seller of an existing one."""
cnpj = order['customer']['cnpj']
known = self.find_contact(cnpj)
if known:
return known
return known, self.contact_seller(known)
company = None
if self.names and len(cnpj) == 14:
try:
company = self.names(cnpj)
except Exception: # a name is a nicety; the order must still go
company = None
return self.request('POST', '/contatos', json=contact_payload(order, company))['id']
return self.request('POST', '/contatos', json=contact_payload(order, company))['id'], None
def contact_seller(self, contact_id):
"""The seller (vendedor) in a contact's registration, or None. A
reading Tiny refuses leaves the order without one: it must still go.
The seller cannot be set after the order is made, so a busy or
unavailable Tiny (429, 5xx, no answer) tries the whole delivery again."""
try:
seller = (self.request('GET', f'/contatos/{contact_id}').get('vendedor') or {}).get('id')
except (TinyRateLimit, TinyUnavailable):
raise
except TinyError as exc:
# The order goes without its seller, for good: Sentry hears of it.
logging.error('Tiny: could not read the seller of contact %s; the order goes without one: %s',
contact_id, exc)
return None
return int(seller) if str(seller or '').isdigit() and int(seller) > 0 else None
def find(self, payload, days=SEARCH_DAYS):
"""An order a previous delivery already created, or None."""
@@ -797,15 +907,17 @@ class TinyOrders:
return detail
return None
def tag(self, tiny_id, known=False):
"""The SITE DTF marcador on the order, once. A retry that finds the
order already created checks first, since POST adds another."""
def tag(self, tiny_id, tags, known=False):
"""The order's marcadores (order_tags), once each. A retry that finds
the order already created checks first, since POST adds another."""
missing = list(tags)
if known:
have = self.request('GET', f'/pedidos/{tiny_id}/marcadores')
have = have if isinstance(have, list) else have.get('itens') or []
if any(str(m.get('descricao', '')).strip().upper() == TAG for m in have):
return
self.request('POST', f'/pedidos/{tiny_id}/marcadores', json=[{'descricao': TAG}])
names = {str(m.get('descricao', '')).strip().upper() for m in have}
missing = [tag for tag in tags if tag not in names]
if missing:
self.request('POST', f'/pedidos/{tiny_id}/marcadores', json=[{'descricao': tag} for tag in missing])
def set_situacao(self, tiny_id, situacao):
self.request('PUT', f'/pedidos/{tiny_id}/situacao', json={'situacao': situacao})
@@ -836,16 +948,18 @@ class TinyOrders:
'tiny_id': str(existing.get('id')), 'tiny_number': str(existing.get('numeroPedido'))}
tiny_id, situacao = existing.get('id'), existing.get('situacao')
else:
contact_id = self.contact(payload['order'])
contact_id, seller = self.contact(payload['order'])
created = self.request('POST', '/pedidos', json=order_payload(
payload, contact_id, self.today, product_id=self.product_id, shipping=self.shipping))
payload, contact_id, self.today, product_id=self.product_id, shipping=self.shipping,
contact_seller=seller))
receipt = {'provider': 'tiny', 'event_key': event_key, 'status': 'created',
'tiny_id': str(created.get('id')), 'tiny_number': str(created.get('numeroPedido'))}
tiny_id, situacao = created.get('id'), ABERTA
# Tagged before it is approved, so a failure here is retried while the order is still open.
if situacao == ABERTA:
self.tag(tiny_id, known=bool(existing))
receipt['marcador'] = TAG
tags = order_tags(payload)
self.tag(tiny_id, tags, known=bool(existing))
receipt['marcador'] = ', '.join(tags)
if status_updates() and situacao == ABERTA:
self.set_situacao(tiny_id, APROVADA)
receipt['situacao'] = SITUACOES[APROVADA]

View File

@@ -30,6 +30,7 @@ team's users may not cancel by hand), and read back to show it is.
import argparse
import base64
import json
import os
import sys
import time
from datetime import datetime
@@ -165,6 +166,15 @@ def conferir(orders, out):
method, result = tiny.configured_pickup(orders)
ok &= result == 'ok'
out(f"{tiny.PICKUP_SETTING} (retirada): {result} {method.get('nome') if method else ''}".rstrip())
legacy = os.environ.get('TINY_PRODUCT_TREATMENT', '').strip()
try:
result = tiny.configured_treatment(orders)
except tiny.TinyError as exc:
result = str(exc)[:200]
ok &= result == 'ok'
label = 'TINY_PRODUCT_TREATMENT' if legacy.isdigit() else tiny.TREATMENT_SKU_SETTING
code = legacy if legacy.isdigit() else tiny.treatment_sku()
out(f'{label} (Ajuste Fino): {result} {code}'.rstrip())
out(f"{tiny.STATUS_UPDATES_SETTING}: {'ligado' if tiny.status_updates() else 'desligado'}")
for name, result in tiny.check(orders=orders).items():
if name in ('pedidos', 'contatos'):

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

@@ -5,6 +5,8 @@ import os
import threading
import time
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 .adapters import FakeTiny, LocalS3Storage, require_runtime
@@ -15,18 +17,44 @@ 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
last_names = 0.0
names_thread = None
last_tiny_keepalive = 0.0
db_down_since = None
storage = LocalS3Storage()
scan_thread = None
render_thread = None
@@ -38,7 +66,16 @@ def cleanup():
AND (expires_at<=now() OR (NOT complete AND created_at<now()-interval '1 day'))
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 50""").fetchall()
for row in rows:
storage.discard(row['object_key'],row['multipart_id'],row['complete'])
# A file this worker may not delete (outside the storage policy's
# prefixes, or a storage refusal) must not stop the cleanup of
# every file after it: it is reported and tried again tomorrow.
try:
storage.discard(row['object_key'],row['multipart_id'],row['complete'])
except ClientError as exc:
logging.error('Cleanup could not delete upload %s (%s): %s', row['id'],
row['object_key'].split('/')[0], exc.response.get('Error',{}).get('Code'))
c.execute("UPDATE dtf_local.uploads SET expires_at=now()+interval '1 day' WHERE id=%s", (row['id'],))
continue
# A generated PNG's pieces for the Kanban's viewer go with it (item 7).
if row['name'].lower().endswith('.png'):
storage.discard_prefix(f"originals/tiles/{row['id']}/")
@@ -66,6 +103,15 @@ def tick():
except Exception as exc:
delay = min(1800, 2**min(job['attempts']+1, 10))
c.execute("UPDATE dtf_local.outbox SET attempts=attempts+1, last_error=%s, available_at=now() + %s * interval '1 second' WHERE id=%s", (str(exc),delay,job['id']))
# Sentry hears of a refused delivery on its first failure and
# every tenth after, not only Integrações (the Tiny refused
# #42 fourteen times unseen, 2026-11-18). One message
# template, so Sentry keeps it as one issue per kind. A
# passing refusal (the Tiny's rate limit) only from the tenth.
attempt = job['attempts'] + 1
if attempt == 1 and not getattr(exc, 'transient', False) or attempt % 10 == 0:
logging.error('Outbox delivery to %s failed (%s, attempt %s): %s',
job['provider'], job['event_key'], attempt, str(exc)[:500])
last_tick = time.monotonic()
return processed
@@ -126,7 +172,8 @@ def resolve_names():
names_thread.start()
def loop():
global last_cleanup
global last_cleanup, db_down_since
delay = 1
while True:
try:
drain()
@@ -140,8 +187,22 @@ def loop():
tiny_keepalive()
reconcile_payments()
resolve_names()
except psycopg.OperationalError as exc:
if db_down_since is None:
db_down_since = time.monotonic()
logging.warning('Database unavailable, retrying: %s', exc)
else:
logging.debug('Database still unavailable, retrying in %s s', delay)
time.sleep(delay)
delay = min(delay * 2, 15)
continue
except Exception:
logging.exception('Local worker tick failed')
else:
if db_down_since is not None:
logging.info('Database back after %s s', int(time.monotonic()-db_down_since))
db_down_since = None
delay = 1
time.sleep(1)
class Health(BaseHTTPRequestHandler):
@@ -163,6 +224,14 @@ class Health(BaseHTTPRequestHandler):
if __name__ == '__main__':
observability.init('worker')
if isinstance(adapters['tiny'], HeldTiny):
logging.error('Worker started in production without the real Tiny: Tiny sends are held')
elif not isinstance(adapters['tiny'], FakeTiny):
try:
with connect() as c:
release_held(c)
except Exception:
logging.exception('Could not release the Tiny sends held while Tiny was off')
scan_thread = threading.Thread(target=scan_loop,args=(storage,),daemon=True)
scan_thread.start()
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)

View File

@@ -53,6 +53,8 @@ TINY_FORMA_ENVIO_RETIRADA=TBD
TINY_STATUS_UPDATES=false
# Tiny id of the forma de recebimento "Boleto" (montador Venda orders).
TINY_RECEIPT_BOLETO=
# Tiny id of the bank account each boleto installment names ("NEXSTAR COBRANÇA").
TINY_BOLETO_ACCOUNT=
# E-mail (password recovery and team alerts). off until the SMTP account exists.
MAIL_ADAPTER=off
MAIL_FROM=DTF Dropstar <nao-responda@SITE_DOMAIN>

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

@@ -89,6 +89,10 @@ x-app-environment: &app-environment
# reads (2026-10-28). true goes back to PDF's /UserUnit scale, for a RIP that
# refuses pages over 5,08 m.
PRINT_PAGE_SCALE: ${PRINT_PAGE_SCALE:-false}
# Length of each print file part, in cm: 10 m, under FlexiPRINT's 4 GB per
# image (Marcus, 2026-11-18). Before this line the stack's value never
# reached the worker, and #81 came out in 15 m parts.
PRINT_PART_CM: ${PRINT_PART_CM:-1000}
# Order creation in Tiny stays off until it has been tested against the
# client's account (Tiny has no sandbox). The application credentials can be
# set now: they let an operator connect Tiny from the Kanban, and the worker
@@ -107,6 +111,10 @@ x-app-environment: &app-environment
TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-}
TINY_PRODUCT_UV_AVULSA: ${TINY_PRODUCT_UV_AVULSA:-}
TINY_PRODUCT_TREATMENT: ${TINY_PRODUCT_TREATMENT:-}
# Ajuste Fino and Redesenho, per art, as the client's SKUs. The numeric
# TINY_PRODUCT_TREATMENT above, when set, still replaces the treatment SKU.
TINY_SKU_TREATMENT: ${TINY_SKU_TREATMENT:-}
TINY_SKU_REDESIGN: ${TINY_SKU_REDESIGN:-}
TINY_SKU_TEXTIL_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-}
TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-}
TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-}
@@ -127,6 +135,9 @@ x-app-environment: &app-environment
# The Tiny forma de recebimento id of "Boleto", for invoiced montador Venda
# orders (front 7a.3). Empty: the order goes without one and its note says so.
TINY_RECEIPT_BOLETO: ${TINY_RECEIPT_BOLETO:-}
# The bank account every boleto installment names ("NEXSTAR COBRANÇA"), so
# Tiny does not pick its preferred one. Empty: no account is sent.
TINY_BOLETO_ACCOUNT: ${TINY_BOLETO_ACCOUNT:-}
# Sets "Aprovada" on paid orders and "Pronto para envio" on finished pickup
# orders, which the client's Tiny -> n8n notices send to customers. Turn on
# only together with TINY_ADAPTER=tiny and after n8n stops sending the
@@ -246,6 +257,7 @@ services:
start_period: 30s
deploy:
replicas: 1
update_config: {order: start-first, failure_action: rollback}
restart_policy: {condition: on-failure, delay: 5s}
worker:
@@ -325,6 +337,7 @@ services:
start_period: 15s
deploy:
replicas: 1
update_config: {order: start-first, failure_action: rollback}
restart_policy: {condition: on-failure, delay: 5s}
kanban:
@@ -351,6 +364,7 @@ services:
start_period: 15s
deploy:
replicas: 1
update_config: {order: start-first, failure_action: rollback}
restart_policy: {condition: on-failure, delay: 5s}
configs:

View File

@@ -210,6 +210,9 @@ opens by hand (CDR, AI, PSD, TIFF). The default is 200, R$ 2,00 a metro
Change it only on the client's instruction; the Site shows the new price after
the redeploy.
`TINY_SKU_TREATMENT` is the Ajuste Fino SKU (default `DTFIMP.AJF.UN`);
`TINY_BOLETO_ACCOUNT` is the bank account each boleto installment names.
## 8. Correios
PAC and SEDEX appear in the cart once `CORREIOS_CODIGO_ACESSO` (the CWS access

View File

@@ -11,7 +11,8 @@ Run from the worker's console (Portainer > Containers > worker > Console):
Removes every order with its moves, files, notices and history, every quote,
payment attempt and payment notification, and the artwork pictures. The
artwork files are marked expired, so the worker deletes them from storage
within a minute. Operators, machines, prices, the Tiny connection and the
within a minute. Operators, machines, prices, the Site tab (products, coupons,
videos with their files), the montador's tables, the Tiny connection and the
backups are kept.
It refuses if any payment was made with real money (Mercado Pago's
@@ -48,6 +49,10 @@ ACCOUNTS = [('sessions', 'sessões de clientes'), ('accounts', 'contas de client
FLOW_FOLDERS = ('1. Arte recebida', '2. Arte conferida', '3. Imprimindo',
'4. Revisão', '5. Finalizado', 'Recibos', 'Revisões')
CONFIRM = 'APAGAR'
# What stays points at some uploads: the Site's videos and captions (Marcus,
# 2026-11-16: the whole Site tab stays). Their files are left alone.
NOT_KEPT = '''id NOT IN (SELECT upload_id FROM dtf_local.site_videos WHERE upload_id IS NOT NULL
UNION SELECT captions_id FROM dtf_local.site_videos WHERE captions_id IS NOT NULL)'''
def counts(c, tables):
@@ -86,7 +91,7 @@ def main(argv=None, out=print, connect=db.connect):
out(f'Recusado: {live} pagamento(s) com dinheiro real (live_mode). Esses pedidos são de clientes.')
return 1
before = counts(c, tables)
files = c.execute('SELECT count(*) AS n FROM dtf_local.uploads WHERE purged_at IS NULL').fetchone()['n']
files = c.execute(f'SELECT count(*) AS n FROM dtf_local.uploads WHERE purged_at IS NULL AND {NOT_KEPT}').fetchone()['n']
for table, label in tables:
out(f'{before[table]:>7} {label}')
out(f'{files:>7} arquivos de arte (o worker apaga do armazenamento)')
@@ -99,7 +104,7 @@ def main(argv=None, out=print, connect=db.connect):
return 0
for table, _ in tables:
c.execute(f'DELETE FROM dtf_local.{table}')
c.execute('UPDATE dtf_local.uploads SET expires_at=now() WHERE purged_at IS NULL')
c.execute(f'UPDATE dtf_local.uploads SET expires_at=now() WHERE purged_at IS NULL AND {NOT_KEPT}')
if args.root and not args.keep_files:
for folder in clean_folders(args.root, dry_run=False):
out(f'esvaziada {folder}')

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);
@@ -319,10 +319,14 @@ try{
const m=result.pos[0].m;
return !m.bits[2*m.cw+2] && !m.bits[2*m.cw+30] && !!m.bits[15*m.cw+30];
})()`),true);
// A real finished sheet keeps its own dimensions and by-metre price.
// A real finished sheet keeps its own width and by-metre price. Its 19 cm
// without ink at the bottom are cut, but for 0,5 cm (Marcus, 2026-11-18);
// the 0,7 cm at the top stay, under the 1 cm the cut starts at.
await click('#bVoltar');await click('[data-modo="file"]');
await evaluate('sendSheet()');
await waitFor(()=>evaluate('folhas.length===1 && !!folhas[0].previewSrc && metros===0.342'),'ready-sheet image');
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].previewSrc && folhas[0].med.alt>34 && folhas[0].corte?.topo===0 &&
folhas[0].corte.fim>18 && Math.abs(metros-(folhas[0].med.alt-folhas[0].corte.fim)/100)<0.0001`),'ready-sheet image, trimmed');
assert.equal(await evaluate(`$('lista').textContent.includes('cm vazios do fim do arquivo. Cobrado: 1,00 m.')`),true);
// On its way at once, with its own row under the uploader (Dropstar,
// 2026-10-29). There is no storage here, so it fails, and says so with a
// way to try again; tests/browser_test.mjs sends it for real.
@@ -343,7 +347,8 @@ try{
// With a sheet loaded the declaration is locked; it cannot flip under the customer.
assert.equal(await evaluate(`document.querySelector('#tipoEnvio .cam[data-tipo="avulsa"]').disabled`),true);
await evaluate(`(()=>{const el=$('lista').querySelector('[data-repf]');el.value=2;el.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await waitFor(()=>evaluate('metros===0.684'),'ready-sheet repetitions');
// Two copies and the 8 mm between them (Marcus, 2026-11-26).
await waitFor(()=>evaluate('Math.abs(metros-(2*folhas[0].m+0.008))<0.0001 && folhas[0].m<0.2'),'ready-sheet repetitions');
assert.equal(await evaluate(`document.querySelectorAll('.folhaPrevia').length`),1);
await evaluate(`(()=>{folhas.push({f:new File(['manual'],'manual.cdr'),med:null,rep:1,m:1,an:null});pintaFolha();})()`);
await waitFor(()=>evaluate(`itemAtual?.nota===0 && itemAtual?.unit===PRECO[modo]+TAXA_MANUAL`),'mixed analyzed and manual sheets: the price plus the manual charge');
@@ -378,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');
@@ -142,7 +142,9 @@ try{
await site.click('[data-sel="0"]');
assert.equal(await site.eval('pedido[0].marcado===true && itensAPagar().length===1'),true);
assert.equal(await site.eval(`Math.abs(pedido[0].total-${total})<0.005`),true);
assert.equal(await site.eval('document.getElementById("bPagar").disabled'),false);
// The freight quote and the customer checks arrive on their own time: wait
// for Pagar to open instead of reading it once (CI run 356).
await waitFor(()=>site.eval('!document.getElementById("bPagar").disabled'),'Pagar enabled');
await site.click('#bPagar');
try{
// A cart the Site can price is approved at once: the customer pays now.
@@ -171,9 +173,15 @@ try{
assert.equal(await kanban.eval('sessionStorage.getItem("dtf-operator")'),null);
assert.equal(await kanban.eval('document.getElementById("password").value'),'');
await kanban.click('[data-tab="site"]');
await waitFor(()=>kanban.eval('!!document.querySelector("[data-site-tab=\\"videos\\"]")'),'Site tabs in Gestão');
await kanban.click('[data-site-tab="videos"]');
await waitFor(()=>kanban.eval('document.querySelectorAll("#site-videos-list .siteVideoRow").length===6'),
'six video slots in Gestão');
assert.equal(await kanban.eval('document.querySelectorAll("#site-videos-list input[type=file]").length'),12);
assert.equal(await kanban.eval('document.querySelectorAll("#site-videos-list input[type=file]").length'),0);
await kanban.click('#site-videos-list .siteVideoRow .btn');
await waitFor(()=>kanban.eval('document.querySelectorAll(".modal input[type=file]").length===2'),'video edit dialog');
await kanban.eval('document.querySelector(".modal .dlghead .btn.sq")?.click()');
await waitFor(()=>kanban.eval('!document.querySelector(".modal")'),'video dialog closed');
await mkdir('output/local',{recursive:true});
await kanban.eval('document.getElementById("site-videos-panel").scrollIntoView()');
await kanban.screenshot('output/local/kanban-videos.png');
@@ -227,12 +235,10 @@ try{
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel');
// The Prumo report is on the card before the designer opens the file.
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] .prumo')`),'Prumo report');
// No machine at payment (Dropstar, 2026-11-05): the pull chooses one. It is
// the machine this test made after sign-in.
// No machine at payment (Dropstar, 2026-11-05): pulling without a session
// machine asks which machine takes the card (DTF-WEB-4). It is the machine
// this test made after sign-in.
const machineId=testMachine;
await kanban.eval(`(()=>{const s=document.querySelector('[data-order="${oid}"] select[aria-label="Máquina do pedido"]');
s.value=${JSON.stringify(machineId)};s.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').machine?.id===${JSON.stringify(machineId)}`),'machine chosen');
// Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão before Finalizado.
for(const [title,state] of [['Arte conferida','tra'],['Imprimindo','imp'],['Revisão','rev'],['Finalizado','fin']]){
if(state==='tra'){
@@ -275,6 +281,12 @@ try{
}
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title);
await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`);
if(state==='imp'){
// The order has no machine and the session has none: pick it here.
await waitFor(()=>kanban.eval(`!!document.querySelector('.mchoice[data-machine="${machineId}"]')`),'machine chooser');
await kanban.click(`.mchoice[data-machine="${machineId}"]`);
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').machine?.id===${JSON.stringify(machineId)}`),'card machine chosen');
}
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state);
if(state==='tra'){
// The file opens from the card itself, without first expanding the order.
@@ -290,7 +302,9 @@ try{
// Other orders the earlier suites left in the queue may still be coming
// down: only once the round ends must no half-written file be left.
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder round finished',60000);
assert.equal((await savedFiles('2. Arte conferida')).some(n=>n.endsWith('.baixando')),false);
assert.equal((await savedFiles('2. Arte conferida')).some(n=>/\.(baixando|crswap)$/.test(n)),false);
// Written in the work folder and moved in whole: nothing stays there (order #30).
assert.deepEqual(await savedFiles('_tmp'),[]);
assert.equal((await savedFiles('1. Arte recebida')).some(n=>n.startsWith(prefix)),false);
// A file whose order was deleted leaves the folder.
await kanban.eval(`(async()=>{const dir=await window.picked.getDirectoryHandle('2. Arte conferida',{create:true});
@@ -344,6 +358,12 @@ try{
await kanban.click('[data-tab="stats"]');
await waitFor(()=>kanban.eval(`document.querySelector('#stats-kpis').children.length>0
&& document.querySelector('#stats-machine-body').children.length>0`),'Números tab and machines by month');
// The stage-times dialog (D1) opens from Números and keeps its five rows.
await kanban.click('#edit-stage-limits');
await waitFor(()=>kanban.eval('!!document.querySelector(".modal.limitsDialog")'),'stage-times dialog');
assert.equal(await kanban.eval('document.querySelectorAll(".modal.limitsDialog tbody tr").length'),5);
await kanban.eval('document.querySelector(".modal .dlghead .btn.sq").click()');
await waitFor(()=>kanban.eval('!document.querySelector(".modal")'),'stage-times dialog closed');
// Cotações lives in its own file now: the list and the review panel load too.
await kanban.click('[data-tab="quotes"]');
await waitFor(()=>kanban.eval(`document.querySelector('#quote-filters').children.length>0
@@ -354,11 +374,32 @@ try{
await waitFor(()=>kanban.eval(`document.querySelector('#users-list').children.length>0
&& document.querySelector('#roles-matrix').children.length>0
&& document.querySelector('#machines-list').children.length>0`),'Usuários tab, people, roles and machines');
// More than one profile (Marcus, 2026-11-26): the form offers the others as chips.
await kanban.eval('userForm()');
await waitFor(()=>kanban.eval(`[...document.querySelectorAll('.fld > span')].some(s=>s.textContent==='Outros perfis')
&& document.querySelectorAll('.fopts .fopt').length>=8`),'user form with other profiles');
await kanban.eval(`document.querySelector('.fopts .fopt').click()`);
assert.equal(await kanban.eval(`document.querySelector('.fopts .fopt').getAttribute('aria-pressed')`),'true');
await kanban.eval(`[...document.querySelectorAll('.modal .dfoot button')].find(b=>b.textContent==='Cancelar').click()`);
await waitFor(()=>kanban.eval(`!document.querySelector('.modal')`),'user form closed');
// Pagamentos and Integrações live in their own file now: both lists still render.
await kanban.click('[data-tab="payments"]');
await waitFor(()=>kanban.eval(`document.querySelector('#payments').children.length>0`),'Pagamentos tab');
await kanban.click('[data-tab="integrations"]');
await waitFor(()=>kanban.eval(`document.querySelector('#integrations').children.length>0`),'Integrações tab');
// The phone board lives in its own file now: open its Mais and filters.
await kanban.call('Emulation.setDeviceMetricsOverride',{width:390,height:844,deviceScaleFactor:1,mobile:true});
await waitFor(()=>kanban.eval('PHONE.matches'),'phone board');
await kanban.click('#more-nav');
await waitFor(()=>kanban.eval('!!document.querySelector(".msheet")'),'phone menu');
await kanban.eval('document.querySelector(".mscrim").click()');
await waitFor(()=>kanban.eval('!document.querySelector(".msheet")'),'phone menu closed');
await kanban.click('#filter-open');
await waitFor(()=>kanban.eval('!!document.querySelector(".msheet")'),'phone filters');
await kanban.eval('document.querySelector(".mscrim").click()');
await waitFor(()=>kanban.eval('!document.querySelector(".msheet")'),'phone filters closed');
await kanban.call('Emulation.setDeviceMetricsOverride',{width:1440,height:1000,deviceScaleFactor:1,mobile:false});
await waitFor(()=>kanban.eval('!PHONE.matches'),'desktop board again');
// A guest sees the order paid in this browser; creating an account keeps it.
const portal=await page(siteOrigin+'/conta/pedidos?order='+oid);
await waitFor(async()=> (await portal.text()).includes('Finalizado'),'customer order tracking');

View File

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

View File

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

View File

@@ -25,6 +25,16 @@ def run():
status,amount_cents,response) VALUES(%s,%s,'mercadopago',%s,'card','approved',1490,%s) RETURNING id''',
(uuid4(), quote, str(uuid4()), Jsonb({'live_mode': True}))).fetchone()['id']
# A Site video's file stays: the whole Site tab is kept (Marcus, 2026-11-16).
video_upload, video_id = uuid4(), None
with db.connect() as c:
taken = {row['id'] for row in c.execute('SELECT id FROM dtf_local.site_videos').fetchall()}
video_id = next(name for name in ('retirada', 'sala', 'nota', 'avulsas', 'subindo', 'png') if name not in taken)
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,expires_at)
VALUES(%s,%s,'reset-video.mp4',1,%s,'',true,now()+interval '30 days')''',
(video_upload, owner, f'originals/reset-test-{video_upload}'))
c.execute("INSERT INTO dtf_local.site_videos(id,upload_id) VALUES(%s,%s)", (video_id, video_upload))
lines = []
# Real money paid: nothing happens, even when confirmed.
assert launch_reset.main(['--confirmar', 'APAGAR'], out=lines.append) == 1
@@ -47,7 +57,11 @@ def run():
for table in ('orders', 'quotes', 'payment_intents', 'movements', 'outbox'):
assert c.execute(f'SELECT count(*) AS n FROM dtf_local.{table}').fetchone()['n'] == 0, table
assert not c.execute('''SELECT 1 FROM dtf_local.uploads WHERE purged_at IS NULL
AND expires_at>now()''').fetchone()
AND expires_at>now() AND id<>%s''', (video_upload,)).fetchone()
assert c.execute('SELECT expires_at>now() AS kept FROM dtf_local.uploads WHERE id=%s',
(video_upload,)).fetchone()['kept']
c.execute('DELETE FROM dtf_local.site_videos WHERE id=%s', (video_id,))
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s', (video_upload,))
assert c.execute('SELECT count(*) AS n FROM dtf_local.operators').fetchone()['n'] >= 1
assert any('Apagado.' in line for line in lines) and 'continua de onde parou' in lines[-1], lines
# The numbering is not reset: DTF-1…DTF-15 already exist in Tiny.
@@ -77,7 +91,7 @@ def run():
'4. Revisão', '5. Finalizado', 'Recibos', 'Revisões'):
assert list((root / name).iterdir()) == [], name
assert (root / 'Estampas' / '1001.png').read_bytes() == b'art'
print('PASS: launch cleanup refuses real payments, counts first, then removes test orders and quotes, keeping the numbering and the art library')
print('PASS: launch cleanup refuses real payments, counts first, then removes test orders and quotes, keeping the numbering, the Site videos\' files and the art library')
if __name__ == '__main__':

View File

@@ -13,7 +13,7 @@ def final_stub(c, oid, owner):
uid = uuid4()
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,'machine-log-test.png',1,%s,'',true,now()+interval '1 day','clean')''',
(uid, owner, f'machine-log-test/{uid}'))
(uid, owner, f'originals/machine-log-test-{uid}'))
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,0,'final','machine log test','test')''', (uuid4(), oid, uid))

View File

@@ -12,7 +12,7 @@ def final_stub(c, oid, owner):
uid = uuid4()
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,'machine-test.png',1,%s,'',true,now()+interval '1 day','clean')''',
(uid, owner, f'machine-test/{uid}'))
(uid, owner, f'originals/machine-test-{uid}'))
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,0,'final','machine test','test')''', (uuid4(), oid, uid))

View File

@@ -47,4 +47,42 @@ assert.notDeepEqual(
apiError('/quotes/ba39b432-b0d1-4b1b-8971-09123e067067', 422, expired).options.fingerprint,
apiError('/orders/ba39b432-b0d1-4b1b-8971-09123e067067', 422, expired).options.fingerprint);
// Every red message reaches Sentry, also one the page caught itself; the
// same text an API error already sent (or deliberately skipped) is not doubled.
captured = null;
window.dtfObservability.uiError('Pastas automáticas: A última tentativa falhou: DTF-26-item-1.png bloqueado.', 'kanban');
assert.ok(captured, 'uiError sends a caught error');
assert.equal(captured.message, 'Aviso kanban: Pastas automáticas: A última tentativa falhou: :arquivo bloqueado.');
assert.deepEqual(captured.options.fingerprint, ['ui-error', 'kanban', 'Pastas automáticas: A última tentativa falhou: :arquivo bloqueado.']);
apiError('/orders', 409, 'Falta a foto da revisão.');
captured = null;
window.dtfObservability.uiError('Falta a foto da revisão.', 'kanban');
assert.equal(captured, null, 'an API error shown in red is sent once');
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:
@@ -123,7 +127,7 @@ def run():
for name, fid in files.items():
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,%s,1,%s,'m',true,now()+interval '20 days','clean')''',
(fid, owner, name + '.png', f'test/{fid}'))
(fid, owner, name + '.png', f'originals/test-{fid}'))
def place(quote, order, uploads, provider, cancelled):
content = {'customer': {'mail': mail}, 'items': [{'mode': 'file', 'uploads': [str(u) for u in uploads]}],
'total_cents': 1490}
@@ -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()
@@ -151,6 +156,10 @@ def run():
order = tester.call('/operator/quotes/' + test_quote + '/test-order', {}, operator=True)
assert order['payment']['provider'] == 'teste' and order['state'] == 'rec', order
assert tester.call('/operator/quotes/' + test_quote + '/test-order', {}, operator=True)['id'] == order['id']
# The quote is that test order's now: registering it names the test order (Sentry DTF-WEB-D).
refused = tester.call('/operator/quotes/' + test_quote + '/register', {'origin': 'atendimento', 'method': 'cash'},
operator=True, expected=409)
assert 'pedido de teste #' + str(order['number']) in refused['detail'], refused
version = order['version']
# Arte conferida, the print queue, takes the order once its final is approved.
from tests.smoke_test import final_png_bytes

View File

@@ -9,6 +9,7 @@ Kanban until someone records what was done.
Run inside the API container (it needs Pillow): python -m tests.print_file_test
"""
import io
from decimal import Decimal
import time
from urllib.request import urlopen
from uuid import uuid4
@@ -106,6 +107,36 @@ def run():
assert row['detail']['footer'].startswith('DROPSTAR · Pedido DTF-%d · Item 1/1 · ' % order['number']), row['detail']
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
# sends what the Site cut from the top and bottom of a 27 x 30 cm UV sheet
# with 20 cm of art in the middle, as web/site-upload.js aplicaCorte does.
# The order bills and prints the 21 cm left, the art whole.
# At 300 DPI, so neither the Site nor the server asks for a resolution note.
sheet = Image.new('RGBA', (px(27), px(30)))
sheet.paste(Image.new('RGBA', (px(23), px(20)), (30, 60, 200, 255)), (px(2), px(5)))
buffer = io.BytesIO()
sheet.save(buffer, 'PNG', dpi=(300, 300))
sheet_upload = upload_bytes(client, buffer.getvalue(), name='LOCAL-TRIMMED-SHEET.png')
trimmed = {'mode': 'uvfile', 'metres': '0.21', 'grade': 90, 'uploads': [sheet_upload],
'production': {'version': 3, 'film_width_cm': 27, 'height_cm': 21,
'sources': [{'upload_id': sheet_upload, 'kind': 'sheet', 'width_cm': 27,
'length_cm': 21, 'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
'measurement': 'file', 'trim_top_cm': 4.5, 'trim_bottom_cm': 4.5}],
'placements': [{'source_index': 0, 'copy_index': 0, 'x_cm': 0, 'y_cm': 0,
'width_cm': 27, 'length_cm': 21, 'rotation_degrees': 0,
'mirrored': False}]},
'quality_status': 'ok', 'quality_acknowledged': False}
sheet_order, sheet_row = wait_print(client, paid_order(client, trimmed)['id'], 'ready')
assert any(line.endswith('Faixas vazias cortadas: 9,0 cm') for line in sheet_order['prumo']), sheet_order['prumo']
assert Decimal(sheet_order['snapshot']['items'][0]['billed_metres']) == 1, sheet_order['snapshot']['items'][0]
trimmed_film = download_png(client, sheet_row['upload_id'])
assert trimmed_film.size == (px(27), px(21) + px(1.5)), trimmed_film.size
# 0,5 cm of margin above and below the art, which fills the rest.
assert trimmed_film.getpixel((px(13), px(0.2)))[3] == 0 and trimmed_film.getpixel((px(13), px(20.8)))[3] == 0
assert trimmed_film.getpixel((px(13), px(1))) == (30, 60, 200, 255)
assert trimmed_film.getpixel((px(13), px(20))) == (30, 60, 200, 255)
print('PASS: a ready sheet with its empty strips cut bills and prints only what is left')
# Item 7: "Abrir e conferir" gets the file in pieces, the first of which is
# the top of the film, then the original.
view = client.call('/operator/orders/' + order['id'] + '/view', operator=True)['files']
@@ -124,6 +155,9 @@ def run():
mine = [f for f in early['files'] if f['order'] == oid]
assert [(f['upload_id'], f['state']) for f in mine] == [(str(row['upload_id']), 'rec')], early['files']
assert mine[0]['name'].startswith('DTF-%d-item-1' % order['number']) and early['states'] == {oid: 'rec'}
# The folders download a whole list one file after another: an hour's link,
# not the 5 minutes that ran out before the last ones began.
assert 'X-Amz-Expires=3600' in mine[0]['url'], mine[0]['url']
late = client.call('/operator/queue/folder', {'early': False, 'held': []}, operator=True)
assert not [f for f in late['files'] if f['order'] == oid] and late['states'] == {}
client.call('/operator/queue/folder', {'early': True, 'held': []}, expected=401)
@@ -169,6 +203,50 @@ def run():
'note': 'again'}, operator=True, expected=409)
print('PASS: generated file approved as final without re-uploading; order queued for printing')
# A ready file generated again for the part size of now (order #36,
# 2026-11-17): from Arte conferida or Imprimindo the generated final goes,
# the order is back in Arte recebida and the file is made once more.
again_upload = upload_bytes(client, artwork(), name='LOCAL-AGAIN.png')
again, made = wait_print(client, paid_order(client, loose_item(again_upload))['id'], 'ready')
v = client.call('/operator/orders/' + again['id'] + '/final-files',
{'version': again['version'], 'files': [{'item_index': 0, 'upload_id': str(made['upload_id'])}],
'note': 'ok'}, operator=True)['version']
client.call('/operator/orders/' + again['id'] + '/move', {'state': 'tra', 'version': v}, operator=True)
client.call('/operator/orders/' + again['id'] + '/print-files/again', {}, operator=True)
with db.connect() as c:
state = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (again['id'],)).fetchone()['state']
finals = c.execute('''SELECT count(*) AS n FROM dtf_local.order_files
WHERE order_id=%s AND kind='final' AND active''', (again['id'],)).fetchone()['n']
back = c.execute('SELECT reason,back FROM dtf_local.movements WHERE order_id=%s ORDER BY id DESC LIMIT 1',
(again['id'],)).fetchone()
assert (state, finals, back['reason'], back['back']) == ('rec', 0, 'Arquivo gerado de novo', True), (state, finals, back)
again, remade = wait_print(client, again['id'], 'ready')
assert str(remade['upload_id']) != str(made['upload_id']), (made, remade)
# Its name carries the version, so it is not taken for the first (#130).
assert remade['name'] == 'DTF-%d-v2-item-1.png' % again['number'], remade['name']
print('PASS: a ready file is generated again from Arte conferida, back in Arte recebida to approve')
# The generated file approved, sent to Correção (its final stops counting)
# and back: the same file is approved again, not refused as already in
# the order (Sentry DTF-WEB-10).
redo, redo_row = wait_print(client, paid_order(client, loose_item(upload_bytes(client, artwork(), name='LOCAL-REDO.png')))['id'], 'ready')
finals = [{'item_index': 0, 'upload_id': str(redo_row['upload_id'])}]
v = client.call('/operator/orders/' + redo['id'] + '/final-files',
{'version': redo['version'], 'files': finals, 'note': 'ok'}, operator=True)['version']
def version_of(oid):
with db.connect() as c:
return c.execute('SELECT version FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()['version']
client.call('/operator/orders/' + redo['id'] + '/move', {'state': 'cor', 'version': v, 'reason': 'Teste'}, operator=True)
client.call('/operator/orders/' + redo['id'] + '/move', {'state': 'rec', 'version': version_of(redo['id']),
'reason': 'Teste'}, operator=True)
client.call('/operator/orders/' + redo['id'] + '/final-files',
{'version': version_of(redo['id']), 'files': finals, 'note': 'de novo'}, operator=True)
with db.connect() as c:
rows = c.execute('''SELECT active FROM dtf_local.order_files WHERE order_id=%s AND kind='final' ''',
(redo['id'],)).fetchall()
assert [r['active'] for r in rows] == [True], rows
print('PASS: a generated final that stopped counting is approved again')
# Item 10: printing, the file goes once into its machine's hot folder for
# its class; Flexi taking it is reported; leaving Imprimindo withdraws
# what Flexi did not take.
@@ -176,6 +254,13 @@ def run():
# No class measured or chosen: the part waits for one.
assert not [p for p in client.call('/operator/queue/hot', {}, operator=True)['write'] if p['order'] == oid]
client.call('/operator/orders/' + oid + '/contraction', {'item_index': 0, 'value': 'C2'}, operator=True)
# Renamed, the machine keeps its folder, the path FlexiPRINT watches;
# no other machine may then take that folder's name.
client.call('/operator/machines/' + machine, {'name': f'Hot {tag} renomeada', 'products': ['textil']},
operator=True)
listed = next(m for m in client.call('/operator/machines', operator=True)['machines'] if m['id'] == machine)
assert listed['name'] == f'Hot {tag} renomeada' and listed['folder'] == f'Hot {tag}', listed
client.call('/operator/machines', {'name': f'Hot {tag}', 'products': ['textil']}, operator=True, expected=409)
hot = client.call('/operator/queue/hot', {}, operator=True)
due = [p for p in hot['write'] if p['order'] == oid]
assert hot['folder'] == '3. Imprimindo' and [(p['folder'], p['name']) for p in due] == \
@@ -192,7 +277,10 @@ def run():
assert not client.call(f'/operator/queue/hot/{part}', {'state': 'consumed'}, operator=True)['ok']
board = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == oid)
assert board['hot'] == {'parts': 1, 'taken': 1, 'waiting': 0}, board['hot']
print('PASS: the printing file goes once into its machine\'s hot folder for its class')
# 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, '
'and a renamed machine keeps its folder')
finally:
client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False},
operator=True)
@@ -207,6 +295,16 @@ def run():
assert red[3] == 255 and red[0] > 200 and red[1] < 60, red
print('PASS: PDF artwork drawn into the PNG print file at 300 DPI')
# Before approving, the panel asks whether the files can be finals: the
# generated PNG can, the customer's PDF original cannot, and the answer
# says why without a refusal (Sentry DTF-WEB-11). Another order's file is
# not read.
check = client.call('/operator/orders/' + pdf_order['id'] + '/final-check',
{'uploads': [str(pdf_row['upload_id']), pdf_upload, str(row['upload_id'])]}, operator=True)
assert [p['upload_id'] for p in check['problems']] == [pdf_upload], check
assert '300 DPI' in check['problems'][0]['message'], check
print('PASS: the panel learns before approving that a file cannot be a final')
# The proof card (Dropstar, 2026-10-30 and 2026-11-03): an order above
# 10 m gets a child card "Prova"; the order waits outside the queue until
# the card in Revisão gets its answer.
@@ -294,15 +392,199 @@ def run():
wait_print(client, card['id'], 'ready')
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (card['id'],))
# The proof's photo, taken in Revisão, stays reachable from its order once
# the answered card leaves the board (the proof of #30, 2026-11-17).
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.order_reviews(order_id,seq,upload_id,kind,width,height,created_by)
VALUES(%s,1,%s,'photo',1600,1200,'Revisor')''', (card['id'], readable))
client.call('/operator/orders/' + card['id'] + '/proof-answer', {'result': 'ok'}, operator=True)
mine = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == parent['id'])
assert [r['kind'] for r in mine['proof_card']['reviews']] == ['photo'], mine['proof_card']
view = client.call('/operator/orders/' + card['id'] + '/reviews/' + str(mine['proof_card']['reviews'][0]['id'])
+ '/view', operator=True)
assert view['url'] and view['kind'] == 'photo', view
assert mine['state'] == 'tra' and mine['final_items'] == [0], mine
assert mine['proof_ok_at'] and mine['proof_card']['proof_result'] == 'ok', mine
with db.connect() as c:
final = c.execute('''SELECT note,created_by FROM dtf_local.order_files
WHERE order_id=%s AND kind='final' AND active''', (parent['id'],)).fetchone()
assert final['created_by'] == 'Prumo' and 'prova' in final['note'].lower(), final
print('PASS: Prova OK turns Prumo\'s full file into the parent final and queues it')
# Entering the queue by Prova OK is Tiny's "Preparando envio", as a card
# moved by hand (orders with a proof skipped it).
with db.connect() as c:
started = c.execute("SELECT payload FROM dtf_local.outbox WHERE event_key=%s",
(f"{parent['id']}:production_started:tiny",)).fetchone()
assert started and started['payload']['event'] == 'production_started', started
print('PASS: Prova OK turns Prumo\'s full file into the parent final, queues it and tells Tiny')
# Prova OK while the parent's file is still being generated (#81, 91,5 m,
# 2026-11-24): the parent waits in Arte recebida and enters the queue on
# its own once the file is ready.
readable = upload_bytes(client, artwork(), name='LOCAL-PROOF-LATE.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)
wait_print(client, parent['id'], 'ready')
wait_print(client, card['id'], 'ready')
with db.connect() as c:
# The parent's file back to "being generated", held by a claim no worker owns.
c.execute('''UPDATE dtf_local.print_files SET status='rendering', upload_id=NULL, finished_at=NULL,
claimed_at=now(), deadline_at=now()+interval '1 hour', claim_token=%s WHERE order_id=%s''',
(str(uuid4()), parent['id']))
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (card['id'],))
client.call('/operator/orders/' + card['id'] + '/proof-answer', {'result': 'ok'}, operator=True)
mine = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == parent['id'])
assert mine['state'] == 'rec' and mine['proof_ok_at'] and not mine['final_items'], mine
with db.connect() as c:
c.execute("UPDATE dtf_local.print_files SET status='pending', claim_token=NULL WHERE order_id=%s",
(parent['id'],))
wait_print(client, parent['id'], 'ready')
deadline = time.monotonic() + 30
while (mine := next(o for o in client.call('/operator/board', operator=True)['orders']
if o['id'] == parent['id']))['state'] != 'tra' and time.monotonic() < deadline:
time.sleep(1)
assert mine['state'] == 'tra' and mine['final_items'] == [0], mine
with db.connect() as c:
moved = c.execute('''SELECT operator,reason FROM dtf_local.movements
WHERE order_id=%s AND to_state='tra' ORDER BY id DESC LIMIT 1''', (parent['id'],)).fetchone()
assert (moved['operator'], moved['reason']) == ('Prumo', 'Prova OK'), moved
with db.connect() as c:
assert c.execute("SELECT 1 FROM dtf_local.outbox WHERE event_key=%s",
(f"{parent['id']}:production_started:tiny",)).fetchone()
print('PASS: a file finished after Prova OK becomes the final, queues the order and tells Tiny')
# Cancelled, an order takes its proof card not yet answered with it: left
# on the board, the card could still be pulled and printed.
readable = upload_bytes(client, artwork(), name='LOCAL-PROOF-CANCEL.png')
parent = paid_order(client, loose_item(readable, copies=1))
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{proof}','true') WHERE id=%s",
(parent['id'],))
card = client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True)
client.call('/operator/orders/' + parent['id'] + '/cancel', {'note': 'cliente desistiu'}, operator=True)
with db.connect() as c:
gone = c.execute('SELECT cancelled_at, cancel_reason FROM dtf_local.orders WHERE id=%s', (card['id'],)).fetchone()
assert gone['cancelled_at'] and 'cliente desistiu' in gone['cancel_reason'], gone
print('PASS: cancelling an order cancels its open proof card')
# A film in parts is approved whole: only some of its parts are refused,
# or the others never reach the machine (#114, #128, #130).
whole = upload_bytes(client, artwork(), name='LOCAL-PARTS.png')
film = paid_order(client, loose_item(whole, copies=1))
_, film_row = wait_print(client, film['id'], 'ready')
second = upload_bytes(client, artwork(), name='LOCAL-PARTS-P2.png')
with db.connect() as c:
c.execute('INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id) VALUES(%s,0,2,%s)',
(film['id'], second))
refused = client.call('/operator/orders/' + film['id'] + '/final-files',
{'version': version_of(film['id']), 'note': 'só a primeira',
'files': [{'item_index': 0, 'upload_id': str(film_row['upload_id'])}]},
operator=True, expected=422)
assert 'faltam p2' in refused['detail'], refused
print('PASS: a film in parts is approved with all its parts or not at all')
# Reprinting some items (Marcus, 2026-11-26, #105): an order the machine
# 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
# the choice is then over.
first_art = upload_bytes(client, artwork(), name='LOCAL-REPRINT-A.png')
second_art = upload_bytes(client, artwork(), name='LOCAL-REPRINT-B.png')
two = [loose_item(first_art), loose_item(second_art)]
quote = client.call('/quotes', {'request_key': str(uuid4()), 'customer': CUSTOMER,
'items': two, 'freight': {'service': 'pickup'}})
approval(client, quote, two)
reprint = client.call('/orders/dev-paid', {'quote_id': quote['id']})
rid = reprint['id']
deadline = time.monotonic() + 120
while True:
board_order = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == rid)
made = {r['item_index']: r for r in board_order['print_files']}
if len(made) == 2 and all(r['status'] == 'ready' for r in made.values()):
break
assert time.monotonic() < deadline, made
time.sleep(1)
generated = {i: str(made[i]['upload_id']) for i in (0, 1)}
v = client.call('/operator/orders/' + rid + '/final-files',
{'version': board_order['version'], 'note': 'ok',
'files': [{'item_index': i, 'upload_id': generated[i]} for i in (0, 1)]}, operator=True)['version']
with db.connect() as c:
# The machine took both files on a first print.
for i in (0, 1):
c.execute('''INSERT INTO dtf_local.hot_parts(order_id,round,seq,item_index,upload_id,name,state)
VALUES(%s,1,%s,%s,%s,%s,'consumed')''', (rid, i + 1, i, generated[i], f'item-{i + 1}.png'))
# Item 2 is corrected; item 1 keeps its file ("Manter o arquivo atual").
corrected = upload_bytes(client, artwork(), name='LOCAL-REPRINT-B2.png', order_id=rid)
v = client.call('/operator/orders/' + rid + '/final-files',
{'version': v, 'note': 'arte corrigida',
'files': [{'item_index': 0, 'upload_id': generated[0]},
{'item_index': 1, 'upload_id': corrected}]}, operator=True)['version']
board_order = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == rid)
assert board_order['printed_before'] and board_order['print_suggested'] == [1], board_order.get('print_suggested')
v = client.call('/operator/orders/' + rid + '/move', {'state': 'tra', 'version': v}, operator=True)['version']
def print_items():
with db.connect() as c:
return c.execute('SELECT print_items FROM dtf_local.orders WHERE id=%s', (rid,)).fetchone()['print_items']
def version():
return next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == rid)['version']
assert print_items() == [1], print_items()
# Every item ticked by hand in Arte recebida is a choice too: entering the
# queue keeps it, the suggestion does not take its place.
client.call('/operator/orders/' + rid + '/move', {'state': 'rec', 'version': v, 'reason': 'teste'}, operator=True)
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [0, 1]}, operator=True)['print_items'] == [0, 1]
client.call('/operator/orders/' + rid + '/move', {'state': 'tra', 'version': version()}, operator=True)
assert print_items() == [0, 1], print_items()
# Back to only the corrected item, then pulled onto a machine for real.
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [1]}, operator=True)['print_items'] == [1]
machine = client.call('/operator/machines', {'name': f'Reprint {uuid4().hex[:6]}', 'products': ['textil']},
operator=True)['id']
v = client.call('/operator/orders/' + rid + '/move', {'state': 'imp', 'version': version(), 'machine_id': machine},
operator=True)['version']
with db.connect() as c:
queued = c.execute('SELECT item_index,upload_id FROM dtf_local.hot_parts WHERE order_id=%s AND round=2',
(rid,)).fetchall()
assert [(q['item_index'], str(q['upload_id'])) for q in queued] == [(1, corrected)], queued
# Sent to Revisão by mistake before Flexi took the file, and undone: the
# file goes back to the folder, alone, and the choice is the same.
v = client.call('/operator/orders/' + rid + '/move', {'state': 'rev', 'version': v}, operator=True)['version']
assert print_items() is None
v = client.call('/operator/orders/' + rid + '/move', {'state': 'imp', 'version': v, 'reason': 'engano'},
operator=True)['version']
assert print_items() == [1], print_items()
with db.connect() as c:
again = c.execute('SELECT item_index,upload_id,state FROM dtf_local.hot_parts WHERE order_id=%s AND round=3',
(rid,)).fetchall()
assert [(r['item_index'], str(r['upload_id']), r['state']) for r in again] == [(1, corrected, 'queued')], again
c.execute("UPDATE dtf_local.hot_parts SET state='consumed' WHERE order_id=%s AND round=3", (rid,))
# Flexi took it: undoing a later pass to Revisão writes nothing again.
v = client.call('/operator/orders/' + rid + '/move', {'state': 'rev', 'version': v}, operator=True)['version']
v = client.call('/operator/orders/' + rid + '/move', {'state': 'imp', 'version': v, 'reason': 'engano'},
operator=True)['version']
with db.connect() as c:
assert not c.execute('SELECT 1 FROM dtf_local.hot_parts WHERE order_id=%s AND round>3', (rid,)).fetchone()
client.call('/operator/orders/' + rid + '/move', {'state': 'rev', 'version': v}, operator=True)
from app import machine_log
with db.connect() as c:
moved = c.execute("SELECT items FROM dtf_local.movements WHERE order_id=%s AND to_state='rev' "
"ORDER BY id DESC LIMIT 1", (rid,)).fetchone()
item = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (rid,)).fetchone()['snapshot']['items'][1]
metres = machine_log.printed_since(c, machine, None)
assert moved['items'] == [1] and print_items() is None, moved
# Three passes to Revisão, two of them undone: item 2's film, once.
expected = Decimal(str(item['metres'] if item.get('metres') is not None else item.get('billed_metres') or 0))
assert metres == expected, (metres, expected)
# Chosen by hand: every item, or some; never an item the order lacks.
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='rec' WHERE id=%s", (rid,))
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [1, 0, 1]}, operator=True)['print_items'] == [0, 1]
assert client.call('/operator/orders/' + rid + '/print-items', {'items': [0]}, operator=True)['print_items'] == [0]
client.call('/operator/orders/' + rid + '/print-items', {'items': [5]}, operator=True, expected=422)
print('PASS: a reprint sends only the items chosen, keeps an all-items choice, and an undone pass to Revisão '
'neither writes again what Flexi took nor counts the film twice')
# A CDR cannot be decoded by the worker. The designer prepares the full
# parent PNG, then the worker automatically cuts the child's proof from it.

View File

@@ -27,6 +27,7 @@ def run():
quote, payment_id = uuid4(), str(900_000_000 + uuid4().int % 99_999_999)
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

@@ -18,6 +18,13 @@ def run():
with connect() as c:
c.execute('INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,expires_at) VALUES(%s,%s,%s,%s,%s,%s,true,%s)',
(uid,uuid4(),'LOCAL-RETENTION-TEST.txt',len(b'LOCAL RETENTION TEST'),key,upload,expiry))
# A file outside the storage policy's prefixes cannot be deleted: it must
# not stop the cleanup of the others, and is tried again a day later.
denied=uuid4()
with connect() as c:
c.execute('INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,expires_at,created_at) VALUES(%s,%s,%s,1,%s,%s,true,%s,%s)',
(denied,uuid4(),'LOCAL-RETENTION-DENIED.txt',f'retention-denied/{denied}','',
datetime.now(timezone.utc)-timedelta(days=1),datetime.now(timezone.utc)-timedelta(days=400)))
# Cleanup takes 50 at a time, oldest first: the suites before this one
# leave their own expired files ahead of the fixture.
for _ in range(100):
@@ -27,6 +34,10 @@ def run():
with connect() as c:
assert c.execute('SELECT purged_at FROM dtf_local.uploads WHERE id=%s',(ids[0],)).fetchone()['purged_at']
assert not c.execute('SELECT purged_at FROM dtf_local.uploads WHERE id=%s',(ids[1],)).fetchone()['purged_at']
with connect() as c:
row=c.execute('SELECT purged_at,expires_at>now() AS later FROM dtf_local.uploads WHERE id=%s',(denied,)).fetchone()
assert not row['purged_at'] and row['later'],row
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s',(denied,))
try:storage.size(f'originals/{ids[0]}');raise AssertionError('Expired bytes still exist')
except ClientError as exc:assert exc.response['ResponseMetadata']['HTTPStatusCode']==404
assert storage.size(f'originals/{ids[1]}')==len(b'LOCAL RETENTION TEST')

View File

@@ -13,6 +13,7 @@ from uuid import uuid4
from PIL import Image, ImageDraw
from app import tiny
from app.adapters import FakeTiny
from app.core import db
from tests.print_file_test import artwork
from tests.smoke_test import Client, item_spec, upload_bytes
@@ -20,6 +21,7 @@ from tests.smoke_test import Client, item_spec, upload_bytes
PASSWORD = 'senha-de-teste-123'
UV = 'uv'
PREMIUM = 'premium'
REDESIGN = 'redesenho'
def premium_sheet():
@@ -38,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,
@@ -61,11 +64,11 @@ def run():
manager.call('/session')
manager.call('/operator/me', operator=True)
manager = manager.operator_client
prices, user, treatment_enabled = [], None, None
prices, user, treatment_enabled, redesign_enabled = [], None, None, None
try:
products = manager.call('/operator/site/products')['products']
assert {product['id'] for product in products} == \
{'file', 'avulsa', 'uvfile', 'uv', 'premium', 'tratamento'}
{'file', 'avulsa', 'uvfile', 'uv', 'premium', 'tratamento', REDESIGN}
assert all(product['unit'] in ('metro', 'pedido', 'arte') and product['title'] for product in products)
# Front 3: Premium is listed and starts switched off (Marcus, 2026-11-10).
@@ -74,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
@@ -128,9 +131,65 @@ def run():
{'produto': {'id': 105}, 'quantidade': 3, 'valorUnitario': 9.9,
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}], pedido['itens']
# Front 1b: Ajuste Fino Redesenho, one price per art, never a band.
redesign = next(product for product in products if product['id'] == REDESIGN)
redesign_enabled = redesign['enabled']
assert redesign['enabled'] is False, redesign
assert redesign['title'] == 'Ajuste Fino Redesenho', redesign
assert redesign['unit'] == 'arte', redesign
manager.call(f'/operator/site/products/{REDESIGN}', {'enabled': True})
# Enabled but still unpriced: the Site hides it and the server refuses it.
refused = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
'items': [arts], 'redesign': [[0, 0]], 'freight': {'service': 'pickup'}}, expected=422)
assert refused['detail'] == 'O Redesenho não está disponível agora.', refused
banded = manager.call(f'/operator/site/products/{REDESIGN}/prices', {
'unit_cents': 2990,
'bands': [{'from_metres': '10', 'unit_cents': 690}]}, expected=422)
assert 'faixas' in banded['detail'], banded
made = manager.call(f'/operator/site/products/{REDESIGN}/prices', {'unit_cents': 2990})
prices.append(made['id'])
assert client.call('/session')['redesign_cents'] == 2990
two = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
'items': [arts], 'redesign': [[0, 0], [0, 1]], 'freight': {'service': 'pickup'}})
assert two['status'] == 'approved', two
redesenho = client.call('/quotes/' + two['id'])['approved']
assert redesenho['redesign'] == {'cents': 5980, 'hours': 48, 'arts': 2,
'unit_cents': 2990}, redesenho
assert redesenho['total_cents'] == redesenho['items'][0]['total_cents'] + 5980, redesenho
# Basic and Redesenho on different arts: each priced on its own service,
# and the basic band counts only the basic arts.
mixed = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
'items': [arts], 'treatment': [[0, 0], [0, 1], [0, 2]],
'redesign': [[0, 3], [0, 4]], 'freight': {'service': 'pickup'}})
mixed = client.call('/quotes/' + mixed['id'])['approved']
assert mixed['treatment'] == {'cents': 2970, 'hours': 24, 'arts': 3,
'unit_cents': 990}, mixed
assert mixed['redesign'] == {'cents': 5980, 'hours': 48, 'arts': 2,
'unit_cents': 2990}, mixed
assert mixed['total_cents'] == mixed['items'][0]['total_cents'] + 2970 + 5980, mixed
# Tiny: the line resolves DTFIMP.AJF.RED through the fake catalogue.
fake = FakeTiny()
pedido = tiny.order_payload({'order_id': two['id'], 'order': redesenho,
'number': 2, 'payment': {}, 'origin': 'site'}, 777,
date(2026, 11, 12), product_id=fake.product_id)
red_code = fake.product_id('DTFIMP.AJF.RED')
assert [line for line in pedido['itens'] if line['produto']['id'] == red_code] == [
{'produto': {'id': red_code}, 'quantidade': 2, 'valorUnitario': 29.9,
'infoAdicional': 'Ajuste Fino Redesenho · 2 artes · +48 h'}], pedido['itens']
# One service per art: a pair in both lists is refused by the model.
both = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
'items': [arts], 'treatment': [[0, 0]], 'redesign': [[0, 0]],
'freight': {'service': 'pickup'}}, expected=422)
assert 'Escolha Ajuste Fino ou Redesenho' in str(both['detail']), both
# Switched off again, a chosen Redesenho is refused.
manager.call(f'/operator/site/products/{REDESIGN}', {'enabled': False})
refused = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
'items': [arts], 'redesign': [[0, 0]], 'freight': {'service': 'pickup'}}, expected=422)
assert refused['detail'] == 'O Redesenho não está disponível agora.', refused
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.
@@ -214,6 +273,7 @@ def run():
staff.call(f'/operator/site/prices/{made["id"]}/cancel', {}, expected=403)
print('PASS: the Site tab switches a product off and refuses quotes, lists Premium switched off'
' and accepts it once enabled, prices Ajuste Fino per art with its band,'
' prices Redesenho per art without bands and sends it to Tiny,'
' schedules and cancels prices, charges the new price, and refuses a non-manage profile')
finally:
with db.connect() as c:
@@ -221,6 +281,9 @@ def run():
c.execute('DELETE FROM dtf_local.product_prices WHERE id=ANY(%s::bigint[])', (prices,))
c.execute("UPDATE dtf_local.products SET enabled=true WHERE id=%s", (UV,))
c.execute("UPDATE dtf_local.products SET enabled=false WHERE id=%s", (PREMIUM,))
if redesign_enabled is not None:
c.execute("UPDATE dtf_local.products SET enabled=%s WHERE id=%s",
(redesign_enabled, REDESIGN))
if treatment_enabled is not None:
try:
manager.call('/operator/site/products/tratamento', {'enabled': treatment_enabled})

View File

@@ -48,6 +48,13 @@ def run():
entry = next(row for row in published if row['id'] == 'sala')
assert entry['product'] == 'file'
assert entry['captions'] == '/api/site/videos/sala/captions'
# One floating video per product: a second one is refused before any
# copy, naming the video that holds the product (DTF-WEB-G).
refused = operator.call('/operator/site-videos/png', {'upload_id': video,
'product': 'file', 'enabled': True}, expected=409)
assert 'A sala às 3 da manhã' in refused['detail'], refused
with db.connect() as c:
assert not c.execute("SELECT 1 FROM dtf_local.site_videos WHERE id='png'").fetchone()
with urlopen(entry['src'], timeout=30) as response:
assert response.read() == VIDEO
with urlopen(Request(BASE + entry['captions'], headers=with_host()), timeout=30) as response:

View File

@@ -57,15 +57,30 @@ class Client:
self.operator_client=Client()
self.operator_client.call('/operator/login',{'email':os.environ.get('OPERATOR_EMAIL','operator@example.test'),'password':os.environ.get('OPERATOR_PASSWORD','local-operator-only')})
return self.operator_client.call(path,body,expected=expected,method=method)
request=Request(BASE+'/api'+path,data=None if body is None else json.dumps(body).encode(),
headers=headers,method=method)
try:
with self.opener.open(request,timeout=30) as response:
assert response.status==expected,(path,response.status,expected)
return json.load(response)
except HTTPError as exc:
if exc.code!=expected:raise AssertionError((path,exc.code,exc.read().decode())) from exc
return json.load(exc)
reset=False
for attempt in range(20):
request=Request(BASE+'/api'+path,data=None if body is None else json.dumps(body).encode(),
headers=headers,method=method)
try:
with self.opener.open(request,timeout=30) as response:
assert response.status==expected,(path,response.status,expected)
return json.load(response)
except HTTPError as exc:
if exc.code==expected:return json.load(exc)
text=exc.read().decode()
# The gateway's own limit (nginx, 20 r/s per address, burst 100) is
# an HTML page, not the API's JSON: a fast suite waits for it.
if exc.code==429 and text.lstrip().startswith('<html') and attempt<19:
time.sleep(1);continue
# The API allows 60 sign-ins per address in 15 min (app/core/auth.py
# throttle), and the whole suite signs in from one address: a test
# that did not ask for the limit starts the count again.
if exc.code==429 and path=='/operator/login' and not reset:
from app.core import db
with db.connect() as c:
c.execute('DELETE FROM dtf_local.login_attempts')
reset=True;continue
raise AssertionError((path,exc.code,text)) from exc
def register(client, customer, password):
"""Create an account as the Site does: with e-mail on, the code sent to the
@@ -125,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,
@@ -181,12 +200,16 @@ def run():
print('PASS: multipart resume, incomplete rejection, immutable completion, ownership, private/downloaded bytes')
# Above QUOTE_AUTO_MAX_METRES (50 m by default), so a person reviews it.
items=[item_spec(m,'13',90,uid) for m in ('file','avulsa','uvfile','uv')]
# One order, one machine (Marcus, 2026-11-26): the two textile products;
# UV goes in an order of its own.
items=[item_spec(m,'26',90,uid) for m in ('file','avulsa')]
draft={'request_key':str(uuid4()),'customer':{'cnpj':'11222333000181','zap':'11999999999','mail':'local-smoke@example.test'},
'items':items,'freight':{'service':'mock-standard','postal_code':'14400000'},
'destination':{'recipient':'Local Smoke Ltda','street':'Rua de Teste','number':'100',
'district':'Centro','city':'Franca','state':'SP','postal_code':'14400000'}}
client.call('/quotes',{**draft,'total_cents':1},expected=422)
mixed_cart=client.call('/quotes',{**draft,'items':[items[0],item_spec('uvfile','13',90,uid)]},expected=422)['detail']
assert any('outra máquina' in str(e.get('msg','')) for e in mixed_cart), mixed_cart
# Freight quoted by CEP alone cannot ship: the address is required, must be
# the quoted CEP, and a pickup order takes none.
client.call('/quotes',{**draft,'destination':None},expected=422)
@@ -222,18 +245,19 @@ def run():
corrected=[{**items[0],'metres':'1.01','grade':0},*items[1:]]
approved=client.call('/operator/quotes/'+qid+'/approve',{'items':corrected},operator=True)
assert approved['items'][0]['total_cents']==2189 and approved['items'][0]['grade']==0
assert [i['unit_cents'] for i in approved['items'][1:]]==[2190,7990,8990]
assert approved['total_cents']==2189+28470+103870+116870+int(os.environ.get('MOCK_FREIGHT_CENTS','1500'))
assert [i['unit_cents'] for i in approved['items'][1:]]==[2190]
assert approved['total_cents']==2189+56940+int(os.environ.get('MOCK_FREIGHT_CENTS','1500'))
assert approved['destination']=={**draft['destination'],'complement':''}
client.call('/operator/quotes/'+qid+'/approve',{'items':items},operator=True,expected=409)
assert not client.call('/quotes/'+qid)['auto_approved']
# 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)
@@ -264,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)
@@ -316,7 +344,7 @@ def run():
if state=='tra':
# The queue takes approved final files only.
client.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
files=[{'item_index':i,'upload_id':upload_bytes(client,final_png_bytes(str(i)),name=f'LOCAL-FINAL-{i}.png',order_id=oid)} for i in range(4)]
files=[{'item_index':i,'upload_id':upload_bytes(client,final_png_bytes(str(i)),name=f'LOCAL-FINAL-{i}.png',order_id=oid)} for i in range(len(items))]
result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True)
version=result['version']
body={'state':state,'version':version,'reason':'Local test correction' if state=='cor' else ''}

View File

@@ -84,11 +84,20 @@ def run():
identities = [operator_identity(emails['expedicao']), operator_identity(emails['vendedor'])]
made_orders, made_quotes = [], []
# A code of its own, so a brand someone saved in Estampas/ is never touched.
stamp_code = 'T' + tag
# With a dot, as Dropstar's own codes (NX.226).
stamp_code = 'T.' + tag
try:
# The seller is a Tiny seller too (Marcus, 2026-11-17): the fake Tiny
# lists two, and a Venda this user assembles carries the one chosen.
sellers = su.call('/operator/tiny/sellers', operator=True)
assert sellers == [{'id': 2001, 'name': 'Lais'}, {'id': 2002, 'name': 'Marcus'}], sellers
for role, email in emails.items():
su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role,
'password': PASSWORD}, operator=True)
su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role, 'password': PASSWORD,
**({'tiny_seller': sellers[0]} if role == 'vendedor' else {})},
operator=True)
listed = {u['email']: u for u in su.call('/operator/users', operator=True)['users']}
assert listed[emails['vendedor']]['tiny_seller'] == sellers[0], listed[emails['vendedor']]
assert listed[emails['gestao']]['tiny_seller'] is None, listed[emails['gestao']]
# The new profile creates through the users API and reads the table.
shipping = signed_in(emails['expedicao'])
seller = signed_in(emails['vendedor'])
@@ -175,6 +184,8 @@ def run():
made_quotes.append(UUID(order_venda['quote_id']))
assert order_venda['state'] == 'rec' and order_venda['origin'] == 'atendimento', order_venda
assert order_venda['snapshot']['with_order'] == 4321, order_venda['snapshot'].get('with_order')
assert order_venda['snapshot']['seller'] == {'id': 2001, 'name': 'Lais'}, order_venda['snapshot'].get('seller')
assert 'seller' not in order_interno['snapshot'], order_interno['snapshot'].get('seller')
payment = order_venda['payment']
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'faturado', 'paid'), payment
with db.connect() as c:

View File

@@ -8,10 +8,21 @@ extra. app/cart_pricing.price_items must return exactly the same list.
import unittest
from decimal import Decimal
from uuid import uuid4
from app import catalog
from app.cart_pricing import price_items, treatment_price
from app.cart_pricing import (designer_hours, needs_designer, price_items,
redesign_price, treatment_price)
from app.core import pricing
try:
from pydantic import ValidationError
from app.core.models import QuoteRequest
except ImportError:
# The validate job runs this file on the host, without the runtime image's
# dependencies; the runtime suites exercise the model there.
QuoteRequest = ValidationError = None
BASE = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990}
UV_BANDS = [{'from_metres': '5', 'unit_cents': 8000},
@@ -24,6 +35,7 @@ def catalog_now(bands=None, prices=None):
now = {mode: {'enabled': True, 'unit_cents': prices[mode],
'bands': bands.get(mode, [])} for mode in BASE}
now['tratamento'] = {'enabled': True, 'unit_cents': 1000, 'bands': []}
now['redesenho'] = {'enabled': True, 'unit_cents': 2990, 'bands': []}
return now
@@ -153,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
@@ -171,6 +185,67 @@ class CartPricingCharacterizationTest(unittest.TestCase):
self.assertEqual(treatment_price(items, [], offer), {})
self.assertEqual(treatment_price(items, True, {**offer, 'enabled': False}), {})
def test_redesenho_is_per_art_never_a_band(self):
# Front 1b: R$ 29,90 per art, and the basic batch band never applies.
offer = {'enabled': True, 'unit_cents': 2990,
'bands': [{'from_metres': '10', 'unit_cents': 690}]}
items = [item('file', '1', uid='u1'), item('file', '1', uid='u2')]
self.assertEqual(redesign_price(items, [[0, 0], [1, 0]], offer),
{'cents': 5980, 'hours': 48, 'arts': 2, 'unit_cents': 2990})
self.assertEqual(redesign_price(items, [], offer), {})
self.assertEqual(redesign_price(items, [[0, 0]], {**offer, 'enabled': False}), {})
self.assertEqual(redesign_price(items, [[0, 0]], {**offer, 'unit_cents': 0}), {})
def test_the_basic_band_counts_only_basic_arts(self):
offer = {'enabled': True, 'unit_cents': 990,
'bands': [{'from_metres': '10', 'unit_cents': 690}]}
items = [item('avulsa', '1', uid=f'u{index}') for index in range(10)]
basic = [[index, 0] for index in range(9)]
self.assertEqual(treatment_price(items, basic, offer),
{'cents': 8910, 'hours': 24, 'arts': 9, 'unit_cents': 990})
redesign = redesign_price(items, [[9, 0]], offer={**offer, 'unit_cents': 2990})
self.assertEqual(redesign['arts'], 1)
def test_designer_helpers_read_both_services(self):
self.assertEqual(designer_hours({}), 0)
self.assertEqual(designer_hours({'treatment': {'cents': 990}}), 24)
self.assertEqual(designer_hours({'redesign': {'cents': 2990}}), 48)
self.assertEqual(designer_hours({'treatment': {'cents': 990},
'redesign': {'cents': 2990}}), 48)
self.assertFalse(needs_designer({}))
self.assertTrue(needs_designer({'treatment': {'cents': 990}}))
self.assertTrue(needs_designer({'redesign': {'cents': 2990}}))
@unittest.skipUnless(QuoteRequest, 'pydantic is only in the runtime image')
def test_a_pair_cannot_be_basic_and_redesenho(self):
def quote(treatment=None, redesign=None, items=1):
entries = []
for _ in range(items):
uid = str(uuid4())
data = item('avulsa', '1', uid=uid)
data['production']['placements'] = [{
'source_index': 0, 'copy_index': 0, 'x_cm': 0, 'y_cm': 0,
'width_cm': 10, 'length_cm': 10, 'rotation_degrees': 0, 'mirrored': False}]
entries.append(data)
payload = {'request_key': str(uuid4()),
'customer': {'cnpj': '11222333000181', 'zap': '11999999999',
'mail': 'arte@example.test'},
'items': entries, 'freight': {'service': 'pickup'}}
if treatment is not None:
payload['treatment'] = treatment
if redesign is not None:
payload['redesign'] = redesign
return payload
QuoteRequest.model_validate(quote(treatment=[[0, 0]], redesign=[[1, 0]], items=2))
with self.assertRaises(ValidationError):
QuoteRequest.model_validate(quote(treatment=[[0, 0]], redesign=[[0, 0]]))
with self.assertRaises(ValidationError):
QuoteRequest.model_validate(quote(treatment=True, redesign=[[0, 0]]))
with self.assertRaises(ValidationError):
QuoteRequest.model_validate(quote(redesign=[[0, 0], [0, 0]]))
with self.assertRaises(ValidationError):
QuoteRequest.model_validate(quote(redesign=[[1, 0]]))
if __name__ == '__main__':
unittest.main()

109
tests/test_db_outage.py Normal file
View File

@@ -0,0 +1,109 @@
"""A short database outage during a redeploy: bounded retries, one report.
Run from the repository root: python3 -m unittest tests.test_db_outage -v.
The worker imports psycopg and boto3, so a host without the API image's
dependencies cannot import it; CI runs this in the api container.
"""
import unittest
from unittest import mock
import psycopg
from app import worker
from app.core import auth
class WorkerDatabaseOutageTest(unittest.TestCase):
class StopLoop(Exception):
pass
class Connection:
def __enter__(self):
return self
def __exit__(self, *exc_info):
return False
def execute(self, *args, **kwargs):
return self
def fetchone(self):
return None
def setUp(self):
worker.db_down_since = None
self.addCleanup(setattr, worker, 'db_down_since', None)
def test_one_error_and_one_info_with_growing_sleeps(self):
outage = psycopg.OperationalError('connection refused')
with mock.patch.object(worker, 'connect',
side_effect=[outage, outage, outage, self.Connection()]), \
mock.patch.object(worker, 'last_cleanup', worker.time.monotonic()), \
mock.patch.object(worker, 'cleanup'), \
mock.patch.object(worker, 'tiny_keepalive'), \
mock.patch.object(worker, 'reconcile_payments'), \
mock.patch.object(worker, 'resolve_names'), \
mock.patch.object(worker.mail, 'send_pending'), \
mock.patch.object(worker.time, 'sleep',
side_effect=[None, None, None, self.StopLoop]) as sleep, \
mock.patch.object(worker.logging, 'warning') as warning, \
mock.patch.object(worker.logging, 'info') as info, \
mock.patch.object(worker.logging, 'debug') as debug:
with self.assertRaises(self.StopLoop):
worker.loop()
# A warning, not an error: a restart is expected (Sentry DTF-API-8).
self.assertEqual(warning.call_count, 1)
self.assertIn('Database unavailable', warning.call_args[0][0])
self.assertEqual(info.call_count, 1)
self.assertIn('Database back after', info.call_args[0][0])
self.assertEqual(debug.call_count, 2)
self.assertEqual([call.args[0] for call in sleep.call_args_list[:3]],
[1, 2, 4])
class AuditPersistenceOutageTest(unittest.TestCase):
def setUp(self):
auth._persistence_error_at = None
self.addCleanup(setattr, auth, '_persistence_error_at', None)
def test_persistence_error_is_logged_at_most_once_per_minute(self):
logger = auth.logging.getLogger('dtf.security')
outage = psycopg.OperationalError('database is down')
with mock.patch.object(auth, 'connect', side_effect=outage), \
mock.patch.object(auth.time, 'monotonic',
side_effect=[100.0, 130.0, 161.0]), \
mock.patch.object(logger, 'error') as error, \
mock.patch.object(logger, 'warning') as warning:
auth.audit('first')
auth.audit('second')
auth.audit('third')
# A connection outage: the event lines and, once a minute, a warning.
self.assertEqual(error.call_count, 0)
self.assertEqual(warning.call_count, 5)
def test_any_other_persistence_failure_is_an_error(self):
logger = auth.logging.getLogger('dtf.security')
with mock.patch.object(auth, 'connect', side_effect=RuntimeError('bad table')), \
mock.patch.object(auth.time, 'monotonic', return_value=100.0), \
mock.patch.object(logger, 'error') as error, \
mock.patch.object(logger, 'warning'):
auth.audit('first')
self.assertEqual(error.call_count, 1)
class RequestDuringOutageTest(unittest.TestCase):
def test_a_request_gets_503_with_retry_after(self):
"""Sentry DTF-API-9: the board answered 500 while the database restarted."""
import asyncio
from app import app as module
request = mock.Mock(method='GET', url=mock.Mock(path='/api/operator/board'))
with mock.patch.object(module.logging, 'warning') as warning:
response = asyncio.run(module.database_unavailable(request, psycopg.OperationalError('down')))
self.assertEqual(response.status_code, 503)
self.assertEqual(response.headers['retry-after'], '5')
self.assertIn(b'reiniciando', response.body)
self.assertEqual(warning.call_count, 1)
if __name__ == '__main__':
unittest.main()

View File

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

67
tests/test_health.py Normal file
View File

@@ -0,0 +1,67 @@
"""The health check (Sentry DTF-API-B): an R2 blip is not the API down.
Runs in the API image: python -m unittest tests.test_health -v.
"""
import unittest
from contextlib import contextmanager
from unittest import mock
from fastapi import HTTPException
from app.api import health as module
@contextmanager
def database(up=True):
if not up:
raise RuntimeError('no database')
yield mock.MagicMock()
class HealthTests(unittest.TestCase):
def setUp(self):
module._storage.update(down_since=None, reported=False)
patches = [mock.patch.object(module.db, 'connect', database), mock.patch.object(module.time, 'sleep')]
for patch in patches:
patch.start()
self.addCleanup(patch.stop)
def check(self, storage_up, now=0):
storage = mock.MagicMock()
if not storage_up:
storage.health.side_effect = RuntimeError('R2 500')
with mock.patch.object(module, 'storage', storage), \
mock.patch.object(module.time, 'monotonic', return_value=now), \
mock.patch.object(module.logging, 'error') as error:
try:
return module.health(), error.call_count
except HTTPException as exc:
return exc.status_code, error.call_count
def test_a_storage_blip_is_reported_but_not_a_503(self):
answer, errors = self.check(storage_up=False, now=100)
self.assertEqual((answer['storage'], errors), ('unavailable', 0))
answer, _ = self.check(storage_up=True, now=150)
self.assertNotEqual(answer['storage'], 'unavailable')
def test_storage_down_for_five_minutes_is_a_503_reported_once(self):
self.check(storage_up=False, now=0)
self.assertEqual(self.check(storage_up=False, now=299)[0]['storage'], 'unavailable')
self.assertEqual(self.check(storage_up=False, now=300), (503, 1))
self.assertEqual(self.check(storage_up=False, now=400), (503, 0))
def test_one_retry_rides_out_a_single_failure(self):
storage = mock.MagicMock()
storage.health.side_effect = [RuntimeError('R2 500'), None]
with mock.patch.object(module, 'storage', storage):
self.assertTrue(module.storage_answers())
def test_the_database_down_is_a_503_at_once(self):
with mock.patch.object(module.db, 'connect', lambda: database(up=False)):
with self.assertRaises(HTTPException) as caught:
module.health()
self.assertEqual(caught.exception.status_code, 503)
if __name__ == '__main__':
unittest.main()

View File

@@ -3,7 +3,7 @@ import unittest
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from app.machine_stats import month_bounds, ratios
from app.machine_stats import month_bounds, pace, ratios
SAO_PAULO = ZoneInfo('America/Sao_Paulo')
@@ -74,5 +74,18 @@ class RatiosTest(unittest.TestCase):
self.assertIsNone(value['payback_months'])
class PaceTest(unittest.TestCase):
def test_seconds_in_imprimindo_give_no_pace(self):
# 16/11: an order moved through Imprimindo in seconds showed 110671,5 m/h.
self.assertIsNone(pace(1.01, 10 / 3600))
self.assertIsNone(pace(5, 0))
self.assertIsNone(pace(5, None))
def test_a_quarter_of_an_hour_gives_the_pace(self):
self.assertEqual(pace(5, 0.25), 20.0)
self.assertEqual(pace(1.5, 0.5), 3.0)
if __name__ == '__main__':
unittest.main()

View File

@@ -137,6 +137,11 @@ class MercadoPagoTests(unittest.TestCase):
self.mp.create('22222222-2222-3333-4444-555555555555', 1000, {'mail': 'a@example.test', 'cnpj': '52998224725'})
person = json.loads(self.requests[-1].content)
self.assertEqual(person['payer']['identification'], {'type': 'CPF', 'number': '52998224725'})
# A one-word name is both first and last name.
self.mp.create('33333333-2222-3333-4444-555555555555', 1000,
{'mail': 'a@example.test', 'cnpj': '52998224725', 'name': 'Kenia'})
self.assertEqual({k: v for k, v in json.loads(self.requests[-1].content)['payer'].items() if 'name' in k},
{'first_name': 'Kenia', 'last_name': 'Kenia'})
self.assertEqual((created['pix_qr_code'], created['status']), ('000201PIX', 'pending'))
# The code expires in 30 minutes, in the format Mercado Pago documents.
expires = datetime.fromisoformat(body['date_of_expiration'])
@@ -161,15 +166,30 @@ class MercadoPagoTests(unittest.TestCase):
{'type': 'card', 'token': 'tok_def', 'payment_method_id': 'visa'})
self.assertNotEqual(self.requests[-1].headers['x-idempotency-key'], first_key)
self.assertTrue(first_key.startswith('dtf-quote-q-card-'))
# 3-D Secure is asked of debit only; the cardholder is the payer.
# 3-D Secure is asked of debit only. The payer is a real document
# (Marcus, 2026-11-18): a placeholder from the card form (999...) gives
# way to the order's, with the order's name; the order's document is
# always kept in the metadata for finance.
self.assertNotIn('three_d_secure_mode', body)
self.mp.create('q', 1000, {'mail': 'a@example.test', 'cnpj': '11222333000181'},
self.mp.create('q', 1000, {'mail': 'a@example.test', 'cnpj': '11222333000181', 'name': 'Maria da Silva'},
{'type': 'card', 'token': 'tok_deb', 'payment_method_id': 'debmaster',
'payer_document_type': 'CPF', 'payer_document': '12345678909'})
'payer_document_type': 'CPF', 'payer_document': '99999999999'})
debit = json.loads(self.requests[-1].content)
self.assertEqual(debit['three_d_secure_mode'], 'optional')
self.assertEqual(debit['payer']['identification'], {'type': 'CPF', 'number': '12345678909'})
self.assertEqual(debit['payer'], {'email': 'a@example.test', 'first_name': 'Maria', 'last_name': 'da Silva',
'identification': {'type': 'CNPJ', 'number': '11222333000181'}})
self.assertEqual(debit['metadata'], {'documento_pedido': '11222333000181'})
self.assertEqual(body['payer']['identification'], {'type': 'CNPJ', 'number': '11222333000181'})
# An order from before the Site asked the name sends none.
self.assertNotIn('first_name', body['payer'])
# A valid document typed in the card form (someone else's card) is the
# payer, as the card token says; the order's stays in the metadata.
self.mp.create('q', 1000, {'mail': 'a@example.test', 'cnpj': '11222333000181', 'name': 'Maria da Silva'},
{'type': 'card', 'token': 'tok_other', 'payment_method_id': 'visa',
'payer_document_type': 'CPF', 'payer_document': '52998224725'})
other = json.loads(self.requests[-1].content)
self.assertEqual(other['payer']['identification'], {'type': 'CPF', 'number': '52998224725'})
self.assertEqual(other['metadata'], {'documento_pedido': '11222333000181'})
self.mp.create('q', 1000, {'mail': 'a@example.test', 'cnpj': '11222333000181'},
{'type': 'card', 'token': 'tok_iss', 'payment_method_id': 'master', 'issuer_id': '24'})
self.assertNotIn('issuer_id', json.loads(self.requests[-1].content))

29
tests/test_one_machine.py Normal file
View File

@@ -0,0 +1,29 @@
"""One order, one machine (Marcus, 2026-11-26): UV and textile never share an
order; basic and premium textile may.
Run from the repository root: python3 -m unittest tests.test_one_machine -v.
"""
import unittest
from app.core.models import ONE_MACHINE, Item, check_one_machine
from tests.test_sheet_trim import sheet_item
def items(*modes):
return [Item.model_validate(sheet_item(mode=mode)) for mode in modes]
class OneMachineTests(unittest.TestCase):
def test_uv_and_textile_never_share_an_order(self):
for modes in (('file', 'uvfile'), ('premium', 'uvfile'), ('uvfile', 'file', 'file')):
with self.assertRaises(ValueError) as caught:
check_one_machine(items(*modes))
self.assertEqual(str(caught.exception), ONE_MACHINE)
def test_one_line_passes(self):
check_one_machine(items('file', 'premium', 'file'))
check_one_machine(items('uvfile', 'uvfile'))
if __name__ == '__main__':
unittest.main()

View File

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

View File

@@ -145,6 +145,9 @@ class PrintFileTests(unittest.TestCase):
self.assertNotIn(b'ESPELHADO', footer_commands(footer(job, item([placement(0, 0, 20, 10)], [source(20, 10)], 10)), (100, 80)))
# The files start with the code the Kanban copies.
self.assertEqual(file_prefix(7, 1), 'DTF-7-item-2')
# Generated again: the version in the name (Marcus, 2026-11-27, #130).
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_jpeg_bytes_are_embedded_unchanged(self):
path = self.save(quadrants(), 'a.jpg', quality=90)

View File

@@ -115,6 +115,26 @@ class PngRenderTests(unittest.TestCase):
self.assertGreater(film.crop((0, 59, film.width, film.height)).getextrema()[3][1], 0)
self.assertEqual(detail['format'], 'png')
def test_a_trimmed_sheet_prints_only_what_is_between_its_empty_strips(self):
# The Site cut 1 cm of transparency above and below 0,5 cm of art
# (Marcus, 2026-11-18): the film is the art alone, read whole or in bands.
art = quadrants(118, 59, alpha=True)
sheet = Image.new('RGBA', (118, 118 + 59 + 118))
sheet.paste(art, (0, 118))
spec = item([placement(0, 0, 1, 0.5)], [{**source(1, 0.5), 'kind': 'sheet',
'trim_top_cm': 1, 'trim_bottom_cm': 1}], 0.5)
for stream in (False, True):
with mock.patch.object(printpng, 'STREAM_ABOVE_PIXELS', 0 if stream else 10 ** 9):
parts, detail = self.render(spec, [self.save(sheet, 'trimmed.png')])
film = Image.open(parts[0][0])
self.assertEqual(film.size, (px(57), 59), stream)
self.assertEqual(film.crop((0, 0, 118, 59)).tobytes(), art.tobytes(), stream)
self.assertEqual(detail['height_cm'], '0.5')
# A cut that does not match the file is refused, so the room prepares it.
spec['production']['sources'][0].update(trim_top_cm=2, trim_bottom_cm=2)
with self.assertRaises(printpng.Unsupported):
self.render(spec, [self.save(sheet, 'trimmed.png')])
def test_loose_art_is_turned_and_mirrored_like_the_site(self):
art = quadrants(80, 40, alpha=True)
# 80 x 40 px at 300 DPI is 6,773 x 3,387 cm; placed turned 90 degrees.
@@ -146,6 +166,40 @@ class PngRenderTests(unittest.TestCase):
self.assertEqual(second.convert('RGBA').getpixel((10, px(22) - px(21) + 5))[:3], RED)
self.assertEqual([p['name'] for p in detail['parts']], ['DTF-7-item-1-p1.png', 'DTF-7-item-1-p2.png'])
def sheet_spec(self, height_cm, film=10):
spec = item([placement(0, 0, film, height_cm)], [source(film, height_cm)], height_cm, film=film)
spec['production']['sources'][0]['kind'] = 'sheet'
return spec
def test_a_ready_sheet_is_cut_in_a_clear_band_not_through_the_art(self):
# Marcus, 2026-11-27, #136: one ready sheet is one piece to the layout;
# the cut finds the clear band in its pixels (30 to 31 cm) under 35 cm.
sheet = Image.new('RGBA', (px(10), px(40)), (220, 30, 60, 255))
sheet.paste((0, 0, 0, 0), (0, px(30), px(10), px(31)))
parts, detail = self.render(self.sheet_spec(40), [self.save(sheet, 'sheet.png')], part_cm=35)
cut = float(detail['parts'][0]['to_cm'])
self.assertTrue(30 < cut < 31, cut)
first = Image.open(parts[0][0]).convert('RGBA')
self.assertEqual(first.getpixel((10, first.height - 2))[3], 0) # ends in the clear band
def test_a_packed_sheet_is_cut_in_its_widest_clear_band(self):
# A sheet packed edge to edge (#83: 2 mm at most between rows): the
# widest clear band, here 2 mm between dots, still cuts no ink.
sheet = Image.new('RGBA', (px(10), px(40)), (220, 30, 60, 255))
sheet.paste((0, 0, 0, 0), (0, px(30), px(10), px(31)))
dots = [px(30 + tenth / 10) for tenth in range(1, 10, 2)] # a dot every 2 mm
for row in dots:
sheet.putpixel((px(5), row), (0, 0, 0, 255))
_, detail = self.render(self.sheet_spec(40), [self.save(sheet, 'sheet.png')], part_cm=35)
cut = px(float(detail['parts'][0]['to_cm']))
self.assertTrue(px(30) < cut < px(31) and cut not in dots, cut)
def test_without_any_clear_row_the_cut_takes_the_least_ink(self):
sheet = Image.new('RGBA', (px(10), px(40)), (220, 30, 60, 255))
sheet.paste((0, 0, 0, 0), (px(1), px(32), px(10), px(32) + 3)) # only a thin edge of ink there
_, detail = self.render(self.sheet_spec(40), [self.save(sheet, 'sheet.png')], part_cm=35)
self.assertTrue(px(32) <= px(float(detail['parts'][0]['to_cm'])) < px(32) + 3, detail['parts'][0])
def test_pieces_for_the_viewer_come_with_the_file(self):
art = quadrants(118, 59, alpha=True)
spec = item([placement(0, 0, 1, 0.5)], [source(1, 0.5)], 0.5)

53
tests/test_profiles.py Normal file
View File

@@ -0,0 +1,53 @@
"""Users with more than one profile (Marcus, 2026-11-26): what they may do is
the sum of their profiles, and an operator's machine rules apply only to the
moves that come from Operador.
Run from the repository root: python3 -m unittest tests.test_profiles -v.
"""
import unittest
from app.core.auth import has, machine_bound, machine_question, may_move, operator_only, roles_of
from tests.test_moves import moves
def user(*roles):
return {'role': roles[0], 'roles': list(roles)}
class ProfilesTest(unittest.TestCase):
def test_moves_are_the_sum_of_the_profiles(self):
self.assertEqual(moves(['operador', 'revisor']), moves('operador') | moves('revisor'))
# Gestão and Operador: the coordination's pulls back, and the operator's moves forward.
self.assertEqual(moves(['gestao', 'operador']), moves('gestao') | moves('operador'))
self.assertTrue(may_move(['gestao', 'operador'], 'tra', 'imp'))
self.assertFalse(may_move('gestao', 'tra', 'imp'))
def test_operador_and_revisor_release_what_they_printed(self):
# D-29 does not block a user with both profiles (Marcus, 2026-11-26).
self.assertTrue(may_move(['operador', 'revisor'], 'rev', 'fin'))
def test_the_machine_rules_follow_the_profile_that_allows_the_move(self):
both = user('operador', 'revisor')
self.assertTrue(machine_bound(both, 'tra', 'imp'))
self.assertTrue(machine_bound(both, 'imp', 'rev'))
self.assertFalse(machine_bound(both, 'rev', 'fin')) # as a Revisor, any machine
self.assertFalse(machine_bound(user('gestao', 'operador'), 'imp', 'cor'))
self.assertTrue(machine_bound(user('operador'), 'imp', 'rev'))
self.assertFalse(machine_bound(user('admin'), 'tra', 'imp'))
def test_capabilities_and_the_machine_question(self):
both = user('operador', 'revisor')
self.assertTrue(has(both, 'inspect') and has(both, 'print'))
self.assertTrue(operator_only(both, 'print'))
self.assertFalse(operator_only(user('gestao', 'operador'), 'print'))
self.assertEqual(machine_question(user('operador')), 'required')
self.assertEqual(machine_question(both), 'required')
self.assertEqual(machine_question(user('gestao', 'operador', 'revisor')), 'optional')
self.assertIsNone(machine_question(user('revisor')))
def test_a_row_from_before_the_list_has_its_one_profile(self):
self.assertEqual(roles_of({'role': 'designer', 'roles': []}), ('designer',))
if __name__ == '__main__':
unittest.main()

View File

@@ -38,5 +38,22 @@ class ProofCutTests(unittest.TestCase):
self.assertEqual(proof_cut(100, 15, None), [Decimal(0), Decimal(15)])
class RenderLimitTests(unittest.TestCase):
"""Order #20 (2026-11-12): a 23.6 m film ran past one 15 min limit."""
def test_the_limit_grows_with_the_parts(self):
from app.printjobs import RENDER_SECONDS, render_seconds
def film(height):
return {'production': {'height_cm': height, 'placements': [
{'y_cm': 0, 'length_cm': height, 'source_index': 0}]}}
self.assertEqual(render_seconds(film(800)), 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)
if __name__ == '__main__':
unittest.main()

78
tests/test_proof_parts.py Normal file
View File

@@ -0,0 +1,78 @@
"""Prova OK approves every part of a film in parts (#114, #128, #130): only
the first part became a final, and the others never reached the folders.
Run from the repository root: python3 -m unittest tests.test_proof_parts -v.
"""
import unittest
from app.proof import approve_parent
class Rows:
def __init__(self, rows):
self.rows = rows
def fetchone(self):
return self.rows[0] if self.rows else None
def fetchall(self):
return self.rows
class Database:
"""Just the reads and writes approve_parent makes."""
def __init__(self, parts, active):
self.parts, self.active, self.inserted, self.outbox = parts, active, [], []
def execute(self, sql, params=()):
text = ' '.join(sql.split())
if 'proof_result' in text:
return Rows([{'number': 131}])
if 'FROM dtf_local.print_files' in text:
return Rows([{'item_index': 0, 'upload_id': self.parts[0]}])
if 'FROM dtf_local.print_parts' in text:
return Rows([{'upload_id': u} for u in self.parts])
if text.startswith('SELECT upload_id FROM dtf_local.order_files'):
return Rows([{'upload_id': u} for u in self.active])
if text.startswith('INSERT INTO dtf_local.order_files'):
self.inserted.append(params[2])
if text.startswith('UPDATE dtf_local.orders SET state'):
return Rows([{'version': 2}])
if 'FROM dtf_local.outbox' in text:
return Rows([])
if text.startswith('INSERT INTO dtf_local.outbox'):
self.outbox.append((params[0], params[2].obj['event']))
return Rows([{'ok': 1}])
ORDER = {'id': 'o', 'number': 131, 'state': 'rec', 'cancelled_at': None, 'payment': {'provider': 'mercadopago'},
'snapshot': {'items': [{'mode': 'file'}]}}
class ProofPartsTests(unittest.TestCase):
def test_every_part_becomes_a_final(self):
db = Database(['p1', 'p2', 'p3'], set())
approve_parent(db, ORDER, 'Prumo')
self.assertEqual(db.inserted, ['p1', 'p2', 'p3'])
def test_the_missing_parts_join_a_first_part_already_approved(self):
db = Database(['p1', 'p2'], {'p1'})
approve_parent(db, ORDER, 'Prumo')
self.assertEqual(db.inserted, ['p2'])
def test_entering_the_queue_by_prova_ok_tells_tiny(self):
# Tiny's "Preparando envio", as for a card moved by hand: orders with
# a proof skipped it.
db = Database(['p1'], set())
self.assertTrue(approve_parent(db, ORDER, 'Prumo'))
self.assertEqual(db.outbox, [('o:production_started:tiny', 'production_started')])
def test_a_final_someone_prepared_stays(self):
db = Database(['p1', 'p2'], {'treated'})
approve_parent(db, ORDER, 'Prumo')
self.assertEqual(db.inserted, [])
if __name__ == '__main__':
unittest.main()

View File

@@ -1,4 +1,5 @@
"""A free proof is a 15 cm window around the measured fine stroke, not the top."""
"""A free proof is a 15 cm window around the measured fine stroke, not the top,
and samples of the colours that window lacks, up to 30 cm (Marcus, 2026-11-26)."""
import io
import tempfile
import unittest
@@ -28,38 +29,78 @@ def item(height_cm=30, fraction='0.75'):
}
RED, BLUE, GREEN = (220, 30, 60, 255), (30, 60, 220, 255), (40, 180, 70, 255)
def cm(value):
return round(value * PX_CM)
def picture(path):
"""The small picture the Site sends of a file: WebP within 480 x 720 px."""
with Image.open(path) as image:
image.thumbnail((480, 720))
out = io.BytesIO()
image.save(out, 'WEBP', quality=80)
return out.getvalue()
class ProofRenderTests(unittest.TestCase):
def _sheet(self, folder):
height = round(30 * PX_CM)
width = round(20 * PX_CM)
image = Image.new('RGBA', (width, height), (220, 30, 60, 255))
ImageDraw.Draw(image).rectangle((0, height // 2, width - 1, height - 1),
fill=(30, 60, 220, 255))
def _sheet(self, folder, bands, height_cm=30):
"""A 20 cm wide sheet painted in [(from_cm, colour)] bands."""
image = Image.new('RGBA', (cm(20), cm(height_cm)), bands[0][1])
draw = ImageDraw.Draw(image)
for start, colour in bands[1:]:
draw.rectangle((0, cm(start), cm(20) - 1, cm(height_cm) - 1), fill=colour)
path = Path(folder) / 'sheet.png'
image.save(path, 'PNG', dpi=(300, 300))
return str(path)
def test_the_window_follows_the_finest_stroke(self):
def proof(self, bands, height_cm=30, fraction='0.75'):
with tempfile.TemporaryDirectory() as source, tempfile.TemporaryDirectory() as out:
sheet = self._sheet(source)
parts, detail = render(item(), {0: (sheet, 'sheet.png')}, out, 'proof',
limit_cm=15, proof_fraction='0.75')
sheet = self._sheet(source, bands, height_cm)
parts, detail = render(item(height_cm, fraction), {0: (sheet, 'sheet.png')}, out, 'proof',
limit_cm=15, proof_fraction=fraction, pictures={0: picture(sheet)})
self.assertEqual(len(parts), 1)
self.assertEqual(detail['parts'][0]['from_cm'], '15')
with Image.open(parts[0][0]) as proof:
self.assertEqual(proof.width, round(20 * PX_CM))
self.assertLessEqual(abs(proof.height - round(15 * PX_CM)), 1)
# The bottom half is blue: the window covered 15 to 30 cm.
self.assertEqual(proof.getpixel((proof.width // 2, round(5 * PX_CM))), (30, 60, 220, 255))
with Image.open(parts[0][0]) as image:
return image.convert('RGBA'), detail
def test_the_top_is_still_the_default_without_a_measure(self):
def test_the_window_follows_the_finest_stroke_and_samples_the_rest(self):
# The stroke is in the blue half: its 15 cm window, then a 5 cm red
# sample from above, 1 cm of clear film between them.
image, detail = self.proof([(0, RED), (15, BLUE)])
self.assertEqual(detail['proof_windows'], [['0', '5'], ['15', '30']])
self.assertEqual(image.width, cm(20))
self.assertLessEqual(abs(image.height - cm(21)), 2)
self.assertEqual(image.getpixel((image.width // 2, cm(2))), RED)
self.assertEqual(image.getpixel((image.width // 2, cm(5.5)))[3], 0)
self.assertEqual(image.getpixel((image.width // 2, cm(10))), BLUE)
def test_the_top_is_still_the_window_without_a_measure(self):
image, detail = self.proof([(0, RED), (15, BLUE)], fraction=None)
self.assertEqual(detail['proof_windows'][0], ['0', '15'])
self.assertEqual(image.getpixel((image.width // 2, cm(5))), RED)
self.assertEqual(image.getpixel((image.width // 2, cm(18))), BLUE)
def test_without_pictures_the_proof_is_the_stroke_window(self):
with tempfile.TemporaryDirectory() as source, tempfile.TemporaryDirectory() as out:
sheet = self._sheet(source)
parts, detail = render(item(fraction=None), {0: (sheet, 'sheet.png')}, out, 'proof',
limit_cm=15)
self.assertEqual(detail['parts'][0]['from_cm'], '0')
with Image.open(parts[0][0]) as proof:
self.assertEqual(proof.getpixel((proof.width // 2, round(5 * PX_CM))), (220, 30, 60, 255))
sheet = self._sheet(source, [(0, RED), (15, BLUE)])
_, detail = render(item(), {0: (sheet, 'sheet.png')}, out, 'proof', limit_cm=15, proof_fraction='0.75')
self.assertEqual(detail['proof_windows'], [['15', '30']])
def test_one_colour_keeps_the_15_cm_proof(self):
image, detail = self.proof([(0, BLUE)])
self.assertEqual(detail['proof_windows'], [['15', '30']])
self.assertLessEqual(abs(image.height - cm(15)), 1)
def test_every_colour_within_30_cm(self):
# Red, blue and green in a 100 cm sheet, the stroke in the blue.
image, detail = self.proof([(0, RED), (30, BLUE), (60, GREEN)], height_cm=100, fraction='0.45')
windows = [(float(a), float(b)) for a, b in detail['proof_windows']]
self.assertEqual(len(windows), 3)
self.assertLessEqual(sum(b - a for a, b in windows) + 1 * (len(windows) - 1), 30)
colours = {image.getpixel((image.width // 2, y)) for y in range(0, image.height, cm(1))}
self.assertTrue({RED, BLUE, GREEN} <= colours, colours)
if __name__ == '__main__':

51
tests/test_reprint.py Normal file
View File

@@ -0,0 +1,51 @@
"""Reprinting some items (Marcus, 2026-11-26, #105): back in the queue after a
print, only the items whose final changed go to the machine again.
Run from the repository root: python3 -m unittest tests.test_reprint -v.
"""
import unittest
from decimal import Decimal
from app.hotfolder import reprint_default
from app.machine_log import film_metres
class ReprintTests(unittest.TestCase):
def test_only_the_item_with_a_new_final_goes_again(self):
finals = [(0, 'a'), (1, 'b-new'), (2, 'c')]
self.assertEqual(reprint_default(finals, {'a', 'b-old', 'c'}, 3), [1])
def test_never_printed_or_nothing_new_or_all_new_is_every_item(self):
finals = [(0, 'a'), (1, 'b')]
self.assertIsNone(reprint_default(finals, None, 2)) # never printed
self.assertIsNone(reprint_default(finals, {'a', 'b'}, 2)) # printed again as it was
self.assertIsNone(reprint_default(finals, {'x', 'y'}, 2)) # every file new
def test_a_film_in_parts_goes_again_when_one_part_is_new(self):
finals = [(0, 'p1'), (0, 'p2-new'), (1, 'q'), (2, 'r')]
self.assertEqual(reprint_default(finals, {'p1', 'p2', 'q', 'r'}, 3), [0])
def test_the_machine_counts_only_the_items_printed_again(self):
snapshot = {'items': [{'billed_metres': '2.0'}, {'billed_metres': '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__':
unittest.main()

85
tests/test_sheet_gap.py Normal file
View File

@@ -0,0 +1,85 @@
"""8 mm of clear film between the copies of a ready sheet (Marcus, 2026-11-26):
a new cart must carry it; a quote made before is still reviewed.
Run from the repository root: python3 -m unittest tests.test_sheet_gap -v.
"""
import unittest
from uuid import uuid4
from app.core.models import SHEET_GAP_CHANGED, Item, check_sheet_gaps
def sheet(copies=3, gap=0.8, mode='file'):
upload = str(uuid4())
width = 27 if mode == 'uvfile' else 57
length = 20
placements = [{'source_index': 0, 'copy_index': i, 'x_cm': 0, 'y_cm': round(i * (length + gap), 4),
'width_cm': width, 'length_cm': length, 'rotation_degrees': 0, 'mirrored': False}
for i in range(copies)]
height = round(copies * length + (copies - 1) * gap, 4)
return Item.model_validate({
'mode': mode, 'metres': str(height / 100), 'grade': 100, 'uploads': [upload],
'quality_status': 'ok', 'quality_acknowledged': False,
'production': {'version': 3, 'film_width_cm': width, 'height_cm': height,
'sources': [{'upload_id': upload, 'kind': 'sheet', 'width_cm': width,
'length_cm': length, 'copies': copies, 'measurement': 'file'}],
'placements': placements}})
class SheetGapTests(unittest.TestCase):
def test_copies_8_mm_apart_pass(self):
check_sheet_gaps([sheet()])
check_sheet_gaps([sheet(copies=1, gap=0)])
check_sheet_gaps([sheet(mode='uvfile')])
def test_copies_without_the_gap_are_refused_with_the_reason(self):
for gap in (0, 0.03, 0.5):
with self.assertRaises(ValueError) as caught:
check_sheet_gaps([sheet(gap=gap)])
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)."""
def test_the_count_is_kept_and_defaults_to_none(self):
item = sheet()
self.assertEqual(item.close_pieces, 0)
data = item.model_dump(mode='json')
self.assertEqual(Item.model_validate({**data, 'close_pieces': 14}).close_pieces, 14)
with self.assertRaises(ValueError):
Item.model_validate({**data, 'close_pieces': -1})
if __name__ == '__main__':
unittest.main()

89
tests/test_sheet_trim.py Normal file
View File

@@ -0,0 +1,89 @@
"""Empty strips cut from a ready sheet (Marcus, 2026-11-18): only a measured
finished sheet may carry them, and they never change what is placed.
Run from the repository root: python3 -m unittest tests.test_sheet_trim -v.
"""
import unittest
from uuid import uuid4
from pydantic import ValidationError
from app.core.models import Item
def sheet_item(mode='file', kind='sheet', measurement='file', top=10, bottom=40):
upload = str(uuid4())
width = 27 if mode in ('uvfile', 'uv') else 57
return {'mode': mode, 'metres': '4.6', 'grade': 100, 'uploads': [upload],
'quality_status': 'ok', 'quality_acknowledged': False,
'production': {'version': 3, 'film_width_cm': width, 'height_cm': '453.8',
'sources': [{'upload_id': upload, 'kind': kind, 'width_cm': width,
'length_cm': '453.8', 'copies': 1, 'measurement': measurement,
'trim_top_cm': top, 'trim_bottom_cm': bottom}],
'placements': [{'source_index': 0, 'copy_index': 0, 'x_cm': 0, 'y_cm': 0,
'width_cm': width, 'length_cm': '453.8',
'rotation_degrees': 0, 'mirrored': False}]}}
class SheetTrimTests(unittest.TestCase):
def test_a_measured_ready_sheet_carries_its_cut_strips(self):
item = Item.model_validate(sheet_item(mode='uvfile'))
source = item.production.sources[0]
self.assertEqual((source.trim_top_cm, source.trim_bottom_cm), (10, 40))
def test_no_strips_by_default(self):
data = sheet_item()
del data['production']['sources'][0]['trim_top_cm'], data['production']['sources'][0]['trim_bottom_cm']
source = Item.model_validate(data).production.sources[0]
self.assertEqual((source.trim_top_cm, source.trim_bottom_cm), (0, 0))
def test_only_a_measured_ready_sheet_is_trimmed(self):
with self.assertRaises(ValidationError):
Item.model_validate(sheet_item(measurement='customer'))
with self.assertRaises(ValidationError):
Item.model_validate(sheet_item(mode='avulsa', kind='artwork'))
with self.assertRaises(ValidationError):
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

@@ -31,5 +31,22 @@ class SpeedFiguresTests(unittest.TestCase):
self.assertTrue(all(row['average'] is None and row['samples'] == 0 for row in rows))
class ClientTimingsTests(unittest.TestCase):
def test_a_value_out_of_range_is_dropped_not_refused(self):
"""DTF-WEB-9: a cart left open for 6 h sent upload_ms 23556292 and
the customer could not pay."""
from app.core.models import ClientTimings
timings = ClientTimings.model_validate({'upload_ms': 23556292, 'analysis_ms': 5000,
'page_ms': -1, 'montage_ms': 1.5, 'upload_bytes': True})
self.assertEqual(timings.model_dump(), {'page_ms': None, 'upload_ms': None, 'upload_bytes': None,
'analysis_ms': 5000, 'montage_ms': None})
def test_an_unknown_field_is_still_refused(self):
from pydantic import ValidationError
from app.core.models import ClientTimings
with self.assertRaises(ValidationError):
ClientTimings.model_validate({'other_ms': 1})
if __name__ == '__main__':
unittest.main()

View File

@@ -51,6 +51,7 @@ class FakeTinyCase(unittest.TestCase):
self.calls = []
self.refuse_status = 0
self.refuse_tag = 0
self.refuse_contact = False
self.tags = {}
self.methods = {'77': {'id': 77, 'nome': 'Retirar pessoalmente', 'tipo': '6',
'formasFrete': [{'id': 771, 'nome': 'Retirar em loja'}]},
@@ -61,6 +62,9 @@ class FakeTinyCase(unittest.TestCase):
'formasFrete': [{'id': 801, 'nome': '.PACKAGE', 'codigo': '3'}]}}
self.products = {value: {'id': int(value), 'sku': f'DTF-{value}', 'descricao': f'Produto {value}',
'situacao': 'A', 'precos': {'preco': 14.9}} for value in PRODUCTS.values()}
# Ajuste Fino, per art: the SKU Marcus registered (2026-11-12).
self.products['106'] = {'id': 106, 'sku': 'DTFIMP.AJF.UN', 'descricao': 'Ajuste Fino',
'situacao': 'A', 'precos': {'preco': 6.9}}
def handler(request):
path = request.url.path.removeprefix('/public-api/v3')
@@ -70,6 +74,11 @@ class FakeTinyCase(unittest.TestCase):
if request.method == 'GET' and path == '/contatos':
cnpj = request.url.params.get('cpfCnpj')
return httpx.Response(200, json={'itens': [c for c in self.contacts if cnpj in (None, c['cpfCnpj'])]})
if request.method == 'GET' and path.startswith('/contatos/'):
wanted = int(path.rsplit('/', 1)[-1])
if self.refuse_contact:
return httpx.Response(self.refuse_contact, text='indisponível')
return httpx.Response(200, json=next(c for c in self.contacts if c['id'] == wanted))
if request.method == 'POST' and path == '/contatos':
contact = {**json.loads(request.content), 'id': 500 + len(self.contacts)}
self.contacts.append(contact)
@@ -145,6 +154,13 @@ class TinyTests(FakeTinyCase):
contact = contact_payload(PAID['order'])
self.assertEqual((contact['tipoPessoa'], contact['cpfCnpj'], contact['endereco']['uf']),
('J', '11.222.333/0001-81', 'SP'))
def test_only_a_montador_venda_names_its_seller(self):
# No seller: Tiny's channel sets it (Dropstar, 2026-10-23).
self.assertNotIn('vendedor', order_payload(PAID, 777, date(2026, 9, 24)))
# A Venda carries who assembled it (Marcus, 2026-11-17).
venda = {**PAID, 'order': {**PAID['order'], 'seller': {'id': 2001, 'name': 'Lais'}}}
self.assertEqual(order_payload(venda, 777, date(2026, 9, 24))['vendedor'], {'id': 2001})
pickup = order_payload({**PAID, 'order': {**PAID['order'], 'destination': None,
'freight': {'service': 'pickup', 'total_cents': 0}}}, 1)
self.assertNotIn('enderecoEntrega', pickup)
@@ -157,9 +173,11 @@ class TinyTests(FakeTinyCase):
treatment = {'order': {**base, 'treatment': {'cents': 990, 'hours': 24},
'total_cents': base['total_cents'] + 990},
**{k: v for k, v in PAID.items() if k != 'order'}}
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
pedido = order_payload(treatment, 777, date(2026, 9, 24))
self.assertIn({'produto': {'id': 105}, 'quantidade': 1, 'valorUnitario': 9.9,
# Ajuste Fino is sold by the SKU Marcus registered, found in the
# catalogue: the arts are its quantity and the band its unit price.
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
pedido = order_payload(treatment, 777, date(2026, 9, 24), product_id=self.tiny.product_id)
self.assertIn({'produto': {'id': 106}, 'quantidade': 1, 'valorUnitario': 9.9,
'infoAdicional': 'Ajuste Fino · 1 arte · +24 h'}, pedido['itens'])
self.assertNotEqual(pedido['dataPrevista'], order_payload(plain, 777, date(2026, 9, 24))['dataPrevista'])
# Per art: the quantity is the number of arts and the unit is the band price.
@@ -167,10 +185,48 @@ class TinyTests(FakeTinyCase):
'unit_cents': 690},
'total_cents': base['total_cents'] + 2070},
**{k: v for k, v in PAID.items() if k != 'order'}}
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
pedido = order_payload(per_art, 777, date(2026, 9, 24), product_id=self.tiny.product_id)
self.assertIn({'produto': {'id': 106}, 'quantidade': 3, 'valorUnitario': 6.9,
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}, pedido['itens'])
# The numeric id, when the client gives one, still wins.
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
pedido = order_payload(per_art, 777, date(2026, 9, 24))
self.assertIn({'produto': {'id': 105}, 'quantidade': 3, 'valorUnitario': 6.9,
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}, pedido['itens'])
# Without the numeric id, the catalogue lookup is required before sending.
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
with self.assertRaisesRegex(TinyError, 'TINY_SKU_TREATMENT'):
order_payload(treatment, 777, date(2026, 9, 24))
def test_faturado_boleto_carries_its_bank_account_on_the_installment(self):
boleto = {'TINY_RECEIPT_BOLETO': '919478947'}
with mock.patch.dict(os.environ, {**boleto, 'TINY_BOLETO_ACCOUNT': '977344551'}), \
mock.patch.dict(tiny_module.RECEIPT_METHODS, {'faturado': 919478947}):
pedido = order_payload({**PAID, 'payment': {'method': 'faturado'}}, 777, date(2026, 9, 24))
self.assertEqual(pedido['pagamento']['formaRecebimento'], {'id': 919478947})
# Every installment names the account: Tiny must not choose its preferred one.
self.assertEqual(pedido['pagamento']['parcelas'], [{
'dias': 0, 'data': '2026-09-24', 'valor': 84.72,
'formaRecebimento': {'id': 919478947}, 'meioPagamento': {'id': 977344551}}])
self.assertIn('faturado (Boleto)', pedido['observacoesInternas'])
# Without the account setting, no account is sent at all.
with mock.patch.dict(os.environ, {**boleto, 'TINY_BOLETO_ACCOUNT': ''}), \
mock.patch.dict(tiny_module.RECEIPT_METHODS, {'faturado': 919478947}):
pedido = order_payload({**PAID, 'payment': {'method': 'faturado'}}, 777, date(2026, 9, 24))
self.assertNotIn('meioPagamento', pedido['pagamento']['parcelas'][0])
# A pix order never gets the boleto account.
with mock.patch.dict(os.environ, {'TINY_BOLETO_ACCOUNT': '977344551'}):
pedido = order_payload({**PAID, 'payment': {'method': 'pix'}}, 777, date(2026, 9, 24))
self.assertNotIn('meioPagamento', pedido['pagamento']['parcelas'][0])
def test_the_check_lists_ajuste_fino_by_its_sku(self):
from app.tiny import check
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
self.assertEqual(check(orders=self.tiny)['Ajuste Fino'], 'ok')
self.products['106']['situacao'] = 'I'
self.tiny.skus.clear()
self.assertIn('DTFIMP.AJF.UN', check(orders=self.tiny)['Ajuste Fino'])
def test_second_delivery_finds_the_first_order(self):
first = self.tiny.deliver('k1', PAID)
@@ -190,6 +246,56 @@ class TinyTests(FakeTinyCase):
self.assertEqual(self.tiny.deliver('k1', PAID)['status'], 'already-created')
self.assertEqual(len(self.orders), 1)
def test_the_seller_of_an_existing_contact_goes_with_the_order(self):
# Marcus, 2026-11-26: the seller in the customer's registration
# (dados complementares); Tiny does not fill it on an API order.
self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477, 'nome': 'Lais'}})
self.tiny.deliver('k1', PAID)
self.assertEqual(self.orders[0]['vendedor'], {'id': 977231477})
def test_the_registration_seller_wins_over_who_assembled_a_venda(self):
self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477}})
venda = {**PAID, 'order': {**PAID['order'], 'seller': {'id': 2001, 'name': 'Kedma'}}}
self.tiny.deliver('k1', venda)
self.assertEqual(self.orders[0]['vendedor'], {'id': 977231477})
def test_without_a_registration_seller_the_assembler_or_none(self):
self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 0, 'nome': ''}})
venda = {**PAID, 'order': {**PAID['order'], 'seller': {'id': 2001, 'name': 'Kedma'}}}
self.tiny.deliver('k1', venda)
self.assertEqual(self.orders[0]['vendedor'], {'id': 2001})
self.tiny.deliver('k2', {**PAID, 'number': 43})
self.assertNotIn('vendedor', self.orders[1])
def test_a_refused_seller_reading_does_not_hold_the_order_and_reaches_sentry(self):
self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477}})
self.refuse_contact = 400
with self.assertLogs(level='ERROR') as logged:
self.assertEqual(self.tiny.deliver('k1', PAID)['status'], 'created')
self.assertNotIn('vendedor', self.orders[0])
self.assertIn('without one', logged.output[0])
def test_an_unavailable_tiny_retries_the_delivery_instead_of_dropping_the_seller(self):
# The seller cannot be set after the order is made (order 151250): a
# 5xx while reading it tries the whole delivery again.
from app.tiny import TinyUnavailable
self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477}})
self.refuse_contact = 503
with self.assertRaises(TinyUnavailable):
self.tiny.deliver('k1', PAID)
self.assertEqual(self.orders, [])
self.refuse_contact = None
self.tiny.deliver('k1', PAID)
self.assertEqual(self.orders[0]['vendedor'], {'id': 977231477})
def test_a_busy_tiny_retries_the_delivery_instead_of_dropping_the_seller(self):
from app.tiny import TinyRateLimit
self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477}})
self.refuse_contact = 429
with self.assertRaises(TinyRateLimit):
self.tiny.deliver('k1', PAID)
self.assertEqual(self.orders, [])
def test_a_contact_typed_without_punctuation_is_found_too(self):
self.contacts.append({'id': 322, 'cpfCnpj': '11222333000181'})
self.tiny.deliver('k1', PAID)
@@ -231,7 +337,7 @@ class TinyTests(FakeTinyCase):
from app.tiny import check
results = check(auth=FakeAuth(), transport=httpx.MockTransport(self.handler))
self.assertEqual(set(results.values()), {'ok'})
self.assertEqual(len(results), 8)
self.assertEqual(len(results), 9)
self.assertTrue(all(method == 'GET' for method, _ in self.calls))
self.products['103']['situacao'] = 'I'
with mock.patch.dict(os.environ, {'TINY_PRODUCT_UV_AVULSA': ''}):
@@ -405,13 +511,14 @@ class TinyStatusTests(FakeTinyCase):
1, thursday, shipping=self.tiny.shipping)
self.assertEqual(pix['pagamento']['formaRecebimento'], {'id': RECEIPT_METHODS['pix']})
self.assertEqual(pix['pagamento']['categoria'], {'id': CATEGORY})
# Dinheiro and the customer's credit (CORREÇÃO DTF), Marcus's ids of 2026-10-27.
self.assertEqual((RECEIPT_METHODS['cash'], RECEIPT_METHODS['credit']), (919478944, 977493654))
# Dinheiro (Marcus, 2026-10-27) and the customer's credit, CREDITO
# PRE-PAGO (Marcus, 2026-11-18; no longer CORREÇÃO DTF).
self.assertEqual((RECEIPT_METHODS['cash'], RECEIPT_METHODS['credit']), (919478944, 987762591))
# A Dropflow order goes in DTF DROPFLOW, not DTF SITE (D-21).
batch = order_payload({**PAID, 'origin': 'dropflow', 'payment': {'method': 'credit', 'outside': True}},
1, thursday, shipping=self.tiny.shipping)
self.assertEqual(batch['pagamento']['categoria'], {'id': 987032506})
self.assertEqual(batch['pagamento']['formaRecebimento'], {'id': 977493654})
self.assertEqual(batch['pagamento']['formaRecebimento'], {'id': 987762591})
self.assertTrue(batch['observacoesInternas'].startswith('Dropflow DTF · pago fora do site (crédito do cliente) · '))
def test_the_order_is_tagged_kanbandtf_once(self):
@@ -424,6 +531,18 @@ class TinyStatusTests(FakeTinyCase):
self.assertEqual(len(self.orders), 1)
self.assertEqual(self.tags[tiny_id], [{'descricao': 'SITE DTF'}])
def test_customer_credit_also_carries_the_credito_pre_pago_marcador(self):
credit = {**PAID, 'payment': {'method': 'credit', 'outside': True}}
first = self.tiny.deliver('k1', credit)
self.assertEqual(first['marcador'], 'SITE DTF, CREDITO PRE-PAGO')
tiny_id = self.orders[0]['id']
self.assertEqual(self.orders[0]['pagamento']['formaRecebimento'], {'id': 987762591})
self.assertEqual(self.tags[tiny_id], [{'descricao': 'SITE DTF'}, {'descricao': 'CREDITO PRE-PAGO'}])
# A retry adds only what is missing.
self.tags[tiny_id] = [{'descricao': 'SITE DTF'}]
self.tiny.deliver('k1', credit)
self.assertEqual(self.tags[tiny_id], [{'descricao': 'SITE DTF'}, {'descricao': 'CREDITO PRE-PAGO'}])
def test_a_failed_tag_is_retried_without_a_second_order(self):
self.refuse_tag = 1
with self.assertRaises(TinyError):
@@ -602,6 +721,7 @@ class TinyProbeTests(FakeTinyCase):
code, text = self.probe('conferir')
self.assertEqual(code, 0)
self.assertIn('TINY_PRODUCT_UV_AVULSA (DTF UV 27 cm · artes avulsas): ok DTF-104', text)
self.assertIn('TINY_SKU_TREATMENT (Ajuste Fino): ok DTFIMP.AJF.UN', text)
self.assertIn('TINY_FORMA_ENVIO_RETIRADA (retirada): ok Retirar pessoalmente', text)
code, text = self.probe('formas-envio')
self.assertIn('77\t6\tRetirar pessoalmente', text)
@@ -815,14 +935,14 @@ class DefaultSkuTests(unittest.TestCase):
class TreatmentSettingTests(unittest.TestCase):
"""A paid treatment needs its own Tiny product, asked with the rest."""
"""Ajuste Fino is sold by its SKU, so no product id is required any more."""
def test_the_treatment_product_is_required_only_when_it_is_paid(self):
def test_the_treatment_id_is_never_required(self):
from app.tiny import required_settings
with mock.patch.dict(os.environ, {'TREATMENT_CENTS': '0'}):
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
self.assertNotIn('TINY_PRODUCT_TREATMENT', required_settings())
with mock.patch.dict(os.environ, {'TINY_SKU_TREATMENT': 'DTFIMP.AJF.LOTE'}):
self.assertNotIn('TINY_PRODUCT_TREATMENT', required_settings())
with mock.patch.dict(os.environ, {'TREATMENT_CENTS': '5000'}):
self.assertIn('TINY_PRODUCT_TREATMENT', required_settings())
if __name__ == '__main__':

View File

@@ -23,5 +23,59 @@ class WorkerDrainTest(unittest.TestCase):
self.assertEqual(tick.call_count, 50)
class RefusedDeliveryTest(unittest.TestCase):
"""A delivery the provider refuses reaches Sentry (logging.error) on its
first failure and every tenth after (#42, 2026-11-18)."""
def tick_with(self, attempts, refusal=None):
job = {'id': 1, 'provider': 'tiny', 'event_key': 'o:paid:tiny', 'payload': {}, 'attempts': attempts}
conn = mock.MagicMock()
conn.execute.return_value.fetchone.return_value = job
connect = mock.MagicMock()
connect.return_value.__enter__.return_value = conn
refusing = mock.MagicMock()
refusing.deliver.side_effect = refusal or RuntimeError('Forma de recebimento não está habilitada')
with mock.patch.object(worker, 'connect', connect), \
mock.patch.dict(worker.adapters, {'tiny': refusing}), \
mock.patch.object(worker.logging, 'error') as error:
self.assertTrue(worker.tick())
return error
def test_first_and_every_tenth_failure_are_reported(self):
self.assertEqual(self.tick_with(0).call_count, 1)
self.assertEqual(self.tick_with(9).call_count, 1)
self.assertEqual(self.tick_with(4).call_count, 0)
def test_a_rate_limit_is_reported_only_when_it_repeats(self):
from app.tiny import TinyRateLimit
limit = TinyRateLimit('Tiny rate limit reached; the outbox will retry')
self.assertEqual(self.tick_with(0, limit).call_count, 0)
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()

Some files were not shown because too many files have changed in this diff Show More