Compare commits

...

200 Commits

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:19:27 -03:00
Cauê Faleiros
ba85168c09 fix: parts of 10 m are the code's default too, not only the stack's
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 7m58s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m21s
A stack without PRINT_PART_CM (the local one and CI) cut films in 15 m parts,
4,8 GB decoded, which FlexiPRINT refuses (Marcus, 2026-11-18). The comments
that still said 15 m now say a part.

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:48:34 -03:00
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
Cauê Faleiros
5ca6792221 Merge Sentry bugs of 12/11: 96 DPI, pending uploads, error grouping
All checks were successful
Build and deploy / Validate source (push) Successful in 1m53s
Build and deploy / Integration suite on a real stack (push) Successful in 8m3s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m49s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 10:23:40 -03:00
Cauê Faleiros
1a756a0beb Merge branch 'bugs-1112-web' into integration 2026-11-12 10:09:20 -03:00
Cauê Faleiros
6896e6a161 fix: one Sentry issue per kind of API error; the expected 410 of a resumed upload is silent (Sentry 12/11)
Every failed API call landed in one issue titled Object.apiError; each now
has its own fingerprint and title from status, path and message, with ids
and file names normalized. The 410 of a recovered cart's expired upload
was already handled (the file goes up again from the stored copy); the
probe no longer reports it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 10:09:20 -03:00
Cauê Faleiros
31776ca353 fix: 96 DPI is accepted as the Site shows it; big carts upload 4 at a time (Sentry 12/11)
The server compared the raw lowest resolution (95,6) with 96 but printed
it rounded, refusing '96 DPI abaixo do mínimo de 96'; it now decides on the
same rounded value the Site shows. A big cart started every upload at once
and hit the limit of 10 pending uploads (429): the limit is 30, that
refusal carries Retry-After so the Site retries by itself, and the Site
runs at most 4 uploads at a time.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 09:38:51 -03:00
Cauê Faleiros
d3918e83dc Merge Critical Corrections plan 007d: Pagamentos and Integrações tabs in their own file
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 7m12s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m32s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 17:26:19 -03:00
Cauê Faleiros
c0905ac28d Merge branch 'main' into fix-front-payments 2026-11-11 16:59:23 -03:00
Cauê Faleiros
c9a7931eed Merge fix: a cart item takes up to 200 files (Sentry DTF-WEB-1)
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 7m25s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m24s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 16:59:19 -03:00
Cauê Faleiros
aae8a8d49a refactor: the Pagamentos and Integrações tabs in web/kanban-integrations.js
A pure move of kanban.js's Payments and integrations section,
byte-identical, loaded after kanban-users.js (Critical Corrections 7,
fourth step). The browser test opens both tabs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 16:45:22 -03:00
Cauê Faleiros
d85e505097 Merge branch 'main' into bug-66 2026-11-11 16:43:33 -03:00
Cauê Faleiros
ab3ac65b69 fix: a cart item takes up to 200 files (Sentry DTF-WEB-1, Dropstar's 66-sheet test)
One item was capped at 20 files, so a real 66-sheet ready-sheet cart was
refused with the generic 'Confira os dados'. The cap is now 200 files per
item; above it the Site and the server say 'Este item tem mais de 200
arquivos. Divida em dois itens.'

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 16:43:32 -03:00
Cauê Faleiros
139f5ad67a Merge Critical Corrections plans 007b and 007c: Cotações and Usuários tabs in their own files
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 5m58s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m25s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 16:39:06 -03:00
Cauê Faleiros
2791f550c2 Merge branch 'main' into integration 2026-11-11 16:20:32 -03:00
Cauê Faleiros
26ed5cecef Merge Critical Corrections plan 008: PDF resolution at the scan; Sentry release
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 7m40s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m30s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 16:20:25 -03:00
Cauê Faleiros
8d9a59b210 Merge branch 'fix-front-users' into integration
# Conflicts:
#	tests/browser_test.mjs
#	web/kanban.html
#	web/kanban.js
2026-11-11 16:08:42 -03:00
Cauê Faleiros
77c04633e2 refactor: the Usuários tab, machines and machine sheet in web/kanban-users.js
A pure move of kanban.js's Machines and users section (with the account
menu, theme and filter wiring that sat inside it), byte-identical, loaded
right after kanban-numbers.js (Critical Corrections 7, third step). The
browser test opens Usuários so a missing name fails it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 16:08:14 -03:00
Cauê Faleiros
fb3a5003b8 refactor: the Cotações tab in web/kanban-quotes.js
A pure move of kanban.js's Quotes section, byte-identical, loaded right
after kanban-numbers.js (Critical Corrections 7, second step). The browser
test opens Cotações so a missing name fails it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 16:08:05 -03:00
Cauê Faleiros
55419d8364 feat: each error in Sentry names the commit it came from
The API image keeps the commit it was built from (RELEASE, from VCS_REF);
the API, the worker and the browser report it as the Sentry release
unless the stack sets IMAGE_TAG.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 15:59:27 -03:00
Cauê Faleiros
f2fa2b7748 Merge main into fix-pdf-check
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 15:58:09 -03:00
Cauê Faleiros
a747c01ec3 Merge Marcus's upload bugs of 11/11 (B1 to B4)
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 6m19s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m33s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 15:15:03 -03:00
Cauê Faleiros
1b299827ea Merge main into bugs-uploads
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

# Conflicts:
#	web/checkout.js
2026-11-11 15:03:53 -03:00
Cauê Faleiros
b980e1849c Merge Sentry: API, worker, Site and Kanban (off until the DSNs are set)
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 6m3s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m30s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 15:02:58 -03:00
Cauê Faleiros
d840d2741f Merge main into bugs-uploads
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 14:49:04 -03:00
Cauê Faleiros
7a24c66997 fix: large carts upload all their files (Marcus's bugs of 11/11, B1 to B4)
B1: an upload start was limited to 60 per 15 minutes per session, so a
66-file cart failed with 'Muitas tentativas'; now 1000 per session and
3000 per source, and the Site waits Retry-After and retries quietly.
B2: a failed file shows its error and 'Tentar de novo' on its own card, and
payment stays blocked with 'Falta enviar N arquivos'. B3: after signing in
again, an upload id the new session does not own (403) is dropped and the
file starts again. B4: the quote is never created before every file is
sent, and an untranslatable 422 is logged for Sentry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 14:49:04 -03:00
Cauê Faleiros
61548fd6b2 Merge main into sentry
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 14:48:01 -03:00
Cauê Faleiros
457ed4cbdf feat: Sentry in the API, the worker, the Site and the Kanban (off until the DSNs are set)
app/observability.py starts sentry-sdk for the API and the worker when
SENTRY_DSN_API is set, with send_default_pii off and a scrub that strips
cookies, tokens, bodies, CPF/CNPJ and e-mails. The browser loads the
official Sentry bundle from our own origin (web/vendor, provenance in its
README) and starts with SENTRY_DSN_WEB from /api/session or
/api/operator/me; every failed API answer the customer or the team gets is
reported with its path, status and message, never the request body. The
CSP allows Blyzer's Sentry ingest host.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 14:48:01 -03:00
Cauê Faleiros
d129a5164e Merge Ajuste Fino: priced per art, offered under the Prumo warnings
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 6m58s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m38s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 14:46:42 -03:00
Cauê Faleiros
49e5ff2081 Merge front 7a.4: montador Venda with shipping
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 14:46:42 -03:00
Cauê Faleiros
dedcbb6aad feat: Ajuste Fino priced per art, with the offer under each Prumo warning (Marcus 10/11, point 1)
The designer treatment becomes Ajuste Fino, priced per art with a batch
band set in the Site tab (e.g. R$ 9,90, from 10 arts R$ 6,90). Under each
art the Prumo warns about, the Site offers 'Quer que um designer resolva?
Ajuste Fino'; the cart keeps 'Ajuste Fino em todas as artes'. The server
counts the chosen arts, Tiny gets the line with that quantity, the card
shows 'Ajuste Fino · N artes'. Old carts asking the treatment for the
whole order keep working.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 14:21:14 -03:00
Cauê Faleiros
b4b34ab3fb feat: montador Venda with shipping at the Site's freight (front 7a.4)
A Venda can now ship: CEP lookup, the address, and the Site's freight
options for the packed metres; the server quotes the freight again at
approval, adds it to the total and keeps the destination, so Tiny gets the
freight and carrier like a Site order.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 14:21:13 -03:00
Cauê Faleiros
07515abbd8 Merge front 10: the 10x15 label at Finalizado
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 5m35s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m7s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 11:48:40 -03:00
Cauê Faleiros
9fd90f33d6 Merge main into label
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 11:32:27 -03:00
Cauê Faleiros
223bd61798 feat: the 10x15 label at Finalizado (Marcus 10/11, point 10)
When an order reaches Finalizado, the Kanban on the computer that opted in
(Integrações > Etiqueta 10x15) prints a 10x15 label rendered by the server:
the Tiny order number in large type (DTF-<n> when there is none), customer,
DTF · N folhas · X m, the delivery line, date and time, the Revisor and a
QR with the number. One automatic print per order (label_prints, claimed
once); Revisor, Expedição, Gestão and the administrators can reprint.
Chrome with --kiosk-printing prints without the dialog.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 11:32:27 -03:00
Cauê Faleiros
71980884a9 chore: TINY_RECEIPT_BOLETO in the production stack and its example
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 5m53s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m12s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 11:18:59 -03:00
Cauê Faleiros
b69e3c1f53 Merge front 7a.3: montador Interno and Venda, Tiny customers, brand per stamp
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 11:18:42 -03:00
Cauê Faleiros
e657551e66 fix: the Premium SKUs are the DTFIMP.TXP family
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 5m26s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m52s
Marcus, 2026-11-11: DTFIMP.TXP.100CM per metre and DTFIMP.TXP.0010CM to
0090CM per 10 cm, like the Têxtil family, not a single DTFP.TX.100CM.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 11:08:51 -03:00
Cauê Faleiros
c38a89f021 Merge main into montador-v2
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

# Conflicts:
#	web/kanban.js
2026-11-11 11:05:57 -03:00
Cauê Faleiros
d044da1a5e Merge front 3: Premium switched off; default machine minimums
Some checks failed
Build and deploy / Validate source (push) Successful in 1m42s
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-11 11:05:32 -03:00
Cauê Faleiros
52ed978e39 test: the Tiny check and probe know the Premium product
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 11:05:32 -03:00
Cauê Faleiros
b5a51137fb feat: montador Interno and Venda, Tiny customers, brand per stamp (front 7a.3, Marcus 10/11)
Interno: the Expedição assembles the marketplace's own sales on the fixed
internal customer Gestão fills in once; no Tiny order, no paid e-mail,
marked interno, it stays in house. Venda: a Vendedor or Gestão picks the
customer from the Tiny base and the order goes to Tiny like an approved
quote, faturado (Boleto from TINY_RECEIPT_BOLETO when set), pickup or
'junto com o pedido de roupa nº X'. Números counts both at table price,
apart from cash (and the average ticket over cash orders only). Each stamp
can carry a brand and a public flag for the future catalogue.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 11:01:44 -03:00
Cauê Faleiros
a9a4b61d99 feat: Premium built and switched off; default machine minimums (front 3, Marcus 10/11)
Premium (8 passadas, R$ 39,90/m, SKU DTFP.TX.100CM) is a fifth textile
ready-sheet product: priced on the server and the Site, a hidden fifth card,
a PREMIUM hot-folder class, its Tiny SKU, and a products row created
disabled by a migration until Dropstar says 'testado'. A machine with no
typed minimum now alerts at Dropstar's fixed minimums: 1 roll of film, 1 L
of each ink, 5 kg of powder.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 10:52:08 -03:00
Cauê Faleiros
9952495c4e Merge branch 'main' into fix-pdf-check 2026-11-10 11:22:44 -03:00
Cauê Faleiros
e6197d6e40 Merge Critical Corrections plan 007a: the Números tab in its own 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 6m9s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m31s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-10 11:22:03 -03:00
Cauê Faleiros
29b79db806 fix: a PDF's resolution is worked out at the scan, not at checkout
create_quote downloaded every PDF sheet (up to 150 MB) and parsed it inside
the customer's request, behind nginx's 30 s. The worker's scan already reads
every upload before the Site lets the customer continue, so it now stores
the PDF's DPI on the upload (uploads.pdf_checked, pdf_dpi) and the checkout
reads the number. An upload scanned before this, or whose work-out failed,
is read at checkout as before (Critical Corrections 2, step 2).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-10 10:47:08 -03:00
Cauê Faleiros
09ff22cde5 refactor: the Números tab in web/kanban-numbers.js
A pure move of kanban.js's Numbers and Máquinas, mês a mês sections,
byte-identical, loaded right after kanban.js like the Site tab. Loading
now waits for DOMContentLoaded: load() could run while the parser waited
for a later tab's script (Critical Corrections 7, first step).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-10 10:46:24 -03:00
Cauê Faleiros
17463c0298 Merge Critical Corrections plan 005: the browser test owns its machine
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 5m30s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m12s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-10 10:20:17 -03:00
Cauê Faleiros
512a134e3e Merge branch 'main' into fix-tests 2026-11-10 10:08:00 -03:00
Cauê Faleiros
494356a211 test: the browser test makes and deletes its own textile machine
It waited for whatever active textile machine earlier suites left, so on a
fresh database, or run on its own, it timed out at 'a textile machine', and
it could pick a machine that was full. It now creates one right after
signing in to the Kanban, uses it for the pull and deletes it at the end.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-10 10:08:00 -03:00
Cauê Faleiros
0dd00f626c Merge Critical Corrections plan 006: database connection pool behind DB_POOL
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 6m18s
Build and deploy / Secret scan and release gate (push) Successful in 13s
Build and deploy / Publish images (push) Successful in 1m34s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-10 10:07:46 -03:00
Cauê Faleiros
5b7e95ad86 feat: a database connection pool behind DB_POOL (off in production)
Every db.connect() opened a new Postgres connection; with DB_POOL=on each
process keeps a psycopg_pool pool (DB_POOL_SIZE, default 20, 10 s
acquisition timeout, dropped connections replaced) with the same
commit/rollback contract. Production stays off until switched in Portainer;
the local stack and CI run with it on. Two nested acquisitions that ran on
every board load and in audits now reuse the caller's connection.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 17:57:42 -03:00
Cauê Faleiros
085c2d0009 Merge Critical Corrections plan 003: one pricing module
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 6m14s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m5s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 17:37:49 -03:00
Cauê Faleiros
4d8f1aeb69 Merge main into fix-pricing
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 17:24:24 -03:00
Cauê Faleiros
81c8cfc520 Merge Critical Corrections plan 004: operator router split by area
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 6m13s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m15s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 17:24:21 -03:00
Cauê Faleiros
31b44a4fac refactor: one pricing module for the Site's check and the approval
app/cart_pricing.py prices a cart once for every caller: the catalog read
once, a pure price_items (base price, manual extra, splits, bands) pinned
against today's arithmetic by a 16-cart characterization test, then the
grade rules, the coupon and the treatment. create_quote and approve call
it instead of their two drifting copies; the Site's pre-check now counts
the manual-file extra like the approval does.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 17:12:49 -03:00
Cauê Faleiros
f5df5b96e4 refactor: app/api/operator.py split by area into a package
A pure move: the 48 Kanban routes, their code and comments are unchanged,
grouped in session, board, quotes, orders, rework, integrations, stats
and files, with shared helpers in common. The fast CI check now compiles
the package's files too (app/**/*.py does not reach a third level without
globstar).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 17:11:19 -03:00
Cauê Faleiros
a6e4d4cb08 Merge front 8.5: configurable art grade rules, off by default
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 6m14s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m5s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 17:00:36 -03:00
Cauê Faleiros
d85aa10fdd Merge main into front-8
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

# Conflicts:
#	.gitea/workflows/deploy.yml
2026-11-09 16:47:28 -03:00
Cauê Faleiros
122a72c542 Merge Critical Corrections plan 002: two API processes, worker drains its queue
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 6m11s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 59s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 16:46:57 -03:00
Cauê Faleiros
c383a4c93b Merge Critical Corrections plan 001: rollback-safe schema and migration files
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 16:46:57 -03:00
Cauê Faleiros
74ac2c978b fix: two API processes by default and the worker drains its queue
The API ran as one uvicorn process, so a slow 150 MB PDF check at checkout
held every other request; WEB_CONCURRENCY now comes from API_WORKERS
(default 2, 1 restores one process) and the api /tmp grows to 512 MiB for
two checks at once. The worker delivered one outbox job per second; it now
drains up to 50 per pass before its periodic tasks.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 16:24:07 -03:00
Cauê Faleiros
272755d2bc feat: the art grade becomes configurable, off by default (front 8.5)
Gestão sets in the Site tab below which grade the designer is warned and
below which the designer treatment is required (only while it is offered).
The decision is stored with the approved quote, so a later change never
rewrites old orders; the card shows 'Nota N: conferir a arte', the Site
forces the treatment box with the reason. With no rule nothing changes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 16:13:30 -03:00
Cauê Faleiros
6b7ef1c4c8 fix: a rollback never stops the database from starting; schema changes are migration files
schema.sql dropped and re-added three CHECK constraints on every start, so
an older image narrowed the lists and failed on rows written by a newer one
(an Expedição user, for example). They are now created only when missing,
and app/migrate.py applies timestamped files from app/migrations/ once each,
recording them in dtf_local.migrations; an older image skips names it does
not know. The first migration sets today's full lists. A CI step rehearses
the rollback on the real database inside a rolled-back transaction.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 16:11:30 -03:00
Cauê Faleiros
63af984e83 Merge front 7a: the montador in the Kanban
All checks were successful
Build and deploy / Integration suite on a real stack (push) Successful in 6m6s
Build and deploy / Validate source (push) Successful in 7s
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-09 16:00:13 -03:00
Cauê Faleiros
89be0a045b test: the montador item's copies sit in one row inside the film
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 16:00:13 -03:00
Cauê Faleiros
f74a6f4fe1 fix: the stamp sizes save again (cursor executemany)
7a.2b brought back the connection-level executemany psycopg does not have.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 15:53:26 -03:00
Cauê Faleiros
31dbd0b062 Merge main into front-7a
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

# Conflicts:
#	.gitea/workflows/deploy.yml
2026-11-09 15:40:55 -03:00
Cauê Faleiros
2c80de0c0a feat: Montar creates the invoiced order card (front 7a.2b)
The montador sends each stamp to storage, splits the list into items of
at most 20 sources and 4000 copies, packs each one with the Site's engine
and creates the order in Arte recebida: typed customer, pickup, the Site's
table price, payment 'faturado', origin dropflow for Expedição and
atendimento otherwise. Until Dropstar decides, these orders do not go to
Tiny and the customer gets no paid e-mail. Vendedor and Expedição may now
upload through the operator upload routes (can_any).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 15:27:04 -03:00
Cauê Faleiros
8993eb25db Merge branch 'main' into front-7a
# Conflicts:
#	app/schema.sql
2026-11-09 15:10:55 -03:00
Cauê Faleiros
04761e63e3 feat: the Site's packing engine shared with the montador's real layout (front 7a.2a)
The packing engine moves verbatim from web/site-packing.js to
web/packing.js, loaded by the Site and the Kanban. Montar folha packs the
list with it after every change and draws the sheet, showing the real
length instead of the estimate.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 14:25:15 -03:00
Cauê Faleiros
7a5116ab19 Merge main into front-7a
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

# Conflicts:
#	.gitea/workflows/deploy.yml
#	app/app.py
#	app/schema.sql
#	web/kanban.html
#	web/kanban.js
2026-11-09 14:14:25 -03:00
Cauê Faleiros
e9db9dec06 feat: Expedição profile, stamp sizes and the Montar folha screen (front 7a.1)
The new Expedição profile and the seller may assemble sheets (capability
assemble). Gestão edits the size table (letter and width). The Montar tab
reads Estampas/<code>-<size>.png or <code>.png from the orders folder,
checks the resolution with the Site's 96/200 DPI ruler, merges repeated
lines and estimates the metres. Montar itself is slice 2.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 13:34:43 -03:00
180 changed files with 16427 additions and 6654 deletions

View File

@@ -58,6 +58,6 @@ MAX_UPLOAD_BYTES=4294967296
UPLOAD_PART_BYTES=8388608
STORAGE_QUOTA_BYTES=53687091200
OWNER_UPLOAD_QUOTA_BYTES=10737418240
MAX_PENDING_UPLOADS=10
MAX_PENDING_UPLOADS=30
# Files above 128 MiB remain blocked (ClamAV config must agree with this limit).
SCAN_MAX_BYTES=134217728

View File

@@ -16,14 +16,22 @@ jobs:
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
- name: Run fast regression checks
run: |
python3 -m py_compile app/*.py app/**/*.py ops/*.py deploy/*.py
python3 -m py_compile app/*.py app/*/*.py app/*/*/*.py ops/*.py deploy/*.py
python3 -m unittest \
tests.test_dependency_lock \
tests.test_staging_readiness \
deploy.test_production_preflight \
tests.test_pricing \
tests.test_cart_pricing \
tests.test_db_pool \
tests.test_coupons \
tests.test_grade_rules \
tests.test_hotfolder \
tests.test_migrate \
tests.test_label \
tests.test_observability \
tests.test_secrets -v
node tests/observability_web_test.mjs
sh -n infra/lock_dependencies.sh
integration:
@@ -67,6 +75,12 @@ jobs:
$COMPOSE up --build -d --wait --wait-timeout 600
$COMPOSE ps
# The database never blocks a rollback. Runs in db-init, the only job
# with the administrator connection; the whole test is rolled back, so
# nothing it inserts or alters remains.
- name: Rollback and migrations
run: $COMPOSE run --rm --no-deps db-init python -m tests.migrations_test
# Run inside the stack's own network. The runner is itself a container, so
# ports published on the host's loopback are in a different namespace and
# unreachable from here. SITE_HOST_HEADER keeps the Host the gateway and
@@ -74,7 +88,7 @@ jobs:
# one a developer exercises on localhost.
- name: API and workflow regressions
run: |
for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test; do
for suite in smoke_test workflow_test security_test upload_limits_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test label_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test; do
echo "--- $suite"
$COMPOSE exec -T \
-e SITE_BASE_URL=http://site \
@@ -87,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 -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

@@ -190,17 +190,49 @@ class EventAdapter(Protocol):
def deliver(self, event_key: str, payload: dict) -> dict: ...
class FakeTiny:
# The montador's Venda customer search (front 7a.3) has somewhere to look
# on the local stack and in CI. Two fixed contacts, always.
CONTACTS = [
{'id': 1001, 'name': 'Nexstar Marketplace Ltda', 'document': '11.222.333/0001-81',
'email': 'financeiro@nexstar.example', 'phone': '1633334444'},
{'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']}",
'event_key': event_key, 'status': 'recorded-locally'}
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): ...
@@ -214,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):
@@ -255,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, operator
from ..core.models import ArtworkSubmission, UploadStart
from ..runtime import file_rows, operator_identity
from ..core.auth import can, can_any, operator
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()
@@ -38,15 +40,15 @@ def final_status(uid: UUID, user=Depends(operator)):
# The parts of an upload its operator started: a final (produce) or the
# photo of a signed pickup receipt (deliver, which includes produce).
@router.post('/api/operator/uploads/{uid}/parts/{number}')
def final_part(uid: UUID, number: int, user=Depends(can('deliver'))):
def final_part(uid: UUID, number: int, user=Depends(can_any('deliver', 'assemble'))):
return part_url(uid,number,session_id=operator_identity(user))
@router.post('/api/operator/uploads/{uid}/complete')
def final_complete(uid: UUID, user=Depends(can('deliver'))):
def final_complete(uid: UUID, user=Depends(can_any('deliver', 'assemble'))):
return complete_upload(uid,session_id=operator_identity(user))
@router.delete('/api/operator/uploads/{uid}')
def final_cancel(uid: UUID, user=Depends(can('deliver'))):
def final_cancel(uid: UUID, user=Depends(can_any('deliver', 'assemble'))):
return cancel_upload(uid,session_id=operator_identity(user))
@router.get('/api/operator/orders/{oid}/files')
@@ -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

@@ -90,7 +90,7 @@ def checked_code(c, table, key, code, request, extra=''):
return row, None
c.execute(f'UPDATE dtf_local.{table} SET attempts=attempts+1 WHERE id=%s', (row['id'],))
left = CODE_ATTEMPTS - row['attempts'] - 1
audit('code_wrong', kind=table, ip=client_ip(request))
audit('code_wrong', kind=table, ip=client_ip(request), c=c)
return None, HTTPException(400, 'Código incorreto. ' + (f'Restam {left} tentativas.' if left > 1 else
'Resta 1 tentativa.' if left == 1 else 'Clique em “Reenviar código”.'))
@@ -157,7 +157,7 @@ def claim_orders(c, identity, profile):
c.execute('UPDATE dtf_local.uploads SET owner=%s WHERE id=ANY(%s::uuid[]) AND owner=%s',
(identity, [str(uid) for uid in uploads], order['owner']))
if orders:
audit('account_orders_claimed', account=str(identity), orders=len(orders))
audit('account_orders_claimed', account=str(identity), orders=len(orders), c=c)
return len(orders)

View File

@@ -1,12 +1,14 @@
"""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
from ..core import db
from .. import catalog, mail
from .. import catalog, grade_rules, mail, observability
from ..core.auth import client_ip, owner, new_session, rate_limit
from ..core.limits import upload_limit_bytes
from ..core.pricing import manual_extra_cents
@@ -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):
@@ -40,14 +78,26 @@ def session(request: Request, response: Response):
session_id = new_session(c, response)
with db.connect() as c:
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(),
# Per metre on a finished sheet someone opens by hand (app/core/pricing.py).
'manual_extra_cents': manual_extra_cents(),
# Zero keeps the designer's treatment hidden, as an off product does.
# Zero keeps Ajuste Fino hidden, as an off product does. Its bands
# are counted in arts, not metres.
'treatment_cents': treatment['unit_cents'] if treatment['enabled'] else 0,
'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,
# What the Site sells now: a switched-off product is hidden there.
# Bands travel with the price; the Site reads them as numbers.
'products': {mode: {**products[mode],
@@ -55,6 +105,10 @@ def session(request: Request, response: Response):
'unit_cents': band['unit_cents']}
for band in products[mode]['bands']]}
for mode in catalog.MODES},
# Public by design: the browser initialises Sentry with these; empty is off.
'sentry_dsn_web': os.environ.get('SENTRY_DSN_WEB', '').strip(),
'sentry_environment': os.environ.get('SENTRY_ENVIRONMENT') or ENVIRONMENT,
'sentry_release': observability.release() or '',
# Public by design: Mercado Pago's card form needs it in the browser.
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
# The delivery options the cart quotes, or none: pickup only.

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):
@@ -53,6 +53,8 @@ def sheet(mid: UUID, user=Depends(can('view'))):
'counters': machine_log.counters(c, mid),
'supplies': machine_log.supply_estimates(c, mid),
'minimums': minimums,
# The values the sheet shows when Gestão has not typed one.
'default_minimums': machine_log.DEFAULT_MINIMUMS,
'alerts': machine_log.alerts(c, mid),
'entries': [{**row, 'label': entry_label(row)} for row in entries],
'catalog': {'supplies': machine_log.SUPPLIES, 'parts': machine_log.PARTS,
@@ -125,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)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,17 @@
"""Kanban: sign-in, the board, commercial review and card movement, by area.
Each module owns its routes; this package keeps the single `router` app/app.py
includes and the names other modules imported from the old single file.
"""
from fastapi import APIRouter
from . import board, common, files, integrations, labels, orders, quotes, rework, session, stats
from .integrations import tiny_callback
from .stats import speed_figures
router = APIRouter()
# The order the routes first appeared in the old file. Static paths that could
# meet a parameterised one stay ahead of it: /orders/finished before any
# /orders/{uid} GET.
for module in (common, session, integrations, board, quotes, rework, orders, labels, stats, files):
router.include_router(module.router)

290
app/api/operator/board.py Normal file
View File

@@ -0,0 +1,290 @@
"""The board, its stage limits, and the finished orders beyond it."""
from datetime import datetime, timezone
from decimal import Decimal
from typing import Literal
from uuid import UUID
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
from ...printjobs import CLAIM_TIMEOUT
from ...runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT,
PUBLIC_ORIGIN, STATES, TRANSITIONS, payment, quote_views)
from .common import (FINAL_OK, LIVE_QUOTE, TREATED, company_names, cursor_pair, person,
thumbnails)
from .integrations import backup_status, freight_status, tiny_status
router = APIRouter()
@router.get('/api/operator/board')
def board(user=Depends(operator)):
with db.connect() as c:
limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']}
for row in c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall()}
# Everything still in progress, however old: an operator must never lose a
# card they can act on. Finished orders are terminal and only accumulate,
# so the board carries a recent window of them and reports the true total.
active = c.execute("SELECT * FROM dtf_local.orders WHERE state<>'fin' ORDER BY created_at").fetchall()
# A proof card that got its answer is done with (app/proof.py).
finished = c.execute('''SELECT * FROM (
SELECT o.*, COALESCE((SELECT max(m.created_at) FROM dtf_local.movements m
WHERE m.order_id=o.id AND m.to_state='fin' AND NOT m.back), o.updated_at) AS finished_at
FROM dtf_local.orders o WHERE o.state='fin' AND o.parent_id IS NULL
) f ORDER BY finished_at DESC,id DESC LIMIT %s''', (BOARD_FINISHED_LIMIT,)).fetchall()
finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL").fetchone()['n']
pending = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND q.approved IS NULL AND {LIVE_QUOTE}
ORDER BY q.created_at DESC,q.id DESC LIMIT %s''', (BOARD_QUOTE_LIMIT,)).fetchall()
approved = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND q.approved IS NOT NULL AND {LIVE_QUOTE}
ORDER BY q.created_at DESC,q.id DESC LIMIT 20''').fetchall()
pending_total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND q.approved IS NULL AND {LIVE_QUOTE}''').fetchone()['n']
approved_total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND q.approved IS NOT NULL AND {LIVE_QUOTE}''').fetchone()['n']
orders = with_print_files(c, active + finished)
assign_late(c, orders, limits)
# A paid notification that did not become an order is money received
# for nothing the factory will make. The board carries the count; the
# Pagamentos tab pages through them until someone records a resolution.
issues_total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events
WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') AND resolved_at IS NULL''').fetchone()['n']
backup = backup_status(c)
quotes = quote_views(c, pending + approved)
return {'states': STATES, 'transitions': TRANSITIONS, 'back': BACK,
'orders': orders, 'payment_issues_total': issues_total, 'tiny': tiny_status(c), 'operator': user,
'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup,
'mail': mail.status(c)},
'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.DEFAULT_PLACES,
'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
'names': company_names(c, orders, quotes),
'pending_total': pending_total, 'approved_total': approved_total,
'stage_limits': limits}
class StageLimit(StrictModel):
state: Literal['rec', 'tra', 'imp', 'rev', 'fin']
hours: Decimal = Field(gt=0, le=10000)
responsible: str = Field(default='', max_length=80)
class StageLimits(StrictModel):
limits: list[StageLimit] = Field(min_length=1, max_length=5)
@router.get('/api/operator/stage-limits')
def get_stage_limits(user=Depends(operator)):
with db.connect() as c:
rows = c.execute('''SELECT state,hours,responsible,updated_by,updated_at
FROM dtf_local.stage_limits ORDER BY array_position(ARRAY['rec','tra','imp','rev','fin'],state)''').fetchall()
return {'limits': [{'state': row['state'], 'hours': float(row['hours']),
'responsible': row['responsible'], 'updated_by': row['updated_by'],
'updated_at': row['updated_at']} for row in rows]}
@router.post('/api/operator/stage-limits')
def set_stage_limits(body: StageLimits, user=Depends(can('manage'))):
seen = set()
with db.connect() as c:
for limit in body.limits:
if limit.state in seen:
raise HTTPException(422, 'Cada etapa aparece uma vez.')
seen.add(limit.state)
c.execute('''INSERT INTO dtf_local.stage_limits(state,hours,responsible,updated_by,updated_at)
VALUES(%s,%s,%s,%s,now())
ON CONFLICT (state) DO UPDATE SET hours=EXCLUDED.hours,responsible=EXCLUDED.responsible,
updated_by=EXCLUDED.updated_by,updated_at=now()''',
(limit.state, limit.hours, limit.responsible.strip(), user))
audit('stage_limits_changed', operator=user, states=','.join(sorted(seen)))
return {'ok': True}
def assign_late(c, orders, limits):
"""How long each card has been in its stage, and whether it passed the
limit Gestão set (front 11). A finished card with pickup is not late."""
ids = [order['id'] for order in orders]
if not ids:
return
entered = {}
for row in c.execute('''SELECT order_id,to_state,created_at FROM dtf_local.movements
WHERE order_id=ANY(%s) ORDER BY created_at,id''', (ids,)).fetchall():
entered[(str(row['order_id']), row['to_state'])] = row['created_at']
now = datetime.now(timezone.utc)
for order in orders:
if order.get('cancelled_at') or payments.is_test(order):
continue
limit = limits.get(order['state'])
if not limit:
continue
# Finalizado only has a pickup deadline; a delivery is done when it
# leaves, and a collected order is not waiting for anyone.
if order['state'] == 'fin' and (order.get('picked_up_at') or
not receipt.is_pickup(order['snapshot'])):
continue
since = entered.get((str(order['id']), order['state']))
if not since and order['state'] == 'fin':
since = order.get('finished_at')
since = since or order['created_at']
hours = max(0.0, (now - since).total_seconds() / 3600)
limit_hours = float(limit['hours'])
# 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']
order['late'] = 'bad' if hours >= limit_hours * 2 else 'warn' if hours >= limit_hours else None
def assign_machines(c, orders):
"""Each machine, its pull attribution, and its printing place."""
names = {str(m['id']): m['name'] for m in c.execute('SELECT id,name FROM dtf_local.machines').fetchall()}
slots = machines.printing_slots(c)
ids = [o['id'] for o in orders] + [o['proof_card']['id'] for o in orders if o.get('proof_card')]
pulled = {r['order_id']: r for r in c.execute('''SELECT DISTINCT ON (order_id) order_id,operator,created_at
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='imp' AND NOT back
ORDER BY order_id,id DESC''', (ids,)).fetchall()}
for order in orders:
key = str(order.get('machine_id') or '')
order['machine'] = ({'id': key, 'name': names[key], 'chosen': bool(order.get('machine_chosen'))}
if key in names else None)
order['printing'] = slots.get(order['id'])
by = pulled.get(order['id']) or (pulled.get(order['proof_card']['id']) if order.get('proof_card') else None)
order['machine_pulled'] = {'by': by['operator'], 'at': by['created_at']} if by else None
return orders
def with_print_files(c, orders):
"""Each order with its generated print files, the items whose final file is
approved, and the customer's corrections waiting to be approved as finals."""
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 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']
for uid in item.get('uploads') or []})
uploads = {row['id']: row for row in c.execute(
'''SELECT id::text AS id,name,original_name FROM dtf_local.uploads WHERE id::text=ANY(%s)''',
(upload_ids,)).fetchall()}
# A film over 15 m is several PNGs, in order (item 13).
parts = c.execute('''SELECT p.order_id,p.item_index,p.part,p.upload_id,u.name FROM dtf_local.print_parts p
JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE p.order_id=ANY(%s) ORDER BY p.part''', (ids,)).fetchall()
for row in generated:
row['parts'] = [{'upload_id': part['upload_id'], 'name': part['name']} for part in parts
if part['order_id'] == row['order_id'] and part['item_index'] == row['item_index']]
finals = c.execute(f'''SELECT f.order_id,f.item_index,f.upload_id FROM dtf_local.order_files f
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=ANY(%s) AND {FINAL_OK}''', (ids,)).fetchall()
# Expired ones too: once corrected, a generated file is no longer the artwork.
fixes = c.execute('''SELECT f.order_id,f.item_index,f.upload_id,u.name,
(u.expires_at<=now() OR u.purged_at IS NOT NULL) AS expired FROM dtf_local.order_files f
JOIN dtf_local.uploads u ON u.id=f.upload_id
WHERE f.order_id=ANY(%s) AND f.kind='correction' AND f.active ORDER BY f.item_index''', (ids,)).fetchall()
# The items whose approved final someone prepared, and who approved it.
treated = c.execute(f'''SELECT f.order_id,f.item_index,f.created_by FROM dtf_local.order_files f
JOIN dtf_local.orders o ON o.id=f.order_id WHERE f.order_id=ANY(%s) AND f.active AND {TREATED}
ORDER BY f.item_index''', (ids,)).fetchall()
# Each order's reworks (D-02 to D-04), with the names of who opened,
# decided and printed.
reworks = c.execute(f'''SELECT r.*, {person('r.opened_by')} AS opened_name, {person('r.decided_by')} AS decided_name,
{person('r.printed_by')} AS printed_name FROM dtf_local.reworks r WHERE r.order_id=ANY(%s) ORDER BY r.id''',
(ids,)).fetchall()
# Why each order was last sent to correction, for the notice to the customer.
reasons = {row['order_id']: row['reason'] for row in c.execute('''SELECT DISTINCT ON (order_id) order_id,reason
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,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'])
# 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
order['print_files'] = [row for row in generated if row['order_id'] == order['id']]
order['prumo'] = prumo.report(order, uploads)
approved = [row for row in finals if row['order_id'] == order['id']]
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')}
for row in fixes if row['order_id'] == order['id']]
order['reworks'] = [row for row in reworks if row['order_id'] == order['id']]
return assign_machines(c, orders)
@router.get('/api/operator/orders/finished')
def finished_page(before_finished_at: datetime | None = None, before_id: UUID | None = None,
limit: int = Query(default=50, ge=1, le=100), user=Depends(operator)):
"""Older finished orders, newest first, beyond the board's recent window."""
paged = cursor_pair(before_finished_at, before_id)
with db.connect() as c:
rows = c.execute('''SELECT * FROM (
SELECT o.*, COALESCE((SELECT max(m.created_at) FROM dtf_local.movements m
WHERE m.order_id=o.id AND m.to_state='fin' AND NOT m.back), o.updated_at) AS finished_at
FROM dtf_local.orders o WHERE o.state='fin' AND o.parent_id IS NULL
) f ''' + ('WHERE (finished_at,id)<(%s,%s) ' if paged else '') + '''
ORDER BY finished_at DESC,id DESC LIMIT %s''',
((before_finished_at, before_id) if paged else ()) + (limit + 1,)).fetchall()
orders = with_print_files(c, rows[:limit])
return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders),
'names': company_names(c, orders)}
@router.get('/api/operator/orders/{uid}/history')
def history(uid: UUID, user=Depends(operator)):
with db.connect() as c:
return c.execute('SELECT * FROM dtf_local.movements WHERE order_id=%s ORDER BY id', (uid,)).fetchall()
@router.get('/api/operator/uploads/{uid}/thumbnail')
def thumbnail(uid: UUID, user=Depends(operator)):
"""The browser-made picture of an artwork. Cached by the operator's browser:
the board is redrawn on every refresh."""
with db.connect() as c:
row = c.execute('SELECT mime,data FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'No picture for this upload')
return Response(bytes(row['data']), media_type=row['mime'],
headers={'Cache-Control': 'private, max-age=86400', 'Content-Disposition': 'inline'})

View File

@@ -0,0 +1,91 @@
"""Helpers and constants shared by more than one Kanban router."""
import re
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()
# A quote that can still become an order: waiting for review, or approved and
# not expired yet. The worker marks it expired at 24 h (app/unpaid.py); until
# then it stays, even past the payment window while an attempt is still live.
LIVE_QUOTE = "(q.discarded_at IS NULL AND q.expired_at IS NULL)"
def uploads_of(rows):
"""Every upload id an order (its snapshot) or a quote (its draft) refers to."""
ids = set()
for row in rows:
content = row.get('snapshot') or row.get('draft') or {}
for item in content.get('items') or []:
ids.update(str(uid) for uid in item.get('uploads') or [])
return ids
def thumbnails(c, *groups):
"""The uploads among these orders and quotes that have an artwork picture,
so the Kanban asks only for pictures that exist."""
ids = set().union(*(uploads_of(rows) for rows in groups))
if not ids:
return []
rows = c.execute('SELECT upload_id FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s::uuid[])',
(list(ids),)).fetchall()
return [str(r['upload_id']) for r in rows]
def company_names(c, *groups):
"""The registry's company names for these orders' and quotes' CNPJs (app/cnpj.py)."""
return cnpj.names(c, [((row.get('snapshot') or row.get('draft') or {}).get('customer') or {}).get('cnpj')
for rows in groups for row in rows])
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})'
def cursor_pair(first, second):
if (first is None) != (second is None):
raise HTTPException(422, 'Both cursor fields are required')
return first is not None
MODES = {'textil': {'file', 'avulsa', 'premium'}, 'uv': {'uvfile', 'uv'},
'folha': {'file', 'uvfile', 'premium'}, 'avulsa': {'avulsa', 'uv'}}
def like(text):
"""A LIKE pattern that matches the text anywhere, its own % and _ literal."""
return '%' + re.sub(r'([\\%_])', r'\\\1', text) + '%'
def numeric(q):
"""The digits of a query made of digits and punctuation only ("#1042",
"11.222.333/0001-81", "(16) 99999-0000"); empty when it has letters."""
return '' if re.search(r'[^\W\d_]', q) else re.sub(r'\D', '', q)
def customer_match(column, q):
"""SQL and parameters matching a customer (e-mail, company name, CNPJ or
WhatsApp) in an order snapshot or a quote draft. CNPJ and phone match by
their digits, and only when nothing but digits and punctuation was typed:
the digits of an e-mail address are not a phone number."""
text, digits = q.strip().lower(), numeric(q)
cnpj = f"regexp_replace(coalesce({column}->'customer'->>'cnpj',''),'\\D','','g')"
sql = (f"lower({column}->'customer'->>'mail') LIKE %s OR {cnpj} IN (SELECT n.cnpj FROM dtf_local.cnpj_names n"
" WHERE lower(n.legal_name) LIKE %s OR lower(n.trade_name) LIKE %s)")
params = [like(text)] * 3
if len(digits) >= 3:
sql += (f" OR regexp_replace(coalesce({column}->'customer'->>'cnpj',''),'\\D','','g') LIKE %s"
f" OR regexp_replace(coalesce({column}->'customer'->>'zap',''),'\\D','','g') LIKE %s")
params += [like(digits), like(digits)]
return '(' + sql + ')', params
# Real work only: an operator's test order and a cancelled one are not production.
# A proof card (app/proof.py) is no sale either.
REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste' AND o.parent_id IS NULL"
# Where orders come from (D-21), in the order Números lists them.
ORIGINS = ('site', 'dropflow', 'atendimento')

256
app/api/operator/files.py Normal file
View File

@@ -0,0 +1,256 @@
"""The print room's files: queue, folders, downloads and the order viewer."""
from datetime import datetime, timedelta, timezone
from typing import Literal
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException
from pydantic import Field
from ... import hotfolder, receipt
from ...core import db
from ...core.auth import audit, can, operator
from ...core.models import StrictModel
from ...printjobs import file_prefix
from ...runtime import storage
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
readable, with a link straight to storage."""
files, names = [], set()
for row in rows:
prefix = file_prefix(row['number'], row['item_index'])
# Generated before 2026-10-23, a file was called pedido-23-item-1.
older = f"pedido-{row['number']}-item-{row['item_index'] + 1}"
name = row['name']
if name.startswith(older):
name = prefix + name[len(older):]
# 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
while name in names:
name = f'{stem} ({copy}).{ext}' if dot else f'{ext} ({copy})'
copy += 1
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, FOLDER_LINK_SECONDS)})
return files
def print_ready(c, states, only=None, paid_after=None):
"""The file to print for each item of the orders in these stages, in queue
order: the approved final, or before approval the generated print file
(unless the customer has sent a correction since). `only` narrows it to
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, 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)), 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
JOIN dtf_local.uploads u ON u.id=pp.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.state IN ('rec','tra') AND o.cancelled_at IS NULL AND p.status='ready'
AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'
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,part NULLS LAST,name''',
(list(states), ids, ids, paid_after, paid_after, list(states), ids, ids, paid_after, paid_after)).fetchall()
return rows
@router.get('/api/operator/orders/{uid}/view')
def view_files(uid: UUID, user=Depends(operator)):
"""What "Abrir e conferir" shows (item 7): each item's generated PNG, part
by part, with links to its pieces, then the customer's originals, which
have only their picture."""
with db.connect() as c:
order = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
made = c.execute('''SELECT item_index, detail FROM dtf_local.print_files WHERE order_id=%s AND status='ready'
ORDER BY item_index''', (uid,)).fetchall()
parts = c.execute('''SELECT p.item_index, p.part, p.upload_id, u.name FROM dtf_local.print_parts p
JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE p.order_id=%s AND u.purged_at IS NULL
ORDER BY p.item_index, p.part''', (uid,)).fetchall()
pictured = {str(r['upload_id']) for r in c.execute(
'SELECT upload_id FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s)',
([UUID(u) for item in order['snapshot']['items'] for u in item['uploads']],)).fetchall()}
items = order['snapshot']['items']
many = len(items) > 1
files = []
for row in made:
mine = [p for p in parts if p['item_index'] == row['item_index']]
details = {d.get('name'): d for d in row['detail'].get('parts') or []}
for part in mine:
tiles = (details.get(part['name']) or {}).get('tiles')
label = (f"Item {row['item_index'] + 1}" if many else 'Arquivo') + \
(f" · parte {part['part']}/{len(mine)}" if len(mine) > 1 else '')
files.append({'name': part['name'], 'label': label, 'item': row['item_index'],
'manifest': tiles and {**tiles, 'urls': [
[storage.view(f"originals/tiles/{part['upload_id']}/{k}/{i}.png", 'image/png')
for i in range(level['strips'])] for k, level in enumerate(tiles['levels'])]}})
for index, item in enumerate(items):
for n, upload in enumerate(item['uploads']):
files.append({'name': ('Original ' + str(n + 1)) if len(item['uploads']) > 1 else 'Original',
'label': (f'Item {index + 1} · ' if many else '') + 'original' +
(f' {n + 1}' if len(item['uploads']) > 1 else ''),
'item': index, 'manifest': None,
'picture': f'/api/operator/uploads/{upload}/thumbnail' if upload in pictured else None})
return {'files': files}
@router.get('/api/operator/orders/{uid}/folder-files')
def folder_files(uid: UUID, user=Depends(can('produce'))):
"""What each item's file is called in the order's stage folder, as the
automatic folders save it: "Tratar a arte" shows where to open it."""
with db.connect() as c:
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
files = named_files(print_ready(c, (row['state'],), only=[uid]))
return {'state': row['state'], 'files': [{'item': f['item'], 'name': f['name']} for f in files]}
@router.get('/api/operator/queue/finals')
def queue_finals(auto: bool = False, user=Depends(can('print'))):
"""The approved final files of every order in the print queue (Arte
conferida). The browser downloads them straight from storage: a zip of
multi-GB sheets would go through the server."""
with db.connect() as c:
files = named_files(print_ready(c, ('tra',)))
# The automatic folder asks whenever the queue changes; only a person's download is logged.
if not auto:
audit('queue_finals_downloaded', operator=user, files=len(files))
return {'files': files}
class FolderSync(StrictModel):
early: bool = False
held: list[UUID] = Field(default_factory=list, max_length=1000)
# When the folders were chosen: the orders paid since are fetched whatever
# their stage, so what passed while the computer was off is not lost.
since: datetime | None = None
@router.post('/api/operator/queue/hot')
def queue_hot(user=Depends(can('print'))):
"""For a computer with the automatic folders: the parts it should write
into the machines' hot folders now, claimed for it alone; those written
and not yet taken by Flexi, to see whether they still are; and those to
delete, withdrawn from cards that left Imprimindo (item 10)."""
with db.connect() as c:
due = hotfolder.claim(c, user)
keys = {str(r['upload_id']): r['object_key'] for r in c.execute(
'SELECT id AS upload_id, object_key FROM dtf_local.uploads WHERE id=ANY(%s)',
([r['upload_id'] for r in due],)).fetchall()} if due else {}
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'], 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']}
for r in watched if r['state'] == 'withdraw']}
class HotReport(StrictModel):
state: Literal['written', 'released', 'consumed', 'gone']
@router.post('/api/operator/queue/hot/{part_id}')
def report_hot(part_id: int, body: HotReport, user=Depends(can('print'))):
"""What a computer saw of a part: written, not written, taken by Flexi,
or deleted after it was withdrawn."""
with db.connect() as c:
applied = hotfolder.report(c, part_id, body.state, user)
if applied and body.state == 'written':
audit('hot_folder_written', part=part_id, operator=user)
return {'ok': applied}
@router.post('/api/operator/queue/folder')
def queue_folder(body: FolderSync, user=Depends(can('print'))):
"""What the Kanban's automatic folders should hold. `early` is Dropstar's
stage folders (2026-10-26): the files of orders in Arte recebida and Arte
conferida, and, for the orders the folders already hold, their files while
they print, are checked in Revisão and sit in Finalizado, so one taken out
of a folder can be fetched again when the order moves on. With `since`,
also every order paid after the folders were chosen, whatever its stage:
a computer that was off catches up on what passed meanwhile (Dropstar's
rules, 2026-10-26). Without it, only
the queue's (Firefox's downloads). `states` answers for the orders the
folders hold files of: a stage, 'cancelled', or nothing when the order was
deleted, so their files can be removed."""
with db.connect() as c:
rows = print_ready(c, ('rec', 'tra') if body.early else ('tra',))
if body.early and body.held:
rows += print_ready(c, ('imp', 'rev', 'fin'), only=body.held)
if body.early and body.since:
seen = {(r['order_id'], r['item_index'], r['upload_id']) for r in rows}
rows += [r for r in print_ready(c, ('imp', 'rev', 'fin'), paid_after=body.since)
if (r['order_id'], r['item_index'], r['upload_id']) not in seen]
files = named_files(rows)
held = c.execute('SELECT id,state,cancelled_at FROM dtf_local.orders WHERE id=ANY(%s)',
(body.held,)).fetchall() if body.held else []
# The pickup receipts no computer saved yet (item 14), due since the
# folders were chosen: one that was off catches up, like the files.
due = c.execute('''SELECT id, number FROM dtf_local.orders WHERE receipt_due_at IS NOT NULL
AND receipt_saved_at IS NULL AND cancelled_at IS NULL AND (%s::timestamptz IS NULL OR receipt_due_at>=%s)
ORDER BY receipt_due_at''', (body.since, body.since)).fetchall() if body.early else []
# The review photos and videos to copy into Revisões/ (front 2). Without
# `since`, the last 30 days, so a new computer catches up.
since = body.since or datetime.now(timezone.utc) - timedelta(days=30)
review_rows = c.execute('''SELECT r.id,r.order_id,o.number,r.upload_id,u.name
FROM dtf_local.order_reviews r
JOIN dtf_local.orders o ON o.id=r.order_id
JOIN dtf_local.uploads u ON u.id=r.upload_id
WHERE o.cancelled_at IS NULL AND r.created_at>=%s ORDER BY r.created_at,r.id''', (since,)).fetchall()
return {'files': files,
'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held},
'receipts': [{'order': str(o['id']), 'number': o['number'], 'name': receipt.file_name(o)} for o in due],
'reviews': [{'id': r['id'], 'order': str(r['order_id']), 'number': r['number'],
'upload_id': str(r['upload_id']), 'name': r['name']} for r in review_rows]}
@router.get('/api/operator/uploads/{uid}/download')
def download(uid: UUID, order_id: UUID | None = None, user=Depends(operator)):
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.uploads WHERE id=%s AND complete', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Completed upload not found')
if row['expires_at'] <= datetime.now(timezone.utc):
raise HTTPException(410, 'Artwork retention expired')
require_clean(row)
name = row['name']
if order_id:
order = c.execute('SELECT number,snapshot FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
originals = [upload for item in order['snapshot']['items'] for upload in item['uploads']]
if str(uid) not in originals:
raise HTTPException(422, 'Este arquivo não é original do pedido.')
index = originals.index(str(uid)) + 1
suffix = row['name'].rsplit('.', 1)[-1].lower() if '.' in row['name'] else 'bin'
name = f'DTF-{order["number"]}-original-{index}.{suffix}'
return {'name':name, 'url':storage.download(row['object_key'],name), 'expires_in':300}

View File

@@ -0,0 +1,236 @@
"""Integrations: freight, backup, payment events, Tiny and Mercado Pago."""
import os
from datetime import datetime, timezone
from typing import Literal
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import RedirectResponse
from ... import tiny
from ...core import db
from ...core.auth import audit, can
from ...core.models import Resolution
from ...runtime import freight, payment
from .common import thumbnails
router = APIRouter()
def freight_status():
"""What delivery the Site offers, and the package rule it prices with."""
real = [carrier for carrier in freight.carriers if carrier.name != 'fake']
status = {'carriers': [carrier.name for carrier in real], 'services': freight.services if real else {}}
if real:
# One package for every carrier (app/package.py).
status.update(real[0].status())
return status
def backup_status(c):
"""The latest database backup and the latest run, which may have failed."""
ok = c.execute('''SELECT finished_at,bytes FROM dtf_local.backups WHERE status='ok'
ORDER BY finished_at DESC LIMIT 1''').fetchone()
last = c.execute('SELECT started_at,finished_at,status,detail FROM dtf_local.backups ORDER BY finished_at DESC LIMIT 1').fetchone()
asked = c.execute('''SELECT 1 FROM dtf_local.backup_requests WHERE requested_at>%s LIMIT 1''',
(last['started_at'] if last else datetime(2000, 1, 1, tzinfo=timezone.utc),)).fetchone()
return {'last_ok': ok['finished_at'].isoformat() if ok else None, 'bytes': ok['bytes'] if ok else None,
'failed': last['detail'] if last and last['status'] == 'failed' else None,
'failed_at': last['finished_at'].isoformat() if last and last['status'] == 'failed' else None,
'requested': asked is not None}
@router.post('/api/operator/backup/run')
def backup_now(user=Depends(can('integrations'))):
"""A backup now, outside the daily hour: the backup service, which alone
may read the whole database, starts it within a minute."""
with db.connect() as c:
c.execute('INSERT INTO dtf_local.backup_requests(requested_by) VALUES(%s)', (user,))
audit('backup_requested', operator=user)
return {'ok': True}
@router.get('/api/operator/payment-events')
def payment_events(state: Literal['open','resolved','all'] = 'open',
offset: int = Query(default=0, ge=0),
limit: int = Query(default=20, ge=1, le=100), user=Depends(can('payments'))):
"""Payments that needed a person, newest first: open ones to act on, resolved ones as history."""
where = {'open': 'AND resolved_at IS NULL', 'resolved': 'AND resolved_at IS NOT NULL', 'all': ''}[state]
with db.connect() as c:
rows = c.execute('''SELECT id,provider,event_id,reference,status,amount_cents,received_at,outcome,
resolved_at,resolved_by,resolution
FROM dtf_local.payment_events WHERE (outcome LIKE 'refused%%' OR outcome LIKE 'attention%%') ''' + where + '''
ORDER BY received_at DESC,id DESC LIMIT %s OFFSET %s''', (limit, offset)).fetchall()
total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events
WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') ''' + where).fetchone()['n']
for row in rows:
row.update(payment_context(c, row))
return {'issues': rows, 'total': total, 'thumbnails': thumbnails(c, [r['quote'] for r in rows if r.get('quote')])}
def payment_context(c, row):
"""Who tried to pay and for what: the quote the payment points to (its
customer, items and total), its order if there is one, the method of the
last attempt and Mercado Pago's own words about the payment."""
payload = c.execute('SELECT payload FROM dtf_local.payment_events WHERE id=%s', (row['id'],)).fetchone()['payload'] or {}
out = {'payment_id': payload.get('payment_id'), 'status_detail': payload.get('status_detail'), 'quote': None, 'order': None, 'method': None}
try:
quote_id = UUID(str(row.get('reference') or ''))
except ValueError:
return out
quote = c.execute('SELECT id,draft,approved,created_at,approved_at FROM dtf_local.quotes WHERE id=%s', (quote_id,)).fetchone()
if not quote:
return out
out['quote'] = {'id': quote['id'], 'draft': quote['draft'], 'created_at': quote['created_at'], 'approved_at': quote['approved_at'],
'total_cents': (quote['approved'] or {}).get('total_cents')}
out['order'] = c.execute('SELECT id,number,state,cancelled_at FROM dtf_local.orders WHERE quote_id=%s', (quote_id,)).fetchone()
attempt = c.execute('''SELECT method,status FROM dtf_local.payment_intents WHERE quote_id=%s
ORDER BY created_at DESC LIMIT 1''', (quote_id,)).fetchone()
out['method'] = attempt['method'] if attempt else None
return out
@router.get('/api/operator/events')
def events(provider: Literal['tiny'] | None = None,
status: Literal['delivered','queued','failing'] | None = None,
event: Literal['payment_approved','production_started','correction_needed','ready','cancelled'] | None = None,
order: int | None = Query(default=None, ge=1), offset: int = Query(default=0, ge=0),
limit: int = Query(default=20, ge=1, le=100), user=Depends(can('integrations'))):
"""The integration send log, newest first, filtered, by page with a total."""
clauses, params = [], []
if provider:
clauses.append('provider=%s'); params.append(provider)
if status == 'delivered':
clauses.append('delivered_at IS NOT NULL')
elif status == 'queued':
clauses.append('delivered_at IS NULL AND last_error IS NULL')
elif status == 'failing':
clauses.append('delivered_at IS NULL AND last_error IS NOT NULL')
if event:
clauses.append("payload->>'event'=%s"); params.append(event)
if order:
clauses.append("payload->>'number'=%s"); params.append(str(order))
where = ('WHERE ' + ' AND '.join(clauses)) if clauses else ''
with db.connect() as c:
rows = c.execute(f'SELECT * FROM dtf_local.outbox {where} ORDER BY id DESC LIMIT %s OFFSET %s',
(*params, limit, offset)).fetchall()
total = c.execute(f'SELECT count(*) AS n FROM dtf_local.outbox {where}', params).fetchone()['n']
return {'events': rows, 'total': total}
@router.post('/api/operator/payment-events/{uid}/resolve')
def resolve_payment(uid: UUID, body: Resolution, user=Depends(can('manage'))):
with db.connect() as c:
row = c.execute('''UPDATE dtf_local.payment_events SET resolved_at=now(), resolved_by=%s, resolution=%s
WHERE id=%s AND (outcome LIKE 'refused%%' OR outcome LIKE 'attention%%') AND resolved_at IS NULL RETURNING id''',
(user, body.note, uid)).fetchone()
if not row:
raise HTTPException(404, 'No open payment issue with this id')
audit('payment_issue_resolved', payment_event=str(uid), operator=user)
return {'ok': True}
def tiny_status(c=None):
if not tiny.configured():
return {'configured': False}
return {'configured': True, 'orders_enabled': os.environ.get('TINY_ADAPTER') == 'tiny',
**tiny.TinyAuth().status(c)}
@router.get('/api/operator/tiny/contacts')
def tiny_contacts(q: str = Query(min_length=1, max_length=120), user=Depends(can('assemble'))):
"""The Tiny contacts a Venda customer is picked from (Fase 2, front
7a.3): by name, or by CPF/CNPJ when only digits were typed. The fake
adapter answers with two fixed contacts on the local stack and in CI."""
if os.environ.get('TINY_ADAPTER') != 'tiny':
from ...adapters import FakeTiny
return FakeTiny().search_contacts(q)
if not tiny.configured():
raise HTTPException(409, 'O Tiny não está conectado.')
try:
return tiny.search_contacts(tiny.TinyOrders(), q)
except tiny.TinyNotConnected:
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."""
if not tiny.configured():
raise HTTPException(503, 'Tiny application is not configured')
audit('tiny_connect_started', operator=user)
return {'url': tiny.TinyAuth().authorize_url(user)}
@router.post('/api/operator/tiny/test')
def tiny_test(user=Depends(can('integrations'))):
"""Read one order and one contact from Tiny. Creates nothing."""
if not tiny.configured():
raise HTTPException(503, 'Tiny application is not configured')
try:
results = tiny.check()
except tiny.TinyNotConnected as exc:
raise HTTPException(409, str(exc))
audit('tiny_tested', operator=user, ok=all(v == 'ok' for v in results.values()))
return {'ok': all(v == 'ok' for v in results.values()), 'results': results}
@router.post('/api/operator/mercadopago/check')
def mercadopago_check(user=Depends(can('integrations'))):
"""The Mercado Pago account behind the configured token; reads only."""
if payment.name != 'mercadopago':
raise HTTPException(409, 'Mercado Pago não está configurado')
from ..mercadopago_probe import check
audit('mercadopago_check', operator=user)
result = check(payment.access_token)
# Whether Mercado Pago's notifications reach this server and pass the
# signature: every accepted one is recorded, a refused one is audited.
with db.connect() as c:
received = c.execute('''SELECT count(*) AS n, max(received_at) AS last FROM dtf_local.payment_events
WHERE provider='mercadopago' AND received_at > now()-interval '24 hours' ''').fetchone()
last = c.execute('''SELECT received_at,status,outcome FROM dtf_local.payment_events
WHERE provider='mercadopago' ORDER BY received_at DESC LIMIT 1''').fetchone()
refused = c.execute('''SELECT count(*) AS n FROM dtf_local.security_events
WHERE event='payment_webhook_rejected' AND created_at > now()-interval '24 hours' ''').fetchone()
result['webhooks'] = {'accepted_24h': received['n'], 'refused_24h': refused['n'], 'last': last}
return result
@router.get('/api/operator/tiny/callback')
def tiny_callback(code: str = Query('', max_length=4096), state: str = Query('', max_length=128),
error: str = Query('', max_length=128)):
"""Tiny's redirect back. Cross-site, so the operator cookie is absent: the
single-use state an operator created is what authorises it. Tiny reports a
refusal (the operator declined, or offline access is not allowed for this
application) with `error` instead of a code."""
if not tiny.configured():
raise HTTPException(503, 'Tiny application is not configured')
try:
if error == 'invalid_scope':
retry = tiny.TinyAuth().without_offline(state)
audit('tiny_offline_refused')
return RedirectResponse(retry, status_code=303)
if error or not code:
raise tiny.TinyError(f'Tiny returned {error or "no code"}')
who = tiny.TinyAuth().complete(code, state)
except tiny.TinyError:
audit('tiny_connect_failed')
return RedirectResponse('/?tiny=failed', status_code=303)
audit('tiny_connected', operator=who)
return RedirectResponse('/?tiny=connected', status_code=303)

View File

@@ -0,0 +1,81 @@
"""The 10x15 thermal label at Finalizado (Fase 2, front 10; Marcus, 2026-11-10).
The label page is rendered by the server; one computer prints it automatically
(the first claim), and the Expedição profile or the Revisor may reprint it.
"""
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Response
from ... import label
from ...core import db
from ...core.auth import audit, can
router = APIRouter()
def _order(c, uid, columns='number,state,cancelled_at'):
order = c.execute(f'SELECT {columns} FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
return order
def _tiny_number(c, uid):
"""The Tiny order number from the sale event's receipt, or None."""
row = c.execute("SELECT receipt->>'tiny_number' AS tiny_number FROM dtf_local.outbox WHERE event_key=%s",
(f'{uid}:paid:tiny',)).fetchone()
return row['tiny_number'] if row else None
def _finished(c, uid):
"""When the card reached Finalizado and who released it, from the movements."""
row = c.execute('''SELECT m.created_at,
COALESCE(NULLIF((SELECT o.name FROM dtf_local.operators o WHERE o.email=m.operator), ''),
m.operator) AS revisor
FROM dtf_local.movements m
WHERE m.order_id=%s AND m.to_state='fin' AND NOT m.back
ORDER BY m.created_at DESC, m.id DESC LIMIT 1''', (uid,)).fetchone()
return (row['created_at'], row['revisor']) if row else (None, None)
@router.get('/api/operator/orders/{uid}/label')
def order_label(uid: UUID, user=Depends(can('label'))):
"""The printable label page (text/html), sized 100 x 150 mm."""
with db.connect() as c:
order = _order(c, uid, 'number,state,cancelled_at,updated_at,snapshot')
if order['cancelled_at'] or order['state'] != 'fin':
raise HTTPException(409, 'A etiqueta é impressa em Finalizado.')
tiny = _tiny_number(c, uid)
finished, revisor = _finished(c, uid)
fields = label.label_fields(order, tiny, finished or order['updated_at'], revisor)
return Response(label.label_html(fields), media_type='text/html; charset=utf-8',
headers={'Cache-Control': 'no-store'})
@router.post('/api/operator/orders/{uid}/label/claim')
def claim_label(uid: UUID, user=Depends(can('label'))):
"""The first computer to ask prints the label; the unique partial index on
the 'auto' row decides, so two computers at once cannot both print it."""
with db.connect() as c:
order = _order(c, uid)
if order['cancelled_at'] or order['state'] != 'fin':
return {'print': False}
row = c.execute('''INSERT INTO dtf_local.label_prints(order_id,reason,printed_by)
VALUES(%s,'auto',%s) ON CONFLICT DO NOTHING RETURNING id''', (uid, user)).fetchone()
if row:
audit('label_printed', order=order['number'], reason='auto', operator=user)
return {'print': bool(row)}
@router.post('/api/operator/orders/{uid}/label/reprint')
def reprint_label(uid: UUID, user=Depends(can('label'))):
"""A new label for an order in Finalizado, from any computer."""
with db.connect() as c:
order = _order(c, uid)
if order['cancelled_at'] or order['state'] != 'fin':
raise HTTPException(409, 'A etiqueta é reimpressa em Finalizado.')
c.execute('''INSERT INTO dtf_local.label_prints(order_id,reason,printed_by)
VALUES(%s,'reprint',%s)''', (uid, user))
audit('label_printed', order=order['number'], reason='reprint', operator=user)
return {'print': True}

657
app/api/operator/orders.py Normal file
View File

@@ -0,0 +1,657 @@
"""Order actions: cancel and delete, machine, contraction, contact, proof,
receipt and pickup, queue place, move, print-file regeneration."""
from datetime import datetime, timezone
from typing import Literal
from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException, Request, Response
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, 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, 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
from .common import FINAL_OK, TREATED
router = APIRouter()
@router.post('/api/operator/orders/{uid}/delete')
def delete_order(uid: UUID, user=Depends(can('manage'))):
"""Deletes a test order, or a paid order already cancelled, with its
history and files' records. A paid order in progress must be cancelled
first, with its reason. A test order's quote is unpaid again; a cancelled
one's is discarded, so it neither returns to Cotações nor can be paid twice.
The payment itself stays recorded, and the audit log keeps who deleted what."""
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, 'Order not found')
test = payments.is_test(row)
if not test and not row.get('cancelled_at'):
raise HTTPException(409, 'Cancele o pedido antes de excluir. Só pedidos cancelados ou de teste podem ser excluídos.')
# Its files leave storage too: the finals, corrections and generated PDFs,
# and the customer's originals unless the quote can still be paid (a test
# order's). The worker deletes them within a minute.
originals = {str(u) for item in row['snapshot'].get('items') or [] for u in item.get('uploads') or []}
produced = {str(r['upload_id']) for r in c.execute('''SELECT upload_id FROM dtf_local.order_files WHERE order_id=%s
UNION SELECT upload_id FROM dtf_local.print_files WHERE order_id=%s AND upload_id IS NOT NULL
UNION SELECT upload_id FROM dtf_local.print_parts WHERE order_id=%s''',
(uid, uid, uid)).fetchall()}
candidates = produced - originals if test else produced | originals
# Its proof cards (app/proof.py) go with it.
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,))
# 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',
(user, row['quote_id']))
freed = release_files(c, candidates)
audit('order_deleted', order=row['number'], test=test, operator=user,
reason=row.get('cancel_reason') or '', files_released=freed)
return {'ok': True}
@router.post('/api/operator/orders/{uid}/cancel')
def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))):
"""A paid order leaves the board but keeps its payment and history. Nothing
is refunded here (that is done at the provider); Tiny is told, so the
order is cancelled there too while it was not invoiced (app/tiny.py)."""
with db.connect() as c:
row = c.execute('''UPDATE dtf_local.orders SET cancelled_at=now(), cancelled_by=%s, cancel_reason=%s,
version=version+1, updated_at=now() WHERE id=%s AND cancelled_at IS NULL RETURNING *''',
(user, body.note, uid)).fetchone()
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()
enqueue(c, f'{uid}:cancelled:tiny', 'tiny',
{'order_id': str(uid), 'number': row['number'], 'event': 'cancelled', 'reason': body.note,
'order': row['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')})
audit('order_cancelled', order=row['number'], operator=user)
return {'ok': True}
class MachineChoice(StrictModel):
machine_id: UUID | None = None
@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 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()
if not current:
raise HTTPException(404, 'Pedido não encontrado.')
proof.require_unlocked(c, current)
if current['cancelled_at'] or current['state'] not in ('rec', 'tra', 'cor'):
raise HTTPException(409, 'A máquina não muda depois que o card entrou em Imprimindo.')
if body.machine_id:
target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone()
if not target or not target['active']:
raise HTTPException(404, 'Máquina não encontrada ou desativada.')
if machines.product_family(current) not in target['products']:
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
linked = c.execute('''SELECT id,state,machine_id,proof_result FROM dtf_local.orders
WHERE parent_id=%s AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone()
if linked and linked['proof_result'] == 'ok' and linked['machine_id'] and body.machine_id != linked['machine_id']:
raise HTTPException(409, 'O pedido precisa ficar na mesma máquina que imprimiu a prova.')
row = c.execute('''UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=%s WHERE id=%s
RETURNING number, state, cancelled_at''', (body.machine_id, body.machine_id is not None, uid)).fetchone()
if current['parent_id']:
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s',
(body.machine_id, body.machine_id is not None, current['parent_id']))
elif linked and linked['proof_result'] is None and linked['state'] in ('rec', 'tra', 'cor'):
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s',
(body.machine_id, body.machine_id is not None, linked['id']))
audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user)
return {'ok': True}
@router.post('/api/operator/orders/{uid}/contraction')
def choose_contraction(uid: UUID, body: Contraction, user=Depends(can('produce'))):
"""The contraction class of an item (Dropstar, 2026-10-30): the browser's
measure comes prefilled, and whoever prepares the art may change it until
the order prints. Both stay: the measure in the snapshot, the choice here."""
with db.connect() as c:
row = c.execute('SELECT id,parent_id,proof_ok_at,snapshot,state,cancelled_at,contraction FROM dtf_local.orders WHERE id=%s FOR UPDATE',
(uid,)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
proof.require_unlocked(c, row)
if body.item_index >= len(row['snapshot']['items']):
raise HTTPException(422, 'Item não encontrado no pedido.')
# Printing, the class still changes while the item's files wait to go
# into the hot folder: the class is its folder (item 10).
written = row['state'] == 'imp' and c.execute('''SELECT 1 FROM dtf_local.hot_parts WHERE order_id=%s
AND item_index=%s AND state NOT IN ('queued','gone') LIMIT 1''', (uid, body.item_index)).fetchone()
if row['cancelled_at'] or row['state'] not in ('rec', 'tra', 'cor', 'imp') or written:
raise HTTPException(409, 'A contração muda até o arquivo ir para a hot folder da máquina.')
chosen = dict(row['contraction'] or {})
key = str(body.item_index)
if body.value is None:
chosen.pop(key, None)
else:
chosen[key] = {'class': body.value, 'by': user, 'at': datetime.now(timezone.utc).isoformat()}
c.execute('UPDATE dtf_local.orders SET contraction=%s WHERE id=%s', (Jsonb(chosen), uid))
audit('order_contraction_chosen', order=str(uid), item=body.item_index, value=body.value or '', operator=user)
return {'ok': True, 'contraction': chosen}
class ContactWait(StrictModel):
waiting: bool
note: str = Field(default='', max_length=500)
@router.post('/api/operator/orders/{uid}/contact')
def contact(uid: UUID, body: ContactWait, user=Depends(can('produce'))):
"""Mark an order as waiting for a word with the customer, with what has to
be agreed, or clear the mark once that is done. The stage does not change
and the customer is not told."""
note = ' '.join(body.note.split())
if body.waiting and len(note) < 3:
raise HTTPException(422, 'Escreva o que precisa ser combinado com o cliente.')
with db.connect() as c:
row = c.execute('''UPDATE dtf_local.orders SET contact_since=CASE WHEN %s THEN now() END,
contact_by=CASE WHEN %s THEN %s END, contact_note=CASE WHEN %s THEN %s END
WHERE id=%s AND cancelled_at IS NULL RETURNING number''',
(body.waiting, body.waiting, user, body.waiting, note, uid)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
# The wait's history, for the time figures that leave it out (D-38).
c.execute('UPDATE dtf_local.contact_waits SET ended_at=now() WHERE order_id=%s AND ended_at IS NULL', (uid,))
if body.waiting:
c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (uid,))
audit('order_contact_waiting' if body.waiting else 'order_contact_done', order=row['number'], operator=user)
return {'ok': True}
class ProofAnswer(StrictModel):
result: Literal['ok', 'rejected']
reason: str = Field(default='', max_length=500)
@router.post('/api/operator/orders/{uid}/proof-answer')
def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
"""The answer to a proof card in Revisão (Dropstar, 2026-11-03): Prova OK
puts its order in the queue; Prova reprovada, with its reason, sends the
order back to Arte recebida. Either way the card closes."""
reason = ' '.join(body.reason.split())
if body.result == 'rejected' and len(reason) < 3:
raise HTTPException(422, 'Diga por que a prova foi reprovada.')
with db.connect() as c:
card = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not card or not card.get('parent_id'):
raise HTTPException(404, 'Card de prova não encontrado.')
if card['cancelled_at'] or card['proof_result'] or card['state'] != 'rev':
raise HTTPException(409, 'A prova é respondida em Revisão, uma vez.')
parent = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (card['parent_id'],)).fetchone()
c.execute('''UPDATE dtf_local.orders SET proof_result=%s, proof_decided_at=now(), proof_decided_by=%s,
proof_reason=%s, state='fin', version=version+1, updated_at=now() WHERE id=%s''',
(body.result, user, reason or None, uid))
label = 'Prova OK' if body.result == 'ok' else 'Prova reprovada: ' + reason
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':
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'],))
c.execute('''UPDATE dtf_local.orders SET state='rec', proof_ok_at=NULL, proof_ok_by=NULL, queue_key=NULL,
machine_id=NULL,machine_chosen=false,
version=version+1, updated_at=now() WHERE id=%s''', (parent['id'],))
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
VALUES(%s,%s,'rec',%s,%s)''', (parent['id'], parent['state'], user, label))
# The proof answer is the contact with the customer: the old
# "Aguardando contato" mark has done its job either way (0.1).
c.execute('''UPDATE dtf_local.orders SET contact_since=NULL, contact_by=NULL, contact_note=NULL
WHERE id=%s''', (parent['id'],))
c.execute('UPDATE dtf_local.contact_waits SET ended_at=now() WHERE order_id=%s AND ended_at IS NULL',
(parent['id'],))
audit('order_proof_answered', order=parent['number'], result=body.result, operator=user)
return {'ok': True}
@router.post('/api/operator/orders/{uid}/proof-card')
def new_proof_card(uid: UUID, user=Depends(can('produce'))):
"""A new proof card for an order whose proof was rejected, or that has
none yet (an order from before the cards)."""
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row or row.get('parent_id'):
raise HTTPException(404, 'Pedido não encontrado.')
if row['cancelled_at'] or row['state'] not in ('rec', 'tra') or row['proof_ok_at'] or proof.open_child(c, uid):
raise HTTPException(409, 'Este pedido já tem uma prova em andamento ou aprovada.')
child = proof.create_child(c, row)
if not child:
raise HTTPException(409, 'Este pedido não leva prova.')
audit('order_proof_card', order=row['number'], operator=user)
return {'ok': True, 'id': child['id'], 'number': child['number']}
@router.post('/api/operator/orders/{uid}/proof')
def proof_ok(uid: UUID, user=Depends(can('print'))):
"""An order from before the proof cards: the print room checked the
proof, and the order may reach Finalizado."""
with db.connect() as c:
if proof.open_child(c, uid):
raise HTTPException(409, 'Este pedido tem um card de prova: a resposta vai nele.')
row = c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1
WHERE id=%s AND cancelled_at IS NULL AND state<>'fin' RETURNING number, version''', (user, uid)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
audit('order_proof_ok', order=row['number'], operator=user)
return {'ok': True, 'version': row['version']}
def paid_with(c, order):
"""How the order was paid, for its receipt: pix, card, cash, credit, or
'teste' for an operator's test order."""
paid = order.get('payment') or {}
if paid.get('provider') == 'teste':
return 'teste'
if paid.get('provider') == payments.MANUAL_PROVIDER:
return paid.get('method')
row = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved'
ORDER BY created_at DESC LIMIT 1''', (order['quote_id'],)).fetchone()
return row and row['method']
@router.get('/api/operator/orders/{uid}/receipt')
def pickup_receipt(uid: UUID, user=Depends(operator)):
"""The pickup receipt's PDF (item 14), for the folder to save or someone
to print again."""
with db.connect() as c:
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
if not receipt.is_pickup(order['snapshot']):
raise HTTPException(409, 'Só pedido de retirada tem recibo.')
body = receipt.render(order, paid_with(c, order))
return Response(body, media_type='application/pdf',
headers={'Content-Disposition': f'inline; filename="{receipt.file_name(order)}"'})
@router.post('/api/operator/orders/{uid}/receipt/claim')
def claim_receipt(uid: UUID, user=Depends(can('print'))):
"""One computer's folder takes the receipt to save: once, so the counter's
queue never prints it twice."""
with db.connect() as c:
row = c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=now(), receipt_saved_by=%s
WHERE id=%s AND receipt_due_at IS NOT NULL AND receipt_saved_at IS NULL AND cancelled_at IS NULL
RETURNING number''', (user, uid)).fetchone()
if not row:
raise HTTPException(409, 'Este recibo já foi salvo.')
audit('pickup_receipt_saved', order=row['number'], operator=user)
return {'ok': True}
@router.post('/api/operator/orders/{uid}/receipt/release')
def release_receipt(uid: UUID, user=Depends(can('print'))):
"""The folder could not save the receipt it took: another computer may."""
with db.connect() as c:
c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=NULL, receipt_saved_by=NULL
WHERE id=%s AND receipt_saved_by=%s''', (uid, user))
return {'ok': True}
def pickup_order(c, uid, lock=False):
"""An order in Finalizado to be picked up, or why it cannot be marked."""
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s' + (' FOR UPDATE' if lock else ''), (uid,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
if order['cancelled_at'] or order['state'] != 'fin' or not receipt.is_pickup(order['snapshot']):
raise HTTPException(409, 'Só um pedido de retirada em Finalizado é marcado como retirado.')
if order['picked_up_at']:
raise HTTPException(409, 'Este pedido já foi marcado como retirado.')
return order
@router.post('/api/operator/orders/{uid}/pickup-uploads')
def begin_pickup_photo(uid: UUID, body: UploadStart, user=Depends(can('deliver'))):
"""The photo of the signed receipt, sent before marking the order."""
with db.connect() as c:
pickup_order(c, uid)
return begin_upload(body, session_id=operator_identity(user))
class PickedUp(StrictModel):
photo: UUID | None = None
PHOTO_TYPES = ('.jpg', '.jpeg', '.png', '.webp', '.heic', '.heif')
@router.post('/api/operator/orders/{uid}/picked-up')
def picked_up(uid: UUID, body: PickedUp, user=Depends(can('deliver'))):
""""Retirado": when and who handed the order over, and the photo of the
signed receipt when there is one (item 14). Finalizado means ready; this
closes the cycle. The photo is kept 30 days, as the order's files are."""
with db.connect() as c:
order = pickup_order(c, uid, lock=True)
if body.photo:
photo = upload_row(c, body.photo, operator_identity(user), lock=True)
if not photo['complete']:
raise HTTPException(409, 'Espere a foto terminar de enviar.')
if not photo['name'].lower().endswith(PHOTO_TYPES):
raise HTTPException(422, 'A foto do recibo precisa ser uma imagem (JPG, PNG, WebP ou HEIC).')
require_clean(photo)
c.execute("UPDATE dtf_local.uploads SET expires_at=now()+interval '30 days' WHERE id=%s", (body.photo,))
row = c.execute('''UPDATE dtf_local.orders SET picked_up_at=now(), picked_up_by=%s, picked_up_photo=%s
WHERE id=%s RETURNING picked_up_at''', (user, body.photo, uid)).fetchone()
audit('order_picked_up', order=order['number'], operator=user, photo=bool(body.photo))
return {'ok': True, 'picked_up_at': row['picked_up_at']}
class QueuePlace(StrictModel):
"""Where a dragged card lands: between two orders of its column, either
of them absent at the top or the bottom."""
after: UUID | None = None
before: UUID | None = None
QUEUE_KEY = 'COALESCE(queue_key, extract(epoch FROM created_at))'
@router.post('/api/operator/orders/{uid}/queue')
def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(operator)):
"""An order's place in its column: by default its payment time; dragged,
halfway between the orders it was dropped between. It neither changes the
order's stage nor counts as activity (the stalled clock keeps running)."""
if not body.after and not body.before:
raise HTTPException(422, 'Informe entre quais pedidos ele fica.')
with db.connect() as c:
row = c.execute('SELECT id,parent_id,proof_ok_at,state,machine_id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Order not found')
proof.require_unlocked(c, row)
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 (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 = {}
for side in ('after', 'before'):
other = getattr(body, side)
if other:
near = c.execute(f'SELECT state, {QUEUE_KEY} AS key FROM dtf_local.orders WHERE id=%s', (other,)).fetchone()
if not near or near['state'] != row['state']:
raise HTTPException(409, 'Os pedidos mudaram de etapa. Clique em Atualizar.')
keys[side] = float(near['key'])
if 'after' in keys and 'before' in keys:
key = (keys['after'] + keys['before']) / 2
elif 'after' in keys:
key = keys['after'] + 60
else:
key = keys['before'] - 60
c.execute('UPDATE dtf_local.orders SET queue_key=%s WHERE id=%s', (key, uid))
audit('order_queue_moved', order=str(uid), operator=user)
return {'ok': True, 'queue_key': key}
@router.post('/api/operator/orders/{uid}/move')
def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
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()
if not row:
raise HTTPException(404, 'Order not found')
if body.version != row['version']:
raise HTTPException(409, 'O pedido mudou. Clique em Atualizar.')
if row.get('cancelled_at'):
raise HTTPException(409, 'Pedido cancelado.')
proof.require_unlocked(c, row)
if body.state == row['state']:
return row
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(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():
raise HTTPException(422, 'Informe o motivo da correção.')
if back and not body.reason.strip():
raise HTTPException(422, 'Informe por que o pedido está voltando de etapa.')
# The machine of this session takes a card when it is pulled. A proof
# and its parent must keep the same physical machine.
account = request.state.operator
session_machine = account['machine']
pulling = row['state'] == 'tra' and body.state == 'imp'
# 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']:
raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.')
if pulling:
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 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']:
raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.')
if machines.product_family(row) not in target['products']:
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
# The machine's sheet speaks between one file and the next, never in
# the middle: a blocking alert stops this card here (app/machine_log.py).
blocking = [alert for alert in machine_log.alerts(c, chosen) if alert['blocking']]
if blocking:
raise HTTPException(409, 'Antes do próximo arquivo: ' + blocking[0]['text'])
linked = c.execute('''SELECT machine_id FROM dtf_local.orders WHERE parent_id=%s
AND proof_result='ok' AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone()
if linked and linked['machine_id'] and chosen != linked['machine_id']:
raise HTTPException(409, 'Puxe o pedido na mesma máquina que imprimiu a prova.')
row['machine_id'] = chosen
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s', (chosen, uid))
if row['parent_id']:
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s',
(chosen, row['parent_id']))
# Arte conferida is the queue: what enters it has its final files approved.
if body.state in ('tra','imp'):
coverage = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
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 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.')
# 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':
raise HTTPException(409, 'A prova termina com Prova OK ou Prova reprovada, não em Finalizado.')
if body.state == 'imp' and proof.waiting(c, row):
raise HTTPException(409, 'Aguardando prova: o pedido entra na fila com Prova OK no card da prova.')
if body.state == 'fin' and not row.get('parent_id') and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']:
raise HTTPException(409, 'Falta a prova: confira a prova impressa e marque Prova OK antes de finalizar.')
# Above 1 m the review photo is the evidence the sheet was checked; a
# proof card is no sale and skips this (app/reviews.py).
if (body.state == 'fin' and not back and not row.get('parent_id')
and reviews.required(row['snapshot']) and not reviews.has_photo(c, uid)):
raise HTTPException(409, 'Pedido acima de 1 m: tire a foto da revisão antes de finalizar.')
if body.state == 'cor':
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,))
# Who moved it, and on which machine: the one it goes to print on, or
# else the mover's.
machine_name = (session_machine or {}).get('name')
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')
# 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.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(),
queue_key=CASE WHEN %s='tra' AND parent_id IS NOT NULL THEN -extract(epoch FROM now()) ELSE NULL END,
receipt_due_at=CASE WHEN %s THEN COALESCE(receipt_due_at, now()) ELSE receipt_due_at END
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).
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,
and for orders paid before the generator existed."""
with db.connect() as c:
row = c.execute('SELECT id,parent_id,proof_ok_at,snapshot,state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Order not found')
proof.require_unlocked(c, row)
if row['state'] not in ('rec','tra'):
raise HTTPException(409, 'Print files are generated only before the order is queued')
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1", (uid,)).fetchone():
raise HTTPException(409, 'A customer correction replaced the original artwork; prepare the final file by hand')
if row['parent_id']:
manual = c.execute("SELECT item_index FROM dtf_local.print_files WHERE order_id=%s AND status='manual'",
(uid,)).fetchall()
for stuck in manual:
original_index = row['snapshot']['items'][stuck['item_index']]['proof_parent_item_index']
prepared = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE order_id=%s
AND item_index=%s AND kind='final' AND active LIMIT 1''',
(row['parent_id'], original_index)).fetchone()
if not prepared:
raise HTTPException(409, 'Prepare e aprove o PNG completo no pedido pai antes de gerar a prova de novo.')
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}

164
app/api/operator/quotes.py Normal file
View File

@@ -0,0 +1,164 @@
"""Quotes: review, search, test and outside-paid orders, discard."""
import re
from datetime import datetime
from typing import Literal
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import Field
from ... import payments, quote_review
from ...core import db
from ...core.auth import audit, can, operator
from ...core.models import Review, StrictModel
from ...runtime import quote_views
from .board import with_print_files
from .common import (LIVE_QUOTE, MODES, company_names, customer_match, like, numeric,
thumbnails)
router = APIRouter()
@router.get('/api/operator/quotes')
def quote_page(kind: Literal['pending','approved'], before_created_at: datetime | None = None,
before_id: UUID | None = None, offset: int = Query(default=0, ge=0),
limit: int = Query(default=50, ge=1, le=100),
q: str | None = Query(default=None, max_length=100),
product: Literal['textil','uv'] | None = None, layout: Literal['folha','avulsa'] | None = None,
flag: Literal['ressalva'] | None = None, user=Depends(operator)):
"""Unpaid quotes, newest first: by cursor, or by page (offset) with a total;
filtered by customer, product, layout and an accepted resolution warning."""
if (before_created_at is None) != (before_id is None):
raise HTTPException(422, 'Both quote cursor fields are required')
clauses = ['o.id IS NULL', LIVE_QUOTE, 'q.approved IS NULL' if kind == 'pending' else 'q.approved IS NOT NULL']
params = []
if q and q.strip():
sql, values = customer_match('q.draft', q)
clauses.append(sql); params += values
if product or layout:
modes = set.intersection(*(MODES[k] for k in (product, layout) if k))
clauses.append("EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i WHERE i->>'mode'=ANY(%s))")
params.append(sorted(modes))
if flag:
clauses.append("EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i WHERE i->>'quality_status'='warning')")
where = ' AND '.join(clauses)
cursor = 'AND (q.created_at,q.id)<(%s,%s)' if before_created_at else ''
skip = 0 if before_created_at else offset
page = params + ([before_created_at, before_id] if before_created_at else []) + [limit+1, skip]
with db.connect() as c:
rows = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE {where} {cursor}
ORDER BY q.created_at DESC,q.id DESC LIMIT %s OFFSET %s''', page).fetchall()
total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE {where}''', params).fetchone()['n']
quotes = quote_views(c, rows[:limit])
return {'quotes': quotes, 'has_more': len(rows)>limit, 'total': total,
'thumbnails': thumbnails(c, quotes), 'names': company_names(c, quotes)}
@router.get('/api/operator/search')
def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator)):
"""One search over orders (any stage) and unpaid quotes: customer e-mail,
CNPJ or WhatsApp, the delivery recipient, or the order number."""
match, params = customer_match('snapshot', q)
digits = numeric(q)
sql = match + " OR lower(coalesce(snapshot->'destination'->>'recipient','')) LIKE %s"
params.append(like(q.strip().lower()))
if digits and len(digits) <= 9:
sql += ' OR number=%s'
params.append(int(digits))
# The code a customer reads out (the id's first characters, see order_code).
code = q.strip().lstrip('#').lower()
if 6 <= len(code) <= 12 and re.fullmatch(r'[0-9a-f]+', code):
sql += " OR replace(id::text,'-','') LIKE %s"
params.append(code + '%')
quote_match, quote_params = customer_match('q.draft', q)
with db.connect() as c:
# Real orders: a proof card is found through its order (app/proof.py).
orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE ({sql}) AND parent_id IS NULL
ORDER BY created_at DESC LIMIT 8''', params).fetchall()
rows = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND {LIVE_QUOTE} AND {quote_match}
ORDER BY q.created_at DESC LIMIT 8''', quote_params).fetchall()
orders = with_print_files(c, orders)
quotes = quote_views(c, rows)
return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
'names': company_names(c, orders, quotes)}
@router.post('/api/operator/quotes/{uid}/approve')
def approve(uid: UUID, body: Review, user=Depends(can('manage'))):
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Quote not found')
return quote_review.approve(c, row, body.items, user)
@router.post('/api/operator/quotes/{uid}/test-order')
def test_order(uid: UUID, user=Depends(can('manage'))):
"""An order for an approved quote without payment, to try the Kanban,
files and print flow in production. Marked TEST on the board, never sent
to Tiny or WhatsApp, and audited."""
with db.connect() as c:
try:
quote = payments.approved_quote(c, uid)
except payments.PaymentRefused as refusal:
raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal))
receipt = {'provider': payments.TEST_PROVIDER, 'id': f'teste-{uid}', 'status': 'paid',
'total_cents': quote['approved']['total_cents'], 'operator': user}
order, created = payments.create_order(c, quote, receipt, 'site')
if created:
audit('test_order_created', order=str(order['id']), operator=user)
return order
class PaidOutside(StrictModel):
# No defaults (D-35): whoever registers the order says where it came from
# and how it was paid.
origin: Literal['site', 'dropflow', 'atendimento']
method: Literal[payments.OUTSIDE_METHODS]
note: str = Field(default='', max_length=300)
@router.post('/api/operator/quotes/{uid}/register')
def register_order(uid: UUID, body: PaidOutside, user=Depends(can('enter'))):
"""The order for an approved quote paid outside the system (Dropstar's
rule D-35): the team builds the cart on the Site, as a customer would, and
registers it here with its origin and how it was paid. The price is the
quote's, the Site's table price."""
with db.connect() as c:
try:
quote = payments.approved_quote(c, uid)
except payments.PaymentRefused as refusal:
raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal))
receipt = {'provider': payments.MANUAL_PROVIDER, 'method': body.method, 'note': body.note.strip(),
'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
@router.post('/api/operator/quotes/{uid}/discard')
def discard_quote(uid: UUID, user=Depends(can('manage'))):
"""An unpaid quote leaves the Kanban and can no longer be paid. Its files
keep their normal expiry; a payment that still arrives for it is refused
and listed under Pagamentos."""
with db.connect() as c:
# Locked like a payment locks it, so a discard and a payment never cross.
row = c.execute('SELECT id FROM dtf_local.quotes WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Quote not found')
if c.execute('SELECT 1 FROM dtf_local.orders WHERE quote_id=%s', (uid,)).fetchone():
raise HTTPException(409, 'Esta cotação já virou pedido.')
c.execute('UPDATE dtf_local.quotes SET discarded_at=now(), discarded_by=%s WHERE id=%s AND discarded_at IS NULL',
(user, uid))
audit('quote_discarded', quote=str(uid), operator=user)
return {'ok': True}

View File

@@ -0,0 +1,73 @@
"""Rework: its causes, and opening and deciding one (D-02 to D-04)."""
from decimal import Decimal
from typing import Literal
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException
from pydantic import Field
from ...core import db
from ...core.auth import audit, can
from ...core.models import StrictModel
router = APIRouter()
# Rework (Dropstar's rules D-02 to D-04): four causes of the house, each with a
# goal of 0,4% of the film printed (1,6% in all), and the customer's approved
# bad art, recorded apart and outside the goal (D-04).
HOUSE_CAUSES = ('impressao', 'perfil_cor', 'tratamento', 'pedido')
CUSTOMER_CAUSE = 'arte_cliente'
REWORK_GOAL_PERCENT = Decimal('0.4')
class ReworkOpen(StrictModel):
cause: Literal[HOUSE_CAUSES + (CUSTOMER_CAUSE,)]
metres: Decimal = Field(gt=0, le=1000)
note: str = Field(default='', max_length=1000)
class ReworkDecision(StrictModel):
authorized: bool
reason: str = Field(default='', max_length=1000)
@router.post('/api/operator/orders/{uid}/reworks')
def open_rework(uid: UUID, body: ReworkOpen, user=Depends(can('rework'))):
"""Coordination opens a rework with its cause (D-02). There is no way to
change the cause afterwards (D-03)."""
with db.connect() as c:
order = c.execute('SELECT id,number,cancelled_at FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
if order['cancelled_at']:
raise HTTPException(409, 'Pedido cancelado não abre retrabalho.')
# Who printed the sheet: who last sent it to Revisão.
printed = c.execute('''SELECT operator FROM dtf_local.movements WHERE order_id=%s AND to_state='rev'
AND NOT back ORDER BY id DESC LIMIT 1''', (uid,)).fetchone()
row = c.execute('''INSERT INTO dtf_local.reworks(order_id,cause,metres,note,printed_by,opened_by)
VALUES(%s,%s,%s,%s,%s,%s) RETURNING *''',
(uid, body.cause, body.metres, body.note.strip(), printed['operator'] if printed else None,
user)).fetchone()
audit('rework_opened', order=order['number'], cause=body.cause, operator=user)
return row
@router.post('/api/operator/reworks/{rid}/decision')
def decide_rework(rid: int, body: ReworkDecision, user=Depends(can('authorize'))):
"""An Administrador authorizes a rework, and only then it counts, or
declines it with a reason (D-02). Never one they opened themselves."""
reason = body.reason.strip()
if not body.authorized and len(reason) < 3:
raise HTTPException(422, 'Diga por que o retrabalho não foi autorizado.')
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.reworks WHERE id=%s FOR UPDATE', (rid,)).fetchone()
if not row:
raise HTTPException(404, 'Retrabalho não encontrado.')
if row['decided_at']:
raise HTTPException(409, 'Este retrabalho já foi decidido.')
if row['opened_by'] == user:
raise HTTPException(409, 'Quem abriu o retrabalho não pode autorizá-lo.')
row = c.execute('''UPDATE dtf_local.reworks SET authorized=%s, decided_by=%s, decided_at=now(), decline_reason=%s
WHERE id=%s RETURNING *''', (body.authorized, user, None if body.authorized else reason, rid)).fetchone()
audit('rework_decided', rework=rid, authorized=body.authorized, operator=user)
return row

View File

@@ -0,0 +1,49 @@
"""Kanban sign-in and sign-out."""
import hashlib
import secrets
from fastapi import APIRouter, HTTPException, Request, Response
from ...core import db
from ...core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, client_ip,
login_failed, password_matches, throttle)
from ...core.models import OperatorLogin
router = APIRouter()
@router.post('/api/operator/login')
def operator_login(body: OperatorLogin, request: Request, response: Response):
email = body.email
throttle('operator:'+email, request)
with db.connect() as c:
account = c.execute('SELECT * FROM dtf_local.operators WHERE email=%s', (email,)).fetchone()
if not c.execute('SELECT 1 FROM dtf_local.operators WHERE active LIMIT 1').fetchone():
raise HTTPException(503, 'Nenhuma conta de operador configurada.')
# Comparable password work whether or not the account exists or is active.
stored = account['password_hash'] if account else DUMMY_PASSWORD_HASH
matches = password_matches(body.password, stored)
if not account or not account['active'] or not matches:
login_failed('operator:'+email)
audit('operator_login_failed', ip=client_ip(request), operator=email)
raise HTTPException(401, 'E-mail ou senha inválidos.')
token = secrets.token_urlsafe(32)
with db.connect() as c:
previous = hashlib.sha256(request.cookies.get('dtf_operator','').encode()).hexdigest()
c.execute('DELETE FROM dtf_local.operator_sessions WHERE token_hash=%s', (previous,))
c.execute('INSERT INTO dtf_local.operator_sessions(token_hash,username) VALUES(%s,%s)',
(hashlib.sha256(token.encode()).hexdigest(), email))
c.execute('UPDATE dtf_local.operators SET last_login_at=now() WHERE id=%s', (account['id'],))
response.set_cookie('dtf_operator', token, httponly=True, secure=COOKIE_SECURE,
samesite='strict', path='/api/operator', max_age=28800)
audit('operator_login_success', operator=email)
return {'ok': True}
@router.post('/api/operator/logout')
def operator_logout(request: Request, response: Response):
with db.connect() as c:
digest = hashlib.sha256(request.cookies.get('dtf_operator','').encode()).hexdigest()
c.execute('DELETE FROM dtf_local.operator_sessions WHERE token_hash=%s', (digest,))
response.delete_cookie('dtf_operator', path='/api/operator', httponly=True,
secure=COOKIE_SECURE, samesite='strict')
audit('operator_logout')
return {'ok': True}

361
app/api/operator/stats.py Normal file
View File

@@ -0,0 +1,361 @@
"""Números: the production figures and the SQL helpers they share."""
from datetime import date, datetime, timedelta, timezone
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
from .rework import CUSTOMER_CAUSE, HOUSE_CAUSES, REWORK_GOAL_PERCENT
router = APIRouter()
LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date"
# A montador "Interno" or "faturado" order records the table price, not money
# received (Marcus, 2026-11-10): the cash figures leave it out and Números
# shows it in its own block.
NOT_CASH = ('COALESCE(o.payment->>\'method\',\'\') NOT IN '
f"('{payments.INTERNAL_METHOD}','{payments.INVOICED_METHOD}')")
def waited(order, start, end):
"""SQL: the seconds `order` spent in "Aguardando contato" between `start`
and `end`. Dropstar's rule D-38: that wait has no deadline and does not
count in the time figures."""
return f'''COALESCE((SELECT sum(extract(epoch FROM least({end}, COALESCE(w.ended_at, now()))
- greatest({start}, w.started_at))) FROM dtf_local.contact_waits w
WHERE w.order_id={order} AND w.started_at<{end} AND COALESCE(w.ended_at, now())>{start}), 0)'''
# Longest period one request may cover: a year and a day, for a year against the last.
STATS_MAX_DAYS = 366
def stats_period(days, start, end):
"""The local days a request covers: the last `days`, or start to end."""
today = datetime.now(timezone(timedelta(hours=-3))).date()
if start is None and end is None:
days = days or 30
return today - timedelta(days=days - 1), today
if start is None or end is None:
raise HTTPException(422, 'Informe a data inicial e a final.')
if start > end:
raise HTTPException(422, 'A data inicial é depois da final.')
if (end - start).days + 1 > STATS_MAX_DAYS:
raise HTTPException(422, f'O período vai até {STATS_MAX_DAYS} dias.')
return start, end
@router.get('/api/operator/stats')
def production_stats(days: int | None = Query(default=None, ge=7, le=365), start: date | None = None,
end: date | None = None, user=Depends(operator)):
"""Production numbers from what the board already records: orders paid in
the period, how long each stage holds an order, what each machine printed,
and what is waiting now. The period is the last `days`, or start to end."""
start, end = stats_period(days, start, end)
period = (start, end)
within = f"{LOCAL_DAY} BETWEEN %s AND %s"
metres = "(SELECT COALESCE(sum((i->>'billed_metres')::numeric),0) FROM jsonb_array_elements(o.snapshot->'items') i)"
with db.connect() as c:
limit_rows = c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall()
limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']}
for row in limit_rows}
total = c.execute(f'''SELECT count(*) AS orders,
COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents,
COALESCE(sum({metres}),0) AS metres,
count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.movements m WHERE m.order_id=o.id
AND m.to_state='cor' AND NOT m.back)) AS corrected
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}''', period).fetchone()
# Approved quotes of the period nobody paid (front 9).
unpaid_figures = unpaid.figures(c, start, end)
daily = {row['day']: row for row in c.execute(f'''SELECT {LOCAL_DAY} AS day, count(*) AS orders,
COALESCE(sum({metres}),0) AS metres FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}
GROUP BY 1''', period).fetchall()}
# Each order's stages as spans: from entering a stage to the next move.
spans = f'''WITH events AS (
SELECT o.id, 'rec' AS state, o.created_at AS at FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}
UNION ALL
SELECT m.order_id, m.to_state, m.created_at FROM dtf_local.movements m
JOIN dtf_local.orders o ON o.id=m.order_id WHERE {REAL_ORDER} AND {within})
SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events'''
# Orders, not passages: an order sent back counts once, its passages apart,
# and its time in a stage is the sum of its passages. Otherwise an order
# that came back twice reads as three quick passages, not one slow order.
stages = c.execute(f'''SELECT state, count(*) AS orders, sum(passages)::int AS passages,
avg(seconds) / 3600 AS average_hours
FROM (SELECT id, state, count(*) AS passages,
sum(extract(epoch FROM until-at) - {waited('s.id', 's.at', 's.until')}) AS seconds
FROM ({spans}) s WHERE until IS NOT NULL GROUP BY id, state) per_order
GROUP BY state''', period + period).fetchall()
lead = c.execute(f'''SELECT count(*) AS orders, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM
f.at - o.created_at) - {waited('o.id', 'o.created_at', 'f.at')}) / 3600 AS median_hours FROM dtf_local.orders o
JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state='fin') f
ON f.at IS NOT NULL
WHERE {REAL_ORDER} AND {within}''', period).fetchone()
# What waits now, however old, and since when in its stage.
waiting = c.execute(f'''SELECT o.state, count(*) AS orders, max(extract(epoch FROM now() - COALESCE(
(SELECT max(m.created_at) FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state=o.state),
o.created_at))) / 3600 AS oldest_hours
FROM dtf_local.orders o WHERE {REAL_ORDER} AND o.state<>'fin' GROUP BY o.state''').fetchall()
# Passages past each stage's acceptable time (front 11), in the
# selected period and today.
# Each passage carries whether its order paid for treatment, which only
# Art received counts (front 5).
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->'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)
# Rework of the period (D-02 to D-04): the authorized ones, by the day
# they were opened, over the film the machines printed in it.
not_test = "COALESCE(o.payment->>'provider','') <> 'teste'"
opened = "(r.opened_at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s"
redone = {row['cause']: row for row in c.execute(f'''SELECT r.cause, sum(r.metres) AS metres,
count(DISTINCT r.order_id) AS orders FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id
WHERE r.authorized AND {not_test} AND {opened} GROUP BY r.cause''', period).fetchall()}
# The house's rework enters the pay of who printed it (D-02).
by_printer = c.execute(f'''SELECT COALESCE({person('r.printed_by')}, 'Sem registro') AS who,
sum(r.metres) AS metres FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id
WHERE r.authorized AND r.cause<>%s AND {not_test} AND {opened} GROUP BY 1 ORDER BY 2 DESC''',
(CUSTOMER_CAUSE,) + period).fetchall()
undecided = c.execute(f'''SELECT r.id, r.order_id, o.number, r.cause, r.metres, r.opened_at,
{person('r.opened_by')} AS opened_name FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id
WHERE r.decided_at IS NULL AND {not_test} ORDER BY r.opened_at''').fetchall()
# Arte tratada, for the designer's productivity: orders of the period
# whose final someone prepared, by who approved it (any version).
treated = c.execute(f'''SELECT COALESCE(op.name, f.created_by) AS who, count(DISTINCT f.order_id) AS orders
FROM dtf_local.order_files f JOIN dtf_local.orders o ON o.id=f.order_id
LEFT JOIN dtf_local.operators op ON op.email=f.created_by
WHERE {REAL_ORDER} AND {within} AND {TREATED} GROUP BY 1 ORDER BY 2 DESC, 1''', period).fetchall()
treated_orders = c.execute(f'''SELECT count(DISTINCT f.order_id) AS n FROM dtf_local.order_files f
JOIN dtf_local.orders o ON o.id=f.order_id WHERE {REAL_ORDER} AND {within} AND {TREATED}''',
period).fetchone()['n']
# Each way in apart (D-21): what came from where, and how long it took
# from payment to Finalizado, Aguardando contato left out as above.
origins = {row['origin']: row for row in c.execute(f'''SELECT o.origin, count(*) AS orders,
COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents,
COALESCE(sum({metres}),0) AS metres,
count(f.at) AS finished, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM
f.at - o.created_at) - {waited('o.id', 'o.created_at', 'f.at')}) / 3600 AS median_hours
FROM dtf_local.orders o
LEFT JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m
WHERE m.order_id=o.id AND m.to_state='fin') f ON true
WHERE {REAL_ORDER} AND {within} GROUP BY o.origin''', period).fetchall()}
# The table price of the montador's Interno and Venda orders, counted
# apart from the money received above (front 7a.3).
price_table = {row['method']: row for row in c.execute(f'''SELECT o.payment->>'method' AS method,
count(*) AS orders, COALESCE(sum({metres}),0) AS metres,
COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}
AND o.payment->>'method' IN (%s,%s) GROUP BY 1''',
period + (payments.INTERNAL_METHOD, payments.INVOICED_METHOD)).fetchall()}
# Coupons used by the period's paid orders (front 8.3): what each code
# brought in orders, billed metres, discount and money received.
coupons_used = c.execute(f'''SELECT o.snapshot->'coupon'->>'id' AS id,
o.snapshot->'coupon'->>'code' AS code, count(*) AS orders,
COALESCE(sum({metres}),0) AS metres,
COALESCE(sum((o.snapshot->'coupon'->>'discount_cents')::bigint),0) AS discount_cents,
COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents
FROM dtf_local.orders o
WHERE {REAL_ORDER} AND {within} AND o.snapshot->'coupon'->>'id' IS NOT NULL
GROUP BY 1,2 ORDER BY orders DESC, code''', period).fetchall()
# Speed (item 0.12): the browser's marks on the way to a quote, the
# Prumo's print generation and the time from payment event to card.
site_speed = c.execute(f'''WITH samples AS (
SELECT (o.snapshot->'timings'->>'page_ms')::numeric AS page_ms,
(o.snapshot->'timings'->>'upload_ms')::numeric AS upload_ms,
(o.snapshot->'timings'->>'upload_bytes')::numeric AS upload_bytes,
(o.snapshot->'timings'->>'analysis_ms')::numeric AS analysis_ms,
(o.snapshot->'timings'->>'montage_ms')::numeric AS montage_ms
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within})
SELECT
avg(page_ms) AS page_avg,
percentile_cont(0.95) WITHIN GROUP (ORDER BY page_ms) AS page_p95, count(page_ms) AS page_n,
avg((upload_ms/1000.0)/(upload_bytes/1048576.0))
FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_avg,
percentile_cont(0.95) WITHIN GROUP (ORDER BY (upload_ms/1000.0)/(upload_bytes/1048576.0))
FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_p95,
count(*) FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_n,
avg(analysis_ms) AS analysis_avg,
percentile_cont(0.95) WITHIN GROUP (ORDER BY analysis_ms) AS analysis_p95, count(analysis_ms) AS analysis_n,
avg(montage_ms) AS montage_avg,
percentile_cont(0.95) WITHIN GROUP (ORDER BY montage_ms) AS montage_p95, count(montage_ms) AS montage_n
FROM samples''', period).fetchone()
print_speed = c.execute(f'''WITH samples AS (
SELECT extract(epoch FROM (p.finished_at-p.created_at)) AS seconds,
COALESCE((o.snapshot->'items'->p.item_index->>'metres')::numeric,
(o.snapshot->'items'->p.item_index->>'billed_metres')::numeric, 0) AS metres
FROM dtf_local.print_files p JOIN dtf_local.orders o ON o.id=p.order_id
WHERE {REAL_ORDER} AND {within} AND p.status='ready' AND p.finished_at IS NOT NULL
AND p.item_index < jsonb_array_length(o.snapshot->'items'))
SELECT avg(seconds) AS avg_s,
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n,
avg(seconds/NULLIF(metres/10,0))
FILTER (WHERE metres>0) AS per10_avg,
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds/NULLIF(metres/10,0))
FILTER (WHERE metres>0) AS per10_p95,
count(*) FILTER (WHERE metres>0) AS per10_n
FROM samples''', period).fetchone()
card_speed = c.execute(f'''WITH samples AS (
SELECT extract(epoch FROM (o.created_at - min(e.received_at))) AS seconds
FROM dtf_local.orders o JOIN dtf_local.payment_events e ON e.reference=o.quote_id::text
WHERE {REAL_ORDER} AND {within} GROUP BY o.id)
SELECT avg(seconds) AS avg_s,
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n
FROM samples WHERE seconds >= 0''', period).fetchone()
today = datetime.now(timezone(timedelta(hours=-3))).date()
late = {state: {'count': 0, 'today': 0} for state in ('rec', 'tra', 'imp', 'rev', 'fin')}
for row in late_rows:
limit = limits.get(row['state'])
if not limit:
continue
hours = float(limit['hours'])
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:
late[row['state']]['today'] += 1
series = []
for offset in range((end - start).days + 1):
day = start + timedelta(days=offset)
row = daily.get(day)
series.append({'day': day.isoformat(), 'orders': row['orders'] if row else 0,
'metres': float(row['metres']) if row else 0.0})
hours = lambda value: round(float(value), 1) if value is not None else None
return {'days': len(series), 'start': start.isoformat(), 'end': end.isoformat(),
'orders': total['orders'], 'cents': int(total['cents']), 'metres': float(total['metres']),
'corrected': total['corrected'], 'daily': series,
'treated': {'orders': treated_orders, 'by': [{'who': row['who'], 'orders': row['orders']} for row in treated]},
'origins': [{'origin': name, 'orders': origins[name]['orders'] if name in origins else 0,
'cents': int(origins[name]['cents']) if name in origins else 0,
'metres': float(origins[name]['metres']) if name in origins else 0.0,
'finished': origins[name]['finished'] if name in origins else 0,
'median_hours': hours(origins[name]['median_hours']) if name in origins else None}
for name in ORIGINS],
'unpaid': unpaid_figures,
'price_table': [{'method': method,
'orders': price_table[method]['orders'] if method in price_table else 0,
'metres': float(price_table[method]['metres']) if method in price_table else 0.0,
'cents': int(price_table[method]['cents']) if method in price_table else 0}
for method in (payments.INVOICED_METHOD, payments.INTERNAL_METHOD)],
'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])},
'stage_limits': limits, 'late': late,
'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'],
'average_hours': hours(row['average_hours'])} for row in stages},
'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting},
'speed': speed_figures(site_speed, print_speed, card_speed),
'machines': printed, 'rework': rework_figures(printed, redone, by_printer, undecided),
'coupons': [{'id': row['id'], 'code': row['code'], 'orders': row['orders'],
'metres': float(row['metres']), 'discount_cents': int(row['discount_cents']),
'cents': int(row['cents'])} for row in coupons_used]}
def speed_figures(site, generation, card):
"""Números' speed block: average and slow-case p95, in seconds per unit."""
def pair(avg, p95, n, scale=1):
return {'average': round(float(avg)/scale, 2) if avg is not None else None,
'p95': round(float(p95)/scale, 2) if p95 is not None else None,
'samples': int(n or 0)}
return [
{'key': 'page', 'label': 'Abrir o montador', 'unit': 's',
**pair(site['page_avg'], site['page_p95'], site['page_n'], 1000)},
{'key': 'upload', 'label': 'Subir o arquivo', 'unit': 's/MB',
**pair(site['upload_avg'], site['upload_p95'], site['upload_n'])},
{'key': 'analysis', 'label': 'Conferência do Prumo', 'unit': 's',
**pair(site['analysis_avg'], site['analysis_p95'], site['analysis_n'], 1000)},
{'key': 'montage', 'label': 'Montagem das avulsas', 'unit': 's',
**pair(site['montage_avg'], site['montage_p95'], site['montage_n'], 1000)},
{'key': 'print', 'label': 'Gerar arquivo final (10 m)', 'unit': 's',
**pair(generation['per10_avg'], generation['per10_p95'], generation['per10_n'])},
{'key': 'card', 'label': 'Card em Arte recebida', 'unit': 's',
**pair(card['avg_s'], card['p95_s'], card['n'])},
]
def rework_figures(printed, redone, by_printer, undecided):
"""Números' rework: per cause, the metres redone over the film printed,
against the goal; the house's total against four times it."""
film = Decimal(str(sum(m['metres'] for m in printed)))
share = lambda metres: float(round(100 * metres / film, 2)) if film else None
causes = []
for cause in HOUSE_CAUSES + (CUSTOMER_CAUSE,):
row = redone.get(cause)
metres = Decimal(row['metres']) if row else Decimal(0)
causes.append({'cause': cause, 'metres': float(metres), 'orders': row['orders'] if row else 0,
'percent': share(metres)})
house = sum(Decimal(str(c['metres'])) for c in causes if c['cause'] != CUSTOMER_CAUSE)
return {'film_metres': float(film), 'goal_percent': float(REWORK_GOAL_PERCENT),
'house': {'metres': float(house), 'percent': share(house),
'goal_percent': float(REWORK_GOAL_PERCENT * len(HOUSE_CAUSES))},
'causes': causes,
'by_printer': [{'who': row['who'], 'metres': float(row['metres'])} for row in by_printer],
'pending': [{'id': row['id'], 'order_id': str(row['order_id']), 'number': row['number'],
'cause': row['cause'], 'metres': float(row['metres']), 'opened_at': row['opened_at'].isoformat(),
'opened_by': row['opened_name']} for row in undecided]}
def machine_output(c, start, end):
"""What each machine printed in the period: the orders that reached
Finalizado then, on the machine they were on, their metres, the hours they
spent in Imprimindo (so metres per hour is the machine's real pace, as the
room moves the cards), when it last finished one, and what it has now.
The metres are the film printed, not the metres billed: billing rounds up
to 10 cm and to one metre at least, and a 0,40 m order printed as 1 m would
make the machine look faster than it is. Orders in Imprimindo on the same
machine at the same time share that time: it counts once."""
metres = ("(SELECT COALESCE(sum(COALESCE(i->>'metres', i->>'billed_metres')::numeric),0)"
" FROM jsonb_array_elements(o.snapshot->'items') i)")
done = c.execute(f'''SELECT o.id, o.machine_id, {metres} AS metres, f.at
FROM dtf_local.orders o
JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m
WHERE m.order_id=o.id AND m.to_state='fin') f ON f.at IS NOT NULL
WHERE {REAL_ORDER} AND (f.at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s''',
(start, end)).fetchall()
ids = [row['id'] for row in done]
printing = {}
for row in c.execute('''WITH events AS (
SELECT m.order_id AS id, m.to_state AS state, m.created_at AS at FROM dtf_local.movements m
WHERE m.order_id=ANY(%s)),
spans AS (SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events)
SELECT id, at, until FROM spans WHERE state='imp' AND until IS NOT NULL''', (ids,)).fetchall() if ids else []:
printing.setdefault(row['id'], []).append((row['at'], row['until']))
last = {str(row['machine_id']): row['at'] for row in c.execute(f'''SELECT o.machine_id, max(m.created_at) AS at
FROM dtf_local.orders o JOIN dtf_local.movements m ON m.order_id=o.id AND m.to_state='fin'
WHERE {REAL_ORDER} AND o.machine_id IS NOT NULL GROUP BY o.machine_id''').fetchall()}
result = []
for m in machines.rows(c):
mine = [row for row in done if str(row['machine_id'] or '') == m['id']]
hours_in = busy_hours([span for row in mine for span in printing.get(row['id'], [])])
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': 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]
if loose:
result.append({'id': None, 'name': 'Sem máquina', 'active': True, 'orders': len(loose),
'metres': float(sum(row['metres'] for row in loose)), 'printing_hours': None,
'metres_per_hour': None, 'last_finished': None, 'now': {}})
return result
def busy_hours(spans):
"""The hours the spans (start, end) cover, time shared by several counted once."""
seconds, reached = 0.0, None
for at, until in sorted(spans):
if reached is None or at >= reached:
seconds += (until - at).total_seconds()
reached = until
elif until > reached:
seconds += (until - reached).total_seconds()
reached = until
return seconds / 3600

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

@@ -8,13 +8,12 @@ from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException
from psycopg.types.json import Jsonb
from .. import catalog, coupons, payments
from .. import cart_pricing, payments
from ..core import db
from ..core.auth import owner
from ..core.models import QuoteRequest
from ..core.pricing import apply_bands, bill_splits, price
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
@@ -40,36 +39,6 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
item['stroke_choice_at'] = accepted_at
reason = quote_review.review_reason(draft)
with db.connect() as c:
if reason is not None or code:
# Waits for review: check the delivery now, priced at approval. A
# coupon is checked on the same priced items (front 8.3).
try:
priced = []
for item in body.items:
catalog.require_enabled(c, item.mode)
priced.append({**price(item.mode, str(item.metres), item.grade,
minimum=Decimal('0') if item.split else Decimal('1'),
unit_cents=catalog.unit_cents(c, item.mode)),
**({'split': item.split.model_dump()} if item.split else {})})
bill_splits(priced)
# Progressive bands (front 8.2), by the order's total per mode.
totals = {}
for item in priced:
totals[item['mode']] = totals.get(item['mode'], Decimal('0')) + Decimal(item['billed_metres'])
banded = {}
for mode, total in totals.items():
price_for_total = catalog.unit_cents_for(c, mode, total)
if price_for_total != catalog.unit_cents(c, mode):
banded[mode] = price_for_total
apply_bands(priced, banded)
if reason is not None:
freight.quote(body.freight.service, body.freight.postal_code,
sum(Decimal(i['billed_metres']) for i in priced),
sum(i['total_cents'] for i in priced))
except ValueError as exc:
raise HTTPException(422, str(exc))
if code:
coupons.check(c, code, body.customer.cnpj, priced)
rows = {}
for item in body.items:
for uid in item.uploads:
@@ -81,6 +50,21 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
raise HTTPException(422, 'JPG não tem fundo transparente. Envie a arte em PNG ou PDF.')
require_clean(row)
rows[str(uid)] = row
names = {uid: row['name'] for uid, row in rows.items()}
# One pricing module for the pre-check and the approval (plan 003). It
# also applies the grade rules and the coupon, as before.
try:
cart = cart_pricing.price_cart(
c, draft['items'], names, coupon_code=code,
customer_document=body.customer.cnpj,
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']),
cart['items_total'])
except ValueError as exc:
raise HTTPException(422, str(exc))
# The grade came from the browser and is shown with the order (it no
# longer sets the price): before a cart is approved at checkout, the
# server works it out from the files.
@@ -95,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

@@ -14,10 +14,10 @@ from fastapi import APIRouter, Depends, HTTPException
from psycopg.errors import UniqueViolation
from psycopg.types.json import Jsonb
from .. import catalog
from .. import catalog, grade_rules
from ..core import db
from ..core.auth import audit, can
from ..core.models import CouponNew, CouponUpdate, SitePriceNew, SiteProductToggle
from ..core.models import CouponNew, CouponUpdate, GradeRules, SitePriceNew, SiteProductToggle
router = APIRouter()
@@ -29,21 +29,20 @@ def price_row(row):
def checked_bands(product, bands):
"""The bands the row will store; 422 in Portuguese for anything invalid."""
if product == 'tratamento' and bands:
raise HTTPException(422, 'O tratamento é um valor por pedido: não tem faixas.')
"""The bands the row will store; 422 in Portuguese for anything invalid.
Ajuste Fino counts its bands in arts; the other products in metres."""
if len(bands) > 5:
raise HTTPException(422, 'Um preço pode ter no máximo 5 faixas.')
checked, last = [], None
for band in bands:
if not band.from_metres.is_finite() or band.from_metres <= 0:
raise HTTPException(422, 'A metragem de cada faixa precisa ser maior que zero.')
raise HTTPException(422, 'O início de cada faixa precisa ser maior que zero.')
if band.unit_cents <= 0:
raise HTTPException(422, 'O preço de cada faixa precisa ser maior que zero.')
if band.unit_cents > 10000000:
raise HTTPException(422, 'O preço de cada faixa é alto demais.')
if last is not None and band.from_metres <= last:
raise HTTPException(422, 'As faixas precisam estar em ordem crescente de metragem.')
raise HTTPException(422, 'As faixas precisam estar em ordem crescente.')
last = band.from_metres
checked.append({'from_metres': str(band.from_metres), 'unit_cents': band.unit_cents})
return checked
@@ -96,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
@@ -233,3 +235,30 @@ def delete_coupon(coupon_id: UUID, user=Depends(can('manage'))):
raise HTTPException(404, 'Cupom não encontrado.')
audit('site_coupon_deleted', coupon=str(coupon_id), code=row['code'], operator=user)
return {'ok': True}
@router.get('/api/operator/site/grade-rules')
def site_grade_rules(user=Depends(can('manage'))):
with db.connect() as c:
rules = grade_rules.current_rules(c)
offered = catalog.treatment_offered(c)
return {'aviso': rules.get('aviso'), 'tratamento': rules.get('tratamento'),
'treatment_offered': offered}
@router.post('/api/operator/site/grade-rules')
def save_grade_rules(body: GradeRules, user=Depends(can('manage'))):
if body.aviso is not None and body.tratamento is not None and body.tratamento > body.aviso:
raise HTTPException(422, 'A regra do Ajuste Fino precisa ser menor ou igual à do aviso.')
with db.connect() as c:
for action, below in (('aviso', body.aviso), ('tratamento', body.tratamento)):
if below is None:
c.execute('DELETE FROM dtf_local.grade_rules WHERE action=%s', (action,))
else:
c.execute('''INSERT INTO dtf_local.grade_rules(action,below,updated_by,updated_at)
VALUES(%s,%s,%s,now())
ON CONFLICT (action) DO UPDATE SET below=EXCLUDED.below,
updated_by=EXCLUDED.updated_by, updated_at=now()''',
(action, below, user))
audit('site_grade_rules_changed', aviso=body.aviso, tratamento=body.tratamento, operator=user)
return {'ok': True}

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,

168
app/api/stamps.py Normal file
View File

@@ -0,0 +1,168 @@
"""The montador's stamp sizes, its brand per stamp, the internal customer and
the Interno and Venda orders a sheet becomes (Fase 2, fronts 7a to 7a.3)."""
import hashlib
import json
import re
from uuid import uuid4
from fastapi import APIRouter, Depends, HTTPException, Request
from psycopg.types.json import Jsonb
from .. import payments, quote_review
from ..core import db
from ..core.auth import audit, can, roles_of
from ..core.models import (Customer, Freight, MontadorOrder, QuoteRequest, StampBrand,
StampSizeTable, UploadStart)
from ..runtime import operator_identity
from .uploads import begin_upload
router = APIRouter()
# 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
# administrators both.
MONTADOR_KINDS = {'expedicao': {'interno'}, 'vendedor': {'venda'},
'superadmin': {'interno', 'venda'}, 'admin': {'interno', 'venda'},
'gestao': {'interno', 'venda'}}
@router.get('/api/operator/stamp-sizes')
def stamp_sizes(user=Depends(can('assemble'))):
with db.connect() as c:
rows = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall()
return {'sizes': rows}
@router.post('/api/operator/stamp-sizes')
def save_stamp_sizes(body: StampSizeTable, user=Depends(can('manage'))):
with db.connect() as c:
c.execute('DELETE FROM dtf_local.stamp_sizes')
c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm,updated_by) VALUES(%s,%s,%s)',
[(row.letter, row.width_cm, user) for row in body.sizes])
audit('stamp_sizes_changed', operator=user, sizes=len(body.sizes))
return {'ok': True}
@router.get('/api/operator/internal-customer')
def read_internal_customer(user=Depends(can('assemble'))):
"""The customer every Interno order belongs to; empty fields mean Gestão
still has to complete it."""
with db.connect() as c:
row = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone()
return row or {'name': '', 'cnpj': '', 'zap': '', 'mail': ''}
@router.post('/api/operator/internal-customer')
def save_internal_customer(body: Customer, user=Depends(can('manage'))):
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.internal_customer(id,name,cnpj,zap,mail,updated_by,updated_at)
VALUES(1,%s,%s,%s,%s,%s,now()) ON CONFLICT(id) DO UPDATE SET name=EXCLUDED.name,
cnpj=EXCLUDED.cnpj, zap=EXCLUDED.zap, mail=EXCLUDED.mail,
updated_by=EXCLUDED.updated_by, updated_at=now()''',
(body.name, body.cnpj, body.zap, body.mail, user))
audit('internal_customer_changed', operator=user)
return {'ok': True}
def internal_customer(c):
"""The fixed Interno customer, ready to use, or the reason Gestão must
complete it first."""
row = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone()
if not row or not all(str(row[key] or '').strip() for key in ('name', 'cnpj', 'zap', 'mail')):
raise HTTPException(409, INTERNAL_MISSING)
try:
return Customer(**row)
except ValueError:
raise HTTPException(409, INTERNAL_MISSING) from None
@router.get('/api/operator/stamps/{code}')
def read_stamp(code: str, user=Depends(can('assemble'))):
"""The brand recorded for a stamp code; nothing else uses it yet."""
if not CODE.fullmatch(code):
raise HTTPException(422, 'Código inválido.')
with db.connect() as c:
row = c.execute('SELECT code,brand,public FROM dtf_local.stamps WHERE code=%s', (code,)).fetchone()
return row or {'code': code, 'brand': '', 'public': False}
@router.post('/api/operator/stamps/{code}')
def save_stamp(code: str, body: StampBrand, user=Depends(can('manage'))):
if not CODE.fullmatch(code):
raise HTTPException(422, 'Código inválido.')
brand = body.brand.strip()
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.stamps(code,brand,public,updated_by,updated_at)
VALUES(%s,%s,%s,%s,now()) ON CONFLICT(code) DO UPDATE SET brand=EXCLUDED.brand,
public=EXCLUDED.public, updated_by=EXCLUDED.updated_by, updated_at=now()''',
(code, brand, body.public, user))
audit('stamp_brand_saved', code=code, operator=user, public=body.public)
return {'ok': True}
@router.post('/api/operator/montador/uploads')
def montador_upload(body: UploadStart, user=Depends(can('assemble'))):
if not body.name.lower().endswith('.png'):
raise HTTPException(422, 'A estampa precisa ser um PNG.')
return begin_upload(body, session_id=operator_identity(user))
@router.post('/api/operator/montador/orders')
def montador_order(body: MontadorOrder, request: Request, user=Depends(can('assemble'))):
"""The card a montador sheet becomes (fronts 7a.3 and 7a.4): Interno (the
fixed internal customer, origin dropflow, never Tiny) or Venda (a Tiny
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."""
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':
customer = internal_customer(c)
origin, method = 'dropflow', payments.INTERNAL_METHOD
else:
customer = body.customer
origin, method = 'atendimento', payments.INVOICED_METHOD
draft = QuoteRequest(request_key=body.request_key, customer=customer, items=body.items,
freight=body.freight or Freight(service='pickup'),
destination=body.destination).model_dump(mode='json', exclude={'request_key'})
draft['montador'] = True
draft['kind'] = body.kind
if body.with_order:
draft['with_order'] = body.with_order
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
owner = operator_identity(user)
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft)
VALUES(%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING''',
(uuid4(), owner, body.request_key, digest, Jsonb(draft)))
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE owner=%s AND request_key=%s FOR UPDATE',
(owner, body.request_key)).fetchone()
if quote['request_hash'] != digest:
raise HTTPException(409, 'A montagem mudou durante o envio. Tente de novo.')
if not quote['approved']:
approved = quote_review.approve(c, quote, body.items, user)
# The order's kind and the clothing order it travels with, on the
# 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()
receipt = {'provider': payments.MANUAL_PROVIDER, 'method': method, 'note': '',
'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user}
order, created = payments.create_order(c, quote, receipt, origin)
if not created:
raise HTTPException(409, f"Esta montagem já virou o pedido #{order['number']}.")
audit('montador_order_created', order=str(order['id']), origin=origin, kind=body.kind, operator=user)
return order

View File

@@ -12,7 +12,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request
from starlette.concurrency import run_in_threadpool
from ..core import db
from ..core.auth import audit, owner, rate_limit
from ..core.auth import audit, client_ip, owner, rate_limit
from ..core.limits import upload_limit_bytes
from ..core.models import UploadStart
from ..payments import UNPAID_HOLD
@@ -20,25 +20,48 @@ from ..runtime import PART_BYTES, storage, upload_row
router = APIRouter()
# A cart of many files: 66 in Marcus's case (2026-11-11), and adding more or
# 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):
"""The public upload route's per-source bucket. The operator upload routes
reuse begin_upload directly and stay bound by their own session bucket."""
rate_limit('upload-start-ip', client_ip(request), UPLOAD_START_IP_LIMIT, 900)
@router.post('/api/uploads')
def begin_upload(body: UploadStart, session_id=Depends(owner)):
def begin_upload(body: UploadStart, session_id=Depends(owner), _source=Depends(upload_ip_limit)):
if body.size > upload_limit_bytes():
raise HTTPException(413, 'O arquivo passa do tamanho máximo aceito. Escolha um arquivo menor.')
uid = uuid4()
key = f'originals/{uid}'
rate_limit('upload-start', str(session_id), 60, 900)
rate_limit('upload-start', str(session_id), UPLOAD_START_LIMIT, 900)
with db.connect() as c:
# Serialize reservations across API processes, including changing guest IDs.
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()
if (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')) or
usage['pending'] >= int(os.environ.get('MAX_PENDING_UPLOADS','10'))):
(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'))
if storage_full or pending_full:
audit('upload_quota_rejected')
if pending_full and not storage_full:
# A big cart goes 4 at a time now (web/upload.js); a burst may
# still meet the pending cap: ask the Site to wait and retry.
raise HTTPException(429, 'Muitos envios ao mesmo tempo. O site tenta de novo sozinho.',
headers={'Retry-After': '15'})
raise HTTPException(429, 'Limite de armazenamento ou de envios pendentes atingido. Tente de novo mais tarde.')
multipart = storage.begin(key)
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,original_name,size,object_key,multipart_id,expires_at)

View File

@@ -5,6 +5,7 @@ changes it in "Minha senha". The superadmin is the system's own account, set fro
administrators manage everyone else. Nobody can remove, disable or demote
themselves, so the last administrator cannot lock the team out by accident.
"""
import os
import re
from decimal import Decimal
from typing import Literal
@@ -13,25 +14,39 @@ from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import Field, field_validator
from .. import machines, mail
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, STATES, TRANSITIONS
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']
# 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
@@ -41,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)
@@ -48,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)
@@ -64,15 +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):
@@ -89,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:
@@ -128,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
@@ -138,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
@@ -165,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)}
@@ -179,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']:
@@ -193,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}
@@ -227,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)}
@@ -238,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)
@@ -251,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,29 +4,66 @@ 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
from . import observability
from .core import db
from .core.auth import audit, client_ip
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage
from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, uploads, users
from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, stamps, uploads, users
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'):
@@ -45,5 +82,5 @@ async def safe_headers(request, call_next):
# Order is not significant: no two routers declare the same path.
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, site_admin, reviews, machine_log):
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, site_admin, reviews, machine_log, stamps):
app.include_router(module.router)

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

@@ -4,6 +4,7 @@ from pathlib import Path
from urllib.parse import urlparse
import psycopg
from psycopg import sql
from . import migrate
from .core.secrets import load as load_secret_files
from .operators import seed_from_environment
@@ -41,6 +42,7 @@ def main():
c.execute(sql.SQL('ALTER ROLE {} NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD {}').format(
sql.Identifier(role), sql.Literal(password)))
c.execute(Path(__file__).with_name('schema.sql').read_text())
applied = migrate.apply(c)
c.execute(sql.SQL('REVOKE CREATE ON SCHEMA public FROM PUBLIC'))
c.execute(sql.SQL('GRANT CONNECT ON DATABASE {} TO {}').format(sql.Identifier(database),sql.Identifier(role)))
c.execute(sql.SQL('GRANT USAGE ON SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
@@ -54,6 +56,8 @@ def main():
# reverted by a stale environment variable on the next deploy.
seeded = seed_from_environment(c)
print('Local schema migrated; runtime role has DML only.')
if applied:
print(f'Schema migrations applied: {", ".join(applied)}')
if seeded:
print(f'Seeded operator account {seeded} from OPERATOR_EMAIL.')

140
app/cart_pricing.py Normal file
View File

@@ -0,0 +1,140 @@
"""One pricing module for every way a cart is priced (Critical Corrections 3).
The Site's pre-check and the approval used to repeat the same chain and had
already drifted: the pre-check ignored the manual-file extra. Everything that
turns items into money lives here now. The catalog is read once, the arithmetic
is pure, and a new price rule only has to be added in one place.
"""
from decimal import Decimal
from . import catalog, coupons, grade_rules
from .core import pricing
def art_pairs(items):
"""[item_index, source_index] for every art in the cart: one artwork of
loose art, or one sheet file of a ready sheet."""
return [[index, source] for index, item in enumerate(items)
for source in range(len((item.get('production') or {}).get('sources') or []))]
def chosen_arts(items, choice):
"""The arts the draft's treatment selects: all of them for True (old carts
and the grade rule), the valid pairs for a list."""
if choice is True:
return art_pairs(items)
if not isinstance(choice, (list, tuple)):
return []
valid = {tuple(pair) for pair in art_pairs(items)}
return [list(pair) for pair in choice
if isinstance(pair, (list, tuple)) and len(pair) == 2 and tuple(pair) in valid]
def treatment_price(items, choice, offer):
"""Ajuste Fino for the chosen arts, with the row's bands counted in arts.
{} 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 = catalog.band_price(offer['unit_cents'], offer.get('bands') or [], count)
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
total, then apply_bands. Exactly as an order is charged."""
priced = []
for item in items:
extra = manual_extra if pricing.is_manual(item, names) else 0
product = catalog_now[item['mode']]
priced.append({**pricing.price(item['mode'], str(item['metres']), item['grade'], extra,
minimum=Decimal('0') if item.get('split') else Decimal('1'),
unit_cents=product['unit_cents']),
**({'split': item['split']} if item.get('split') else {})})
pricing.bill_splits(priced)
totals = {}
for item in priced:
totals[item['mode']] = totals.get(item['mode'], Decimal('0')) + Decimal(item['billed_metres'])
banded = {}
for mode, total in totals.items():
product = catalog_now[mode]
price_for_total = catalog.band_price(product['unit_cents'], product['bands'], total)
if price_for_total != product['unit_cents']:
banded[mode] = price_for_total
pricing.apply_bands(priced, banded)
return priced
def price_cart(c, items, names, *, coupon_code=None, customer_document=None,
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, '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:
if not catalog_now[item['mode']]['enabled']:
raise HTTPException(422, 'Este produto não está à venda agora.')
priced = price_items(items, names, catalog_now, pricing.manual_extra_cents())
offer = catalog_now['tratamento']
offered = bool(offer['enabled'] and offer['unit_cents'] > 0)
flags = grade_rules.triggered(grade_rules.current_rules(c), priced, offered)
if not treatment_rule:
flags.pop('tratamento', None)
treatment = treatment_price(items, wants_treatment, offer)
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:
coupon = coupons.check(c, coupon_code, customer_document, priced)
return {'items': priced,
'items_total': sum(i['total_cents'] for i in priced),
'coupon': coupon,
'treatment': treatment,
'treatment_cents': treatment.get('cents', 0),
'redesign': redesign,
'redesign_cents': redesign.get('cents', 0),
'grade_flags': flags}

View File

@@ -2,52 +2,63 @@
Dropstar, 2026-11-05 (Fase 2, front 8): the products and their prices leave the
code and live in the database, with a start date and a history. `PRICES` in
app/core/pricing.py stays as the seed and the fallback for the four modes;
app/core/pricing.py stays as the seed and the fallback for the five modes;
`treatment_cents()` stays as the fallback for `tratamento`. A price row is never
changed or deleted once its start date has passed (the table is the history),
and an approved quote keeps the price it was approved with.
`tratamento` is the designer's treatment (front 5), a fixed amount per order:
it counts as offered only when it is switched on and priced above zero.
`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. `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 total metres of that product (front
8.2): below the first band the base price, then the highest band reached wins
and the whole quantity is charged at that one price. The bands travel with the
row, so they start and become history with it.
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
band reached wins and the whole quantity is charged at that one price. The
bands travel with the row, so they start and become history with it.
"""
from decimal import Decimal
from .core import pricing
# The four modes sold by the metre, and the treatment sold per order.
MODES = ('file', 'avulsa', 'uvfile', 'uv')
PRODUCTS = (*MODES, 'tratamento')
# The modes sold by the metre, and the services sold per art.
MODES = ('file', 'avulsa', 'uvfile', 'uv', 'premium')
PRODUCTS = (*MODES, 'tratamento', 'redesenho')
TITLES = {
'file': 'Têxtil folha pronta',
'avulsa': 'Têxtil artes avulsas',
'uvfile': 'UV folha pronta',
'uv': 'UV artes avulsas',
'tratamento': 'Tratamento pelo designer',
'premium': 'Têxtil Premium · 8 passadas',
'tratamento': 'Ajuste Fino',
'redesenho': 'Ajuste Fino Redesenho',
}
UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro',
'tratamento': 'pedido'}
'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, metres: Decimal) -> int:
"""The per-metre price for this quantity: the base, or the highest band
reached. The whole quantity is charged at one price, not in steps."""
metres = Decimal(str(metres))
def band_price(base_cents: int, bands: list, quantity: Decimal) -> int:
"""The unit price for this quantity: the base, or the highest band reached.
The quantity is metres for a product and arts for Ajuste Fino; the whole
quantity is charged at one price, not in steps."""
quantity = Decimal(str(quantity))
price = base_cents
best = None
for band in bands or []:
start = Decimal(str(band['from_metres']))
if metres >= start and (best is None or start >= best):
if quantity >= start and (best is None or start >= best):
best = start
price = band['unit_cents']
return price
@@ -76,14 +87,20 @@ def unit_cents(c, product: str) -> int:
return row['unit_cents'] if row else fallback_cents(product)
def unit_cents_for(c, product: str, metres: Decimal) -> int:
def unit_cents_for(c, product: str, quantity: Decimal) -> int:
"""The current price of one product for this quantity, bands included."""
row = c.execute('''SELECT unit_cents, bands FROM dtf_local.product_prices
WHERE product=%s AND starts_at <= now()
ORDER BY starts_at DESC, id DESC LIMIT 1''', (product,)).fetchone()
if not row:
return fallback_cents(product)
return band_price(row['unit_cents'], row['bands'], metres)
return band_price(row['unit_cents'], row['bands'], quantity)
def treatment_offered(c) -> bool:
"""Whether the designer's treatment is on the Site: enabled and priced."""
offer = current(c)['tratamento']
return bool(offer['enabled'] and offer['unit_cents'] > 0)
def require_enabled(c, product: str) -> None:

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,16 +74,32 @@ 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'],))
def audit(event, **fields):
_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:
from psycopg.types.json import Jsonb
with connect() as c:
if c is not None:
c.execute('INSERT INTO dtf_local.security_events(event,details) VALUES(%s,%s)',(event,Jsonb(fields)))
else:
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()
@@ -125,7 +144,7 @@ def login_failed(email):
# backup, the Tiny log): the others see there only what is on and off.
# The designer approves and refuses artwork and asks for corrections, on every
# order whatever its machine. Which cards each profile moves is MOVES.
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro')
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao')
CAPABILITIES = {
'view': set(ROLES),
'produce': {'superadmin', 'admin', 'gestao', 'designer'},
@@ -155,6 +174,13 @@ CAPABILITIES = {
# The photo or video of the printed sheet in Revisão (Fase 2, front 2): who
# releases to Finalizado, and Gestão, which may stand in for them.
'inspect': {'superadmin', 'admin', 'gestao', 'revisor'},
# Montar folha (Fase 2, front 7): the new Expedição profile and the seller,
# who gets this one action although otherwise view-only (D-30).
'assemble': {'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'},
# The 10x15 thermal label at Finalizado (Marcus, 2026-11-10, front 10): the
# Revisor who releases the card, the Expedição profile that ships it, and
# Gestão, which may stand in for either.
'label': {'superadmin', 'admin', 'gestao', 'revisor', 'expedicao'},
}
# Who moves which card (Dropstar's flow, 2026-10-23, and their rules of
@@ -181,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':
@@ -196,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):
@@ -207,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
@@ -232,7 +305,18 @@ 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
def can_any(*capabilities):
"""A dependency that lets through a profile with any of these capabilities,
and returns the operator's e-mail, as the routes record it."""
def check(request: Request):
account = signed_in(request)
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

@@ -1,9 +1,18 @@
import os
import threading
from pathlib import Path
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
def connect():
from .. import migrate
# One pool per process, created on first use when DB_POOL is on (default off).
_pool = None
_pool_lock = threading.Lock()
def _direct():
# Production passes credentials as discrete libpq fields. This avoids
# treating characters in a generated password as URL syntax. Local and
# test environments retain DATABASE_URL compatibility.
@@ -17,7 +26,44 @@ def connect():
)
return psycopg.connect(os.environ['DATABASE_URL'], row_factory=dict_row)
def _pool_arguments():
"""The conninfo and kwargs for the pool, matching _direct()'s settings."""
if os.environ.get('DATABASE_HOST'):
return '', {
'host': os.environ['DATABASE_HOST'],
'dbname': os.environ['DATABASE_NAME'],
'user': os.environ['DATABASE_USER'],
'password': os.environ['DATABASE_PASSWORD'],
'row_factory': dict_row,
}
return os.environ['DATABASE_URL'], {'row_factory': dict_row}
def _pool_instance():
global _pool
if _pool is None:
with _pool_lock:
if _pool is None:
conninfo, kwargs = _pool_arguments()
_pool = ConnectionPool(
conninfo, kwargs=kwargs, min_size=1,
max_size=int(os.environ.get('DB_POOL_SIZE') or 20),
open=True, timeout=10, check=ConnectionPool.check_connection)
return _pool
def connect():
"""A connection for one `with` block. Pooled when DB_POOL is on (default
off): the same commit/rollback contract, the connection goes back to the
pool instead of closing."""
if os.environ.get('DB_POOL', 'off').lower() != 'on':
return _direct()
return _pool_instance().connection()
def initialize():
with connect() as c:
# The schema lives at the package root, one level up from core/.
c.execute((Path(__file__).resolve().parent.parent / 'schema.sql').read_text())
migrate.apply(c)

View File

@@ -127,9 +127,14 @@ 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=19, strict=True)
source_index: int = Field(ge=0, le=199, strict=True)
copy_index: int = Field(ge=0, le=199, strict=True)
x_cm: Decimal = Field(ge=0, le=57)
y_cm: Decimal = Field(ge=0, le=1200000)
@@ -148,7 +153,7 @@ class ProductionSpec(StrictModel):
version: Literal[2, 3]
film_width_cm: Decimal
height_cm: Decimal = Field(gt=0, le=1200000)
sources: list[ProductionSource] = Field(min_length=1, max_length=20)
sources: list[ProductionSource] = Field(min_length=1, max_length=200)
placements: list[ProductionPlacement] = Field(min_length=1, max_length=4000)
class Split(StrictModel):
@@ -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 = {}
@@ -174,16 +210,20 @@ def check_splits(items):
class Item(StrictModel):
mode: Literal['file','avulsa','uvfile','uv']
mode: Literal['file','avulsa','uvfile','uv','premium']
metres: Decimal = Field(gt=0, le=12000)
grade: int = Field(ge=0, le=100, strict=True)
uploads: list[UUID] = Field(min_length=1, max_length=20)
uploads: list[UUID] = Field(min_length=1, max_length=200)
production: ProductionSpec
quality_status: Literal['ok', 'warning', 'unverified']
quality_acknowledged: bool
# 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)
@@ -199,13 +239,22 @@ class Item(StrictModel):
source_dpi: int | None = Field(default=None, ge=0, le=1000000)
split: Split | None = None
@field_validator('uploads', mode='before')
@classmethod
def uploads_cap(cls, value):
# The Site shows a "Value error, ..." message as it is (web/checkout.js
# problem()); the Field cap alone would give the generic sentence.
if isinstance(value, list) and len(value) > 200:
raise ValueError('Este item tem mais de 200 arquivos. Divida em dois itens.')
return value
@model_validator(mode='after')
def production_matches_uploads(self):
if self.split and (self.mode not in ('avulsa', 'uv') or self.split.part > self.split.of):
raise ValueError('Only loose artwork is split into sheets')
if [source.upload_id for source in self.production.sources] != self.uploads:
raise ValueError('Production sources must match uploaded files in order')
is_sheet = self.mode in ('file', 'uvfile')
is_sheet = self.mode in ('file', 'uvfile', 'premium')
# UV is 27 cm wide (Dropstar, 2026-10-28; it was 28,5).
film_width = Decimal('27') if self.mode in ('uvfile', 'uv') else Decimal('57')
if self.production.film_width_cm != film_width:
@@ -215,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')
@@ -240,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):
@@ -265,8 +341,12 @@ class QuoteRequest(StrictModel):
destination: Destination | None = None
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
proof: bool = False
# "Quero o tratamento pelo designer": a fixed service line, when priced (front 5).
treatment: bool = False
# 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).
@@ -275,6 +355,39 @@ 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')
def treatment_arts_exist(self):
if isinstance(self.treatment, list):
seen = set()
for item_index, source_index in self.treatment:
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('Ajuste Fino: arte não encontrada no pedido.')
if (item_index, source_index) in seen:
raise ValueError('Ajuste Fino: cada arte aparece uma vez.')
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')
@@ -288,12 +401,53 @@ class QuoteRequest(StrictModel):
raise ValueError('The delivery address CEP must be the CEP freight was quoted for')
return self
class MontadorOrder(StrictModel):
"""What the montador sends (fronts 7a.3 and 7a.4): Interno or Venda, loose
artwork only; the server prices and approves it as a quote. An Interno
order takes the fixed customer from the database, a Venda one the customer
picked from Tiny. A Venda ships with the Site's freight or travels with the
customer's clothing order; an Interno never ships."""
request_key: UUID
kind: Literal['interno', 'venda']
# Empty for an Interno order: the server reads the internal customer.
customer: Customer | None = None
items: list[Item] = Field(min_length=1, max_length=30)
# A Venda that travels with the customer's clothing order; pickup freight.
with_order: int | None = Field(default=None, ge=1, le=999999, strict=True)
# A Venda with "Envio": the chosen freight service and the full address.
freight: Freight | None = None
destination: Destination | None = None
@model_validator(mode='after')
def order_kind(self):
if any(item.mode != 'avulsa' for item in self.items):
raise ValueError('O montador só monta artes avulsas.')
if self.kind == 'venda' and self.customer is None:
raise ValueError('O pedido de venda precisa do cliente.')
delivery = bool(self.freight and self.freight.service != 'pickup')
if self.kind == 'interno':
if self.with_order is not None:
raise ValueError('O pedido interno não tem envio.')
if delivery or self.destination is not None:
raise ValueError('O pedido interno não tem envio.')
elif delivery:
if self.with_order is not None:
raise ValueError('Escolha retirada, envio ou junto com o pedido de roupa.')
if self.destination is None:
raise ValueError('O envio precisa do endereço completo.')
if self.destination.postal_code != self.freight.postal_code:
raise ValueError('O CEP do frete e o do endereço precisam ser o mesmo.')
elif self.destination is not None:
raise ValueError('Só o pedido com envio tem endereço de entrega.')
return self
class Review(StrictModel):
items: list[Item] = Field(min_length=1, max_length=30)
@model_validator(mode='after')
def splits_complete(self):
check_splits(self.items)
check_one_machine(self.items)
return self
class Pay(StrictModel):
@@ -308,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}$')
@@ -383,7 +537,7 @@ class CouponNew(StrictModel):
min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1)
max_uses: int | None = Field(default=None, gt=0, strict=True)
max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True)
product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None
product: Literal['file', 'avulsa', 'uvfile', 'uv', 'premium'] | None = None
note: str = Field(default='', max_length=1000)
@@ -396,11 +550,17 @@ class CouponUpdate(StrictModel):
min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1)
max_uses: int | None = Field(default=None, gt=0, strict=True)
max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True)
product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None
product: Literal['file', 'avulsa', 'uvfile', 'uv', 'premium'] | None = None
note: str | None = Field(default=None, max_length=1000)
paused: bool | None = None
class GradeRules(StrictModel):
"""As regras da nota da arte: um limite por ação, ou nada (null)."""
aviso: int | None = Field(ge=1, le=100, strict=True)
tratamento: int | None = Field(ge=1, le=100, strict=True)
class Contraction(StrictModel):
item_index: int = Field(ge=0, le=100)
# None returns the item to the class the browser measured.
@@ -493,3 +653,25 @@ class ArtworkSubmission(StrictModel):
version: int = Field(ge=0, strict=True)
files: list[FileReference] = Field(min_length=1, max_length=60)
note: str = Field(min_length=1, max_length=1000)
class StampSize(StrictModel):
"""One row of the montador's size table (Fase 2, front 7)."""
letter: str = Field(pattern=r'^[A-Z]{1,2}$')
width_cm: Decimal = Field(gt=0, le=56, decimal_places=2)
class StampSizeTable(StrictModel):
"""The whole table, replaced in one go by Gestão."""
sizes: list[StampSize] = Field(min_length=1, max_length=26)
@model_validator(mode='after')
def letters_unique(self):
letters = [row.letter for row in self.sizes]
if len(letters) != len(set(letters)):
raise ValueError('Cada tamanho tem uma letra própria.')
return self
class StampBrand(StrictModel):
"""The brand recorded per stamp code, for the future catalogue (front 7a.3)."""
brand: str = Field(default='', max_length=120)
public: bool = False

View File

@@ -8,7 +8,20 @@ import os
import re
from decimal import Decimal, ROUND_CEILING
PRICES = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990}
# 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
# person before printing. It pays this per metre on top of the product's price
@@ -25,7 +38,7 @@ def manual_extra_cents() -> int:
def treatment_cents() -> int:
"""The designer's treatment, a fixed amount per order (front 5).
"""Ajuste Fino, a fixed amount per art (front 1a).
Zero keeps the option hidden: the price is the client's decision, and the
server and the Site read the same `TREATMENT_CENTS`.
@@ -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

@@ -15,8 +15,10 @@ again, by the Site's own rules:
is only vectors (web/site-pdf.js, dpiDasImagens and resumoDpi).
Images are measured from their first bytes, never decoded. A PDF is opened
only up to PDF_MAX_BYTES, the size the Site itself analyses. A grade that
cannot be recomputed is None; the caller decides what that means.
only up to PDF_MAX_BYTES, the size the Site itself analyses. Its DPI is worked
out when the scan finishes and stored on the upload row (pdf_checked), so
checkout uses the stored number and opens the file only when it is absent. A
grade that cannot be recomputed is None; the caller decides what that means.
"""
import math
import os
@@ -130,6 +132,16 @@ def pdf_dpi(path):
return js_round(sum(dpi * area for dpi, area in found) / total)
def stored_pdf_dpi(storage, row):
"""A stored PDF's DPI, read once; None when it is above PDF_MAX_BYTES."""
if row['size'] > PDF_MAX_BYTES:
return None
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
storage.client.download_fileobj(storage.bucket, row['object_key'], handle)
handle.flush()
return pdf_dpi(handle.name)
class Files:
"""The uploaded files, read from storage as little as needed."""
@@ -150,13 +162,10 @@ class Files:
def pdf_dpi(self, row):
key = row['object_key']
if key not in self._dpis:
if row['size'] > PDF_MAX_BYTES:
self._dpis[key] = None
if row.get('pdf_checked'):
self._dpis[key] = row['pdf_dpi']
else:
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
self.storage.client.download_fileobj(self.storage.bucket, key, handle)
handle.flush()
self._dpis[key] = pdf_dpi(handle.name)
self._dpis[key] = stored_pdf_dpi(self.storage, row)
return self._dpis[key]
@@ -208,14 +217,45 @@ def resolution_issue(files, items, rows):
dpis.append(dpi)
if not dpis:
continue
lowest = min(dpis)
if lowest < DPI_REFUSE:
return f'Item {index}: resolução de {js_round(lowest)} DPI abaixo do mínimo de {DPI_REFUSE} DPI.'
if lowest < DPI_IDEAL and (item['quality_status'] != 'warning' or not item['quality_acknowledged']):
# The Site shows and compares the rounded DPI (web/site-quality.js,
# site-pdf.js): decide on the same whole number, not the raw fraction.
shown = js_round(min(dpis))
if shown < DPI_REFUSE:
return f'Item {index}: resolução de {shown} DPI abaixo do mínimo de {DPI_REFUSE} DPI.'
if shown < DPI_IDEAL and (item['quality_status'] != 'warning' or not item['quality_acknowledged']):
return f'Item {index}: confirme a ressalva de resolução entre {DPI_REFUSE} e {DPI_IDEAL - 1} DPI.'
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:

34
app/grade_rules.py Normal file
View File

@@ -0,0 +1,34 @@
"""What the art grade decides, set in the Kanban's Site tab (Fase 2, front 8.5).
With no rule nothing changes anywhere. An item triggers a rule when its grade
is below the rule's `below`; the order's worst item decides. `aviso` flags the
order for the designer; `tratamento` makes Ajuste Fino required, but only while
it is offered (enabled and priced above zero).
"""
def current_rules(c) -> dict:
"""{'aviso': 70, 'tratamento': 50} for the rows that exist."""
return {row['action']: row['below'] for row in
c.execute('SELECT action, below FROM dtf_local.grade_rules').fetchall()}
def triggered(rules: dict, items, treatment_offered: bool) -> dict:
"""The rules the order's worst item triggers: {'aviso': N}, maybe with
'tratamento': N. N is the worst grade; empty when no rule applies."""
grades = [item.get('grade') for item in items if item.get('grade') is not None]
if not grades:
return {}
worst = min(grades)
flags = {}
if 'aviso' in rules and worst < rules['aviso']:
flags['aviso'] = worst
if treatment_offered and 'tratamento' in rules and worst < rules['tratamento']:
flags['tratamento'] = worst
return flags
def treatment_message(grade: int) -> str:
"""The refusal the customer sees when Ajuste Fino is required."""
return (f'Sua arte tem nota {grade}: para imprimir com qualidade, o Ajuste Fino '
'é obrigatório neste pedido.')

View File

@@ -1,11 +1,13 @@
"""Each machine's hot folders (Dropstar's third round, item 10, 2026-10-29/30).
FlexiPRINT watches 3. Imprimindo/<máquina>/<C1|C2|C3>/ 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;
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.
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 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
@@ -13,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.
@@ -22,11 +25,11 @@ 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')
# The premium product's own folder (Dropstar, 2026-11-10, front 3).
PREMIUM = 'PREMIUM'
def contraction(order, index):
@@ -41,12 +44,26 @@ def contraction(order, index):
return item.get('stroke_class') if item.get('stroke_class') in CLASSES else None
def folder_class(order, index):
"""The folder an item's parts go to: PREMIUM for the premium product,
whatever contraction class is recorded, else C1/C2/C3."""
item = order['snapshot']['items'][index]
return PREMIUM if item.get('mode') == 'premium' else contraction(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):
@@ -54,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."""
@@ -65,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']
@@ -83,12 +134,14 @@ def claim(c, user):
machine, order = row['machine_id'], row['order_id']
if row['state'] != 'queued' or order in blocked:
continue
cls = contraction(row, row['item_index'])
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

129
app/label.py Normal file
View File

@@ -0,0 +1,129 @@
"""The 10x15 cm thermal label printed at Finalizado (Fase 2, front 10).
Marcus, 2026-11-10: when a card reaches Finalizado the Kanban prints a label on
the Zebra ZD220: the Tiny order number, the customer, what the order is, pickup
or shipping, when it was released and by which Revisor, and a QR with the Tiny
order number only. The server renders the page so its content lives in one
place. The QR is an inline SVG from segno; nothing is loaded from outside.
`label_fields` is pure, for the tests; `label_html` only adds the markup and the
QR. Without a Tiny receipt the order keeps its own DTF-<number> as the number
and in the QR (an Interno order never reaches Tiny).
"""
import html
from datetime import timezone
from decimal import Decimal
from zoneinfo import ZoneInfo
LOCAL = ZoneInfo('America/Sao_Paulo')
SERVICE_NAMES = {'pac': 'Correios PAC', 'sedex': 'Correios SEDEX', 'jadlog': 'Jadlog'}
def _escape(value):
return html.escape(str(value if value is not None else ''), quote=True)
def _metres(items):
"""The order's billed metres with a comma and two decimals, as the card shows."""
total = sum((Decimal(str(item.get('billed_metres') or item.get('metres') or 0))
for item in items), Decimal(0))
return f'{total:.2f}'.replace('.', ',')
def _sheets(count):
return f'{count} folha' if count == 1 else f'{count} folhas'
def _delivery(snapshot):
"""Retirada, Envio with the carrier the card shows, junto com a roupa, or Interno."""
if snapshot.get('with_order'):
return f"Junto com pedido de roupa nº {snapshot['with_order']}"
if snapshot.get('kind') == 'interno':
return 'Interno'
if snapshot.get('destination'):
freight = snapshot.get('freight') or {}
service = freight.get('service')
return 'Envio · ' + (freight.get('description') or SERVICE_NAMES.get(service) or service or 'Frete')
return 'Retirada'
def _customer(snapshot):
customer = snapshot.get('customer') or {}
destination = snapshot.get('destination') or {}
return customer.get('name') or destination.get('recipient') or customer.get('mail') or '—'
def _finished_at(value):
if value is None:
return ''
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')
def label_fields(order, tiny_number, finished_at, revisor):
"""What the label says, from one order and its Tiny sale receipt."""
snapshot = order.get('snapshot') or {}
items = snapshot.get('items') or []
code = str(tiny_number) if tiny_number else f"DTF-{order['number']}"
return {'code': code, 'customer': _customer(snapshot), 'sheets': len(items),
'metres': _metres(items), 'delivery': _delivery(snapshot),
'finished_at': _finished_at(finished_at), 'revisor': revisor or '—',
'qr': code}
def qr_svg(text):
"""The QR as an inline SVG, dark on the label's white; segno is pure Python.
`omitsize` keeps a viewBox and drops the fixed width/height, so the CSS can
print it at the label's 30 mm without the modules staying pixel-sized.
"""
import segno
return segno.make_qr(text, error='m').svg_inline(border=1, omitsize=True)
def label_html(fields):
"""The printable page: 100 x 150 mm, black on white, no external resources."""
code = _escape(fields['code'])
# The number is as large as its length allows on the 88 mm of usable width.
code_size = 22 if len(str(fields['code'])) <= 7 else 18 if len(str(fields['code'])) <= 9 else 15
customer = _escape(fields['customer'])
sheets = _escape(_sheets(int(fields['sheets'])))
metres = _escape(fields['metres'])
delivery = _escape(fields['delivery'])
finished = _escape(fields['finished_at'])
revisor = _escape(fields['revisor'])
return f"""<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<title>Etiqueta {code}</title>
<style>
@page {{ size: 100mm 150mm; margin: 0 }}
* {{ box-sizing: border-box }}
html, body {{ margin: 0; padding: 0; background: #fff; color: #000 }}
body {{ font-family: system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif }}
.label {{ width: 100mm; height: 150mm; padding: 6mm 6mm 5mm; display: flex;
flex-direction: column; gap: 2mm; overflow: hidden }}
.code {{ font-size: {code_size}mm; line-height: .95; font-weight: 800; letter-spacing: -.02em;
white-space: nowrap; overflow: hidden }}
.customer {{ font-size: 6mm; line-height: 1.15; font-weight: 700 }}
.line {{ font-size: 4.6mm; line-height: 1.2 }}
.foot {{ font-size: 3.6mm; line-height: 1.35; margin-top: 2mm }}
.qr {{ margin-top: auto; display: flex; justify-content: center }}
.qr svg {{ width: 30mm; height: 30mm; display: block }}
</style>
</head>
<body>
<div class="label">
<div class="code">{code}</div>
<div class="customer">{customer}</div>
<div class="line">DTF · {sheets} · {metres} m</div>
<div class="line">{delivery}</div>
<div class="foot"><div>Finalizado em {finished}</div><div>Revisor: {revisor}</div></div>
<div class="qr">{qr_svg(fields['qr'])}</div>
</div>
</body>
</html>
"""

View File

@@ -16,8 +16,9 @@ once, which lets exactly one more card through.
clean CLEAN_EVERY_METRES printed since the last "clean" event.
align ALIGN_AFTER_FILM_METRES printed since the last film change (a
supply entry of "film") with no "align" event after it.
supply a supply whose estimated stock is at or below the minimum Gestão set
for that machine (no minimum, no alert).
supply a supply whose estimated stock is at or below the machine's minimum:
the one Gestão typed, or Dropstar's default for that supply (1 roll
of film, 1 L of each ink, 5 kg of powder).
The supply estimate assumes each entry refills what was used since the one
before: the use per metre is the quantity entered over the metres printed in
@@ -27,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
@@ -40,6 +42,11 @@ SUPPLY_INTERVALS = 3
SUPPLIES = {'film': ('Filme', 'rolo'), 'ink_c': ('Tinta ciano', 'L'), 'ink_m': ('Tinta magenta', 'L'),
'ink_y': ('Tinta amarela', 'L'), 'ink_k': ('Tinta preta', 'L'), 'ink_w': ('Tinta branca', 'L'),
'powder': ('Poliamida', 'kg')}
# Dropstar's fixed minimums (2026-11-10): a machine with no minimum typed uses
# these. Units match the supplies: rolls, litres and kilograms.
DEFAULT_MINIMUMS = {'film': Decimal('1'), 'ink_c': Decimal('1'), 'ink_m': Decimal('1'),
'ink_y': Decimal('1'), 'ink_k': Decimal('1'), 'ink_w': Decimal('1'),
'powder': Decimal('5')}
PARTS = {'cap': 'Cap', 'damper': 'Damper', 'head': 'Cabeça de impressão', 'wiper': 'Wiper', 'other': 'Outra peça'}
EVENTS = {'clean': 'Limpeza', 'align': 'Alinhamento da cabeça', 'stop': 'Parada'}
@@ -52,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):
@@ -130,8 +166,13 @@ def estimate(entries, metres_between, metres_since_last, minimum=None):
'minimum': minimum}
def minimum_for(minimums, item):
"""The minimum typed for the machine, or Dropstar's default for that supply."""
return minimums.get(item, DEFAULT_MINIMUMS.get(item))
def supply_low(value):
"""Whether an estimate is at or below the machine's minimum (no minimum, no alert)."""
"""Whether an estimate is at or below the machine's minimum (typed or default)."""
return bool(value) and value['minimum'] is not None and value['stock'] <= value['minimum']
@@ -151,7 +192,8 @@ def supply_estimates(c, machine_id):
continue
printed = [printed_since(c, machine_id, row['created_at']) for row in rows]
between = [printed[index - 1] - printed[index] for index in range(1, len(printed))]
value = estimate([row['quantity'] for row in rows], between, printed[-1], minimums.get(item))
value = estimate([row['quantity'] for row in rows], between, printed[-1],
minimum_for(minimums, item))
if value is not None:
result[item] = value
return result

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

@@ -93,7 +93,8 @@ def order_paid(c, order, origin):
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas',
'premium': 'DTF Têxtil Premium · folha montada'}
def quote_expired(c, quote, origin):

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").

34
app/migrate.py Normal file
View File

@@ -0,0 +1,34 @@
"""Timestamped schema migrations, applied once by the database initializer.
schema.sql is the frozen baseline and runs on every start; a change after it is
a file in app/migrations/, named YYYYMMDDHHMM_slug.sql. The name is the
migration's identity and is recorded in dtf_local.migrations, so a deploy never
applies one twice and an older image skips names it does not know.
"""
import re
from pathlib import Path
MIGRATIONS = Path(__file__).resolve().with_name('migrations')
LOCK = 804209
NAME = re.compile(r'\d{12}_[a-z0-9-]+\.sql')
def apply(c, directory=MIGRATIONS) -> list[str]:
"""Run, in name order, every migration file not yet recorded in
dtf_local.migrations, each recorded in the same transaction. A name in
the table that has no file (written by a newer image) is ignored, so an
older image still starts."""
c.execute('SELECT pg_advisory_xact_lock(%s)', (LOCK,))
files = {}
for path in Path(directory).iterdir():
if not path.is_file() or not NAME.fullmatch(path.name):
raise ValueError(f'Unexpected file in {directory}: {path.name}')
files[path.name] = path
applied = []
for name in sorted(files):
if c.execute('SELECT 1 FROM dtf_local.migrations WHERE name=%s', (name,)).fetchone():
continue
c.execute(files[name].read_text())
c.execute('INSERT INTO dtf_local.migrations(name) VALUES(%s)', (name,))
applied.append(name)
return applied

View File

@@ -0,0 +1,14 @@
-- The current lists of the three CHECK constraints whose values have grown
-- over time, applied once to every database, including one whose copy is older
-- (an image before front 7a lacks 'expedicao', for example). From now on,
-- widening a list is a new migration that drops and adds that one constraint.
ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao'));
ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check;
ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
CHECK(kind IN ('reset','code','account','notice','order','alert','test'));
ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check;
ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento'));

View File

@@ -0,0 +1,7 @@
-- Front 8.5: what the art grade decides, set in the Kanban's Site tab. No row
-- means no rule, and nothing changes; each action has at most one threshold.
CREATE TABLE IF NOT EXISTS dtf_local.grade_rules (
action text PRIMARY KEY CHECK (action IN ('aviso','tratamento')),
below integer NOT NULL CHECK (below BETWEEN 1 AND 100),
updated_by text NOT NULL, updated_at timestamptz NOT NULL DEFAULT now()
);

View File

@@ -0,0 +1,4 @@
-- The PDF's resolution, worked out at the scan (Critical Corrections 2): pdf_checked
-- false = not worked out yet (checkout reads as before), NULL pdf_dpi with it true = unreadable.
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS pdf_checked boolean NOT NULL DEFAULT false;
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS pdf_dpi integer;

View File

@@ -0,0 +1,24 @@
-- Front 7a.3: a brand per stamp, for the future catalogue, and the montador's
-- fixed internal customer. The brand is only recorded here for now; nothing
-- else reads it yet (Marcus, 2026-11-10).
CREATE TABLE IF NOT EXISTS dtf_local.stamps (
code text PRIMARY KEY CHECK (code ~ '^[A-Za-z0-9_-]{1,40}$'),
brand text NOT NULL DEFAULT '',
public boolean NOT NULL DEFAULT false,
updated_by text NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
-- The one customer every Interno order belongs to (the marketplace's own
-- sales). Gestão completes it; until then an Interno order is refused.
CREATE TABLE IF NOT EXISTS dtf_local.internal_customer (
id integer PRIMARY KEY DEFAULT 1 CHECK (id=1),
name text NOT NULL DEFAULT '',
cnpj text NOT NULL DEFAULT '',
zap text NOT NULL DEFAULT '',
mail text NOT NULL DEFAULT '',
updated_by text NOT NULL DEFAULT 'sistema',
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO dtf_local.internal_customer(id,name) VALUES(1,'Nexstar · Marketplace')
ON CONFLICT (id) DO NOTHING;

View File

@@ -0,0 +1,17 @@
-- Front 3: the Premium product (Marcus, 2026-11-10), built and switched OFF
-- until Dropstar prints the three test sheets and says "testado". The products
-- CHECK is the inline constraint of dtf_local.products.id, which Postgres
-- named 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'));
INSERT INTO dtf_local.products(id, enabled) VALUES ('premium', false)
ON CONFLICT (id) DO NOTHING;
-- A coupon may also target the new product (the Site tab lists every mode).
ALTER TABLE dtf_local.coupons DROP CONSTRAINT IF EXISTS coupons_product_check;
ALTER TABLE dtf_local.coupons ADD CONSTRAINT coupons_product_check
CHECK (product IN ('file','avulsa','uvfile','uv','premium'));

View File

@@ -0,0 +1,12 @@
-- Front 10: the 10x15 cm label at Finalizado (Marcus, 2026-11-10). One 'auto'
-- print per order, decided by the unique partial index, so two computers
-- asking at once cannot both print it; a reprint is always another row.
CREATE TABLE IF NOT EXISTS dtf_local.label_prints (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
reason text NOT NULL CHECK (reason IN ('auto','reprint')),
printed_by text NOT NULL,
printed_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX IF NOT EXISTS label_prints_one_auto
ON dtf_local.label_prints(order_id) WHERE reason='auto';

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;

146
app/observability.py Normal file
View File

@@ -0,0 +1,146 @@
"""Sentry for the API and the worker, off until a DSN arrives (note Sentry).
`init(component)` reads `SENTRY_DSN_API` and returns without importing the SDK
when it is empty, so local and CI runs carry no Sentry dependency or network
cost. When it is set, `scrub` keeps cookies, credentials, request bodies and
Brazilian personal data out of the events (LGPD).
"""
import os
import re
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
EMAIL = re.compile(r'[^\s@]+@[^\s@]+\.[A-Za-z]{2,}')
# CPF (11 digits) or CNPJ (14), with or without punctuation.
DOCUMENT = re.compile(r'(?<!\d)(?:\d{2}\.?\d{3}\.?\d{3}/?\d{4}-?\d{2}'
r'|\d{3}\.?\d{3}\.?\d{3}-?\d{2})(?!\d)')
SENSITIVE_PARAM = re.compile(r'token|signature|x-amz', re.I)
SENSITIVE_HEADER = re.compile(r'^(cookie|authorization|x-.*token.*)$', re.I)
REDACTED = '[removido]'
def _clean(text):
"""Replace e-mail addresses and CPF/CNPJ in one string."""
if not isinstance(text, str):
return text
return DOCUMENT.sub(REDACTED, EMAIL.sub(REDACTED, text))
def _scrub_query(query):
"""A query string without token, signature and X-Amz parameters."""
if not isinstance(query, str) or not query:
return query
pairs = parse_qsl(query, keep_blank_values=True)
kept = [(key, value) for key, value in pairs if not SENSITIVE_PARAM.search(key)]
return query if len(kept) == len(pairs) else urlencode(kept, doseq=True)
def _scrub_url(url):
if not isinstance(url, str):
return url
parts = urlsplit(url)
if not parts.query:
return url
return urlunsplit(parts._replace(query=_scrub_query(parts.query)))
def _scrub_text(value):
"""Personal data and a URL query string inside a message or crumb."""
value = _clean(value)
if not isinstance(value, str) or '?' not in value:
return value
head, _, query = value.partition('?')
return head + '?' + _scrub_query(query)
def _scrub_value(value):
if isinstance(value, str):
return _scrub_text(value)
if isinstance(value, list):
return [_scrub_value(item) for item in value]
if isinstance(value, dict):
return {key: _scrub_value(item) for key, item in value.items()}
return value
def _scrub_request(request):
"""Cookies, credentials, query tokens and bodies never leave the server."""
if not isinstance(request, dict):
return
request.pop('cookies', None)
request.pop('data', None)
request.pop('body', None)
headers = request.get('headers')
if isinstance(headers, dict):
request['headers'] = {key: value for key, value in headers.items()
if not SENSITIVE_HEADER.match(str(key))}
if 'query_string' in request:
request['query_string'] = _scrub_query(request['query_string'])
if 'url' in request:
request['url'] = _scrub_url(request['url'])
def scrub(event, hint=None):
"""before_send: strip credentials, bodies and personal data from an event."""
if not isinstance(event, dict):
return event
_scrub_request(event.get('request'))
if 'message' in event:
event['message'] = _scrub_text(event['message'])
logentry = event.get('logentry')
if isinstance(logentry, dict) and 'message' in logentry:
logentry['message'] = _scrub_text(logentry['message'])
exception = event.get('exception')
if isinstance(exception, dict):
for value in exception.get('values') or []:
if isinstance(value, dict) and 'value' in value:
value['value'] = _scrub_text(value['value'])
breadcrumbs = event.get('breadcrumbs')
if isinstance(breadcrumbs, dict):
breadcrumbs = breadcrumbs.get('values') or []
if isinstance(breadcrumbs, list):
for crumb in breadcrumbs:
if not isinstance(crumb, dict):
continue
if 'message' in crumb:
crumb['message'] = _scrub_text(crumb['message'])
if 'data' in crumb:
crumb['data'] = _scrub_value(crumb['data'])
if 'extra' in event:
event['extra'] = _scrub_value(event['extra'])
return event
def _traces_rate():
try:
return float(os.environ.get('SENTRY_TRACES', '0') or 0)
except (TypeError, ValueError):
return 0.0
def release():
"""The deploy this process runs: IMAGE_TAG when the stack sets one, else the
commit the image was built from (RELEASE, from deploy/Dockerfile.api)."""
value = os.environ.get('IMAGE_TAG') or os.environ.get('RELEASE') or ''
return None if value in ('', 'unknown', 'latest') else value
def init(component):
"""Start Sentry for this process; False (and no imports) without a DSN."""
dsn = os.environ.get('SENTRY_DSN_API', '').strip()
if not dsn:
return False
import sentry_sdk
environment = os.environ.get('SENTRY_ENVIRONMENT')
if not environment:
from .runtime import ENVIRONMENT
environment = ENVIRONMENT
sentry_sdk.init(
dsn=dsn,
environment=environment,
release=release(),
send_default_pii=False,
traces_sample_rate=_traces_rate(),
before_send=scrub,
)
sentry_sdk.set_tag('component', component)
return True

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
@@ -60,15 +71,51 @@ def is_test(order):
# (Dropstar's rule D-35, 2026-10-26; the user's answers of 2026-10-27).
MANUAL_PROVIDER = 'manual'
OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit')
# A montador Venda order is invoiced, not paid at the counter: it is not one of
# the Cotações "registrar" methods. It goes to Tiny as an approved quote does.
INVOICED_METHOD = 'faturado'
# A montador Interno order: the marketplace's own sale, already invoiced there.
# It stays in house and never reaches Tiny (Marcus, 2026-11-10).
INTERNAL_METHOD = 'interno'
def in_tiny(order):
"""Whether the order goes to Tiny: every order but a test or a proof card
(app/proof.py), which is no sale. A Dropflow order goes in its own revenue
category (app/tiny.py, CATEGORIES)."""
"""Whether the order goes to Tiny: every order but an internal one, a test
or a proof card (app/proof.py), which is no sale. A Dropflow order goes in
its own revenue category (app/tiny.py, CATEGORIES)."""
if (order.get('payment') or {}).get('method') == INTERNAL_METHOD:
return False
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.
@@ -146,7 +193,10 @@ def create_order(c, quote, payment, origin):
proof.create_child(c, order)
if is_test(order):
return order, True
mail.order_paid(c, order, PUBLIC_ORIGIN)
# An invoiced or internal montador order was not paid here: no "pedido
# pago" e-mail for either (front 7a.3).
if payment.get('method') not in (INVOICED_METHOD, INTERNAL_METHOD):
mail.order_paid(c, order, PUBLIC_ORIGIN)
if not in_tiny(order):
return order, True
# How it was paid, for the order's payment in Tiny.
@@ -190,7 +240,7 @@ def apply(c, event):
except (ValueError, AttributeError):
order = None
if order:
audit('payment_reversed', order=order['number'], status=event.status)
audit('payment_reversed', order=order['number'], status=event.status, c=c)
return f"attention: payment {event.status} for order {order['number']}"
if event.status != 'approved':
return f'ignored: {event.status}'
@@ -201,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}'
@@ -212,11 +262,20 @@ def apply(c, event):
expected = quote['approved']['total_cents']
if type(event.amount_cents) is not int or event.amount_cents != expected:
audit('payment_amount_mismatch', quote=str(quote_id),
expected_cents=expected, paid_cents=event.amount_cents)
expected_cents=expected, paid_cents=event.amount_cents, c=c)
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):
@@ -234,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()
@@ -187,24 +229,30 @@ def render_one(storage):
(source_ids,)).fetchone()['e']
by_id = {str(row['id']): row for row in uploads}
if job.get('wait_for_treatment'):
finish(job, 'manual', {'reason': 'Tratamento pago: prepare e aprove o PNG completo no pedido pai para gerar a prova.'})
finish(job, 'manual', {'reason': 'Ajuste Fino pago: prepare e aprove o PNG completo no pedido pai para gerar a prova.'})
return True
if any(row['size'] > LARGE_SOURCE_BYTES and not row['name'].lower().endswith(STREAMED) for row in uploads):
finish(job, 'manual', {'reason': f'arquivo acima de {LARGE_SOURCE_BYTES // 1048576} MB que não é PNG nem PDF: '
'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

@@ -19,10 +19,9 @@ from decimal import Decimal
from fastapi import HTTPException
from psycopg.types.json import Jsonb
from . import catalog, coupons, payments
from . import cart_pricing, payments
from .proof import PROOF_ABOVE_METRES
from .core.models import PRODUCTION_VERSIONS
from .core.pricing import apply_bands, bill_splits, is_manual, manual_extra_cents, price
from .runtime import freight, upload_row
from .scanning import require_clean
@@ -60,79 +59,72 @@ def approve(c, row, items, reviewer):
raise HTTPException(409, 'A cotação usa uma montagem antiga: o cliente precisa montar o pedido de novo.')
if len(items) != len(draft['items']):
raise HTTPException(422, 'Confira todos os itens da cotação.')
priced = []
names = {}
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.')
names = {}
for upload_id in item.uploads:
upload = upload_row(c, upload_id, row['owner'])
require_clean(upload)
names[str(upload_id)] = upload['name']
catalog.require_enabled(c, item.mode)
extra = manual_extra_cents() if is_manual(original, names) else 0
priced.append({**price(item.mode, str(item.metres), item.grade, extra,
minimum=Decimal('0') if item.split else Decimal('1'),
unit_cents=catalog.unit_cents(c, item.mode)),
'uploads': original['uploads'], 'production': original['production'],
'quality_status': original['quality_status'],
'quality_acknowledged': original['quality_acknowledged'],
'residue_accepted': original.get('residue_accepted', 0),
**({'residue_accepted_at': original['residue_accepted_at']}
if original.get('residue_accepted_at') else {}),
**({'stroke_px': original['stroke_px'], 'stroke_class': original['stroke_class']}
if original.get('stroke_class') else {}),
**({'stroke_choice': original['stroke_choice']} if original.get('stroke_choice') else {}),
**({'stroke_choice_at': original['stroke_choice_at']}
if original.get('stroke_choice_at') else {}),
**({'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 {}),
**({'split': original['split']} if original.get('split') else {})})
bill_splits(priced)
# Progressive bands (front 8.2): one price for the whole quantity of each
# product, chosen by the order's total billed metres of that mode.
totals = {}
for item in priced:
totals[item['mode']] = totals.get(item['mode'], Decimal('0')) + Decimal(item['billed_metres'])
banded = {}
for mode, total in totals.items():
price_for_total = catalog.unit_cents_for(c, mode, total)
if price_for_total != catalog.unit_cents(c, mode):
banded[mode] = price_for_total
apply_bands(priced, banded)
items_total = sum(i['total_cents'] for i in priced)
# The coupon discounts the items, after their bands, never freight or the
# treatment (front 8.3). It is checked again here: a quote that waited may
# have met an expiry or a use limit since it was created.
coupon = None
if draft.get('coupon'):
coupon = coupons.check(c, draft['coupon'], (draft.get('customer') or {}).get('cnpj'), priced)
# The montador assembles the sheet itself: the treatment rule does not apply.
cart = cart_pricing.price_cart(
c, [item.model_dump(mode='json') for item in items], names,
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']
for priced_item, original in zip(priced, draft['items']):
priced_item.update({
'uploads': original['uploads'], 'production': original['production'],
'quality_status': original['quality_status'],
'quality_acknowledged': original['quality_acknowledged'],
'residue_accepted': original.get('residue_accepted', 0),
**({'residue_accepted_at': original['residue_accepted_at']}
if original.get('residue_accepted_at') else {}),
**({'stroke_px': original['stroke_px'], 'stroke_class': original['stroke_class']}
if original.get('stroke_class') else {}),
**({'stroke_choice': original['stroke_choice']} if original.get('stroke_choice') else {}),
**({'stroke_choice_at': original['stroke_choice_at']}
if original.get('stroke_choice_at') else {}),
**({'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', ''),
metres, items_total)
except ValueError as exc:
raise HTTPException(422, str(exc))
treatment = 0
if draft.get('treatment'):
# The designer's treatment is offered only when switched on and priced.
offer = catalog.current(c)['tratamento']
treatment = offer['unit_cents'] if offer['enabled'] else 0
approved = {'customer': draft['customer'], 'items': priced, 'freight': quoted_freight,
'destination': draft.get('destination'),
# The customer's proof only above 10 m (Dropstar, 2026-10-28).
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
# Designer treatment is one fixed service line (front 5).
**({'treatment': {'cents': treatment, 'hours': 24}} if treatment 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).
**({'coupon': coupon} if coupon else {}),
# 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}
'total_cents': items_total - discount + quoted_freight['total_cents']
+ 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

@@ -21,7 +21,8 @@ MARGIN = 4 * MM
ROOM = WIDTH - 2 * MARGIN
FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'}
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas',
'premium': 'DTF Têxtil Premium · folha montada'}
METHODS = {'pix': 'Pix', 'card': 'Cartão', 'cash': 'Dinheiro', 'credit': 'Crédito do cliente'}
# Helvetica's widths for what the tables in printfile.py leave out.
EXTRA = {'$': 556, '(': 333, ')': 333, '_': 556, '#': 556, '—': 1000, '@': 1015, '&': 667, '+': 584, "'": 191}

View File

@@ -142,14 +142,20 @@ def quote_view(c, row, order=None, attempt=None, known=False):
items = (row['approved'] or row['draft']).get('items') or []
treatment = (row['approved'] or {}).get('treatment')
if not treatment and (row['draft'] or {}).get('treatment'):
offer = catalog.current(c)['tratamento']
if offer['enabled'] and offer['unit_cents'] > 0:
treatment = {'cents': offer['unit_cents'], 'hours': 24}
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

@@ -8,6 +8,7 @@ are those of the format its name claims (a PNG that really is a PNG, not a
program renamed .png). That is the check the client chose for large files; it
does not look for malware inside a valid file.
"""
import logging
import re
import socket
import struct
@@ -16,6 +17,7 @@ from fastapi import HTTPException
from .core.auth import audit
from .core.db import connect
from .core.limits import scan_limit_bytes
from .grade_check import stored_pdf_dpi
def require_clean(row):
if not row['complete'] or row['scan_state'] != 'clean':
@@ -144,11 +146,22 @@ def scan_one(storage, scanner=None):
finally:stream.close()
except Exception:
state,reason='error','Malware scanner unavailable; file remains blocked'
# A PDF's resolution is worked out here, once, so checkout never reads
# it (Critical Corrections 2). A failure leaves it for the fallback.
checked,pdf_dpi_value=False,None
if state=='clean' and name.lower().endswith('.pdf'):
try:
pdf_dpi_value=stored_pdf_dpi(storage,row)
checked=True
except Exception:
logging.exception('Could not work out the PDF DPI of upload %s',row['id'])
c.execute("""UPDATE dtf_local.uploads SET name=%s,scan_state=%s,scan_reason=%s,scanned_at=now(),
scan_after=now()+interval '1 minute',
pdf_checked=CASE WHEN %s THEN true ELSE pdf_checked END,
pdf_dpi=CASE WHEN %s THEN %s ELSE pdf_dpi END,
expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END
WHERE id=%s""",(name,state,reason,state,row['id']))
audit('artwork_scan', upload=str(row['id']), result=state)
WHERE id=%s""",(name,state,reason,checked,checked,pdf_dpi_value,state,row['id']))
audit('artwork_scan', upload=str(row['id']), result=state, c=c)
return True
def scan_loop(storage):

View File

@@ -284,11 +284,18 @@ CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names (
-- from the console); administrators manage users and machines; gestão runs
-- the business; designers approve artwork; operadores print; revisores check
-- the printed sheet and are the only ones to release it to Finalizado;
-- vendedores only read.
-- vendedores only read; expedição assembles sheets in the Kanban's montador.
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin';
ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro'));
-- Created once, and widened only by a migration: re-adding it on every start
-- would let an older image narrow the list and refuse rows written under a
-- later one, and the database would not finish starting.
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='operators_role'
AND conrelid='dtf_local.operators'::regclass) THEN
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao'));
END IF;
END $$;
-- Print machines and which products each prints. An order gets its machine
-- when someone pulls it into Imprimindo; no machine is assigned at payment.
-- limit_metres remains the load shown for a machine.
@@ -410,11 +417,16 @@ UPDATE dtf_local.accounts a SET email_verified=true WHERE NOT a.email_verified A
-- E-mail kinds: a password-recovery link, a code, the notice that an account
-- already exists, the notice of a changed e-mail, a customer's paid order,
-- the team's alerts and a test.
-- Defined once, here: the schema runs on every start, and an earlier, narrower
-- copy would refuse the rows of the kinds added after it.
ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check;
ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
CHECK(kind IN ('reset','code','account','notice','order','alert','test'));
-- Created once, and widened only by a migration: the schema runs on every
-- start, and re-adding an earlier, narrower copy would refuse the rows of the
-- kinds added after it.
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='mail_queue_kind_check'
AND conrelid='dtf_local.mail_queue'::regclass) THEN
ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
CHECK(kind IN ('reset','code','account','notice','order','alert','test'));
END IF;
END $$;
-- The print proof (Dropstar, 2026-10-21): an order above 10 m, or one whose
-- customer asked for a proof at checkout, prints 20 cm first; the room marks
@@ -452,8 +464,13 @@ WHERE o.contact_since IS NOT NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.contac
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS origin text;
UPDATE dtf_local.orders SET origin='site' WHERE origin IS NULL;
ALTER TABLE dtf_local.orders ALTER COLUMN origin SET NOT NULL;
ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check;
ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento'));
-- Created once, and widened only by a migration; never re-added on start.
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='orders_origin_check'
AND conrelid='dtf_local.orders'::regclass) THEN
ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento'));
END IF;
END $$;
-- Rework (Dropstar's rules D-02 to D-04, 2026-10-26; the user's answers of
-- 2026-10-27). Gestão opens it with its cause, and the cause never changes
@@ -618,6 +635,15 @@ CREATE TABLE IF NOT EXISTS dtf_local.product_prices (
);
CREATE INDEX IF NOT EXISTS product_prices_current ON dtf_local.product_prices(product, starts_at DESC);
-- Front 7a: the stamp sizes of the Kanban's montador; Gestão edits them.
CREATE TABLE IF NOT EXISTS dtf_local.stamp_sizes (
letter text PRIMARY KEY CHECK (letter ~ '^[A-Z]{1,2}$'),
width_cm numeric(5,2) NOT NULL CHECK (width_cm > 0 AND width_cm <= 56),
updated_by text NOT NULL DEFAULT 'sistema',
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES ('A',20),('B',24),('C',27),('D',30)
ON CONFLICT (letter) DO NOTHING;
-- Front 8.2: a price may also have bands by the order's total metres of that
-- product: base price, then "from 5 m R$ Y", "from 20 m R$ Z" (jsonb list of
-- {"from_metres": "5", "unit_cents": 1990}, strictly increasing, at most 5).

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,37 +52,46 @@ 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
# _FILE as a path to a secret file, and one product mode is called "file".
PRODUCT_SETTINGS = {'file': 'TINY_PRODUCT_TEXTIL_FOLHA', 'avulsa': 'TINY_PRODUCT_TEXTIL_AVULSA',
'uvfile': 'TINY_PRODUCT_UV_FOLHA', 'uv': 'TINY_PRODUCT_UV_AVULSA'}
'uvfile': 'TINY_PRODUCT_UV_FOLHA', 'uv': 'TINY_PRODUCT_UV_AVULSA',
'premium': 'TINY_PRODUCT_TEXTIL_PREMIUM'}
# The common code prefix of a mode's SKUs ("DTFIMP.TX" for DTFIMP.TX.100CM,
# the metre, and DTFIMP.TX.0010CM to DTFIMP.TX.0090CM). When set, it replaces
# the mode's product id.
SKU_SETTINGS = {'file': 'TINY_SKU_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_TEXTIL_AVULSA',
'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA'}
'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA',
'premium': 'TINY_SKU_TEXTIL_PREMIUM'}
# Or a SKU per 10 cm ("DTFIMP.UV.010CM"), alone (2,30 m is 23 of it) or after
# a metre SKU ("DTFIMP.UV.1MT"): 2,30 m is 2 metres and 3 of the 10 cm.
STEP_SETTINGS = {'file': 'TINY_SKU10_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU10_TEXTIL_AVULSA',
'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA'}
'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA',
'premium': 'TINY_SKU10_TEXTIL_PREMIUM'}
METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_METRO_TEXTIL_AVULSA',
'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA'}
'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA',
'premium': 'TINY_SKU_METRO_TEXTIL_PREMIUM'}
# Dropstar's own catalogue (checked against its Tiny export, 2026-10-14): Têxtil
# as DTFIMP.TX.100CM per metre and DTFIMP.TX.0010CM to 0090CM for the rest, UV
# as DTFIMP.UV.1MT per metre and DTFIMP.UV.010CM per 10 cm, the ready sheet and
# loose artwork alike. The settings above only override these.
SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX'}
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',
'uv': 'DTF UV 27 cm · artes avulsas'}
'uv': 'DTF UV 27 cm · artes avulsas',
'premium': 'DTF Têxtil Premium 57 cm · folha montada'}
# How far back to look for an order a previous delivery may already have made.
SEARCH_DAYS = 7
# A "ready" event can come after corrections; it normally knows the Tiny id.
@@ -103,8 +113,19 @@ OUTSIDE_NOTES = {'pix': 'Pix', 'card': 'cartão', 'cash': 'dinheiro', 'credit':
def internal_note(payload):
paid = payload.get('payment') or {}
how = f"pago fora do site ({OUTSIDE_NOTES.get(paid.get('method'), paid.get('method'))})" if paid.get('outside') else 'pago'
return f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}"
method = paid.get('method')
if method == 'faturado':
# A montador Venda order is invoiced (front 7a.3): its forma de
# recebimento is "Boleto" when the client's id is configured.
boleto = os.environ.get('TINY_RECEIPT_BOLETO', '').strip()
how = 'faturado (Boleto)' if boleto.isdigit() else 'faturado: forma de recebimento a definir'
else:
how = f"pago fora do site ({OUTSIDE_NOTES.get(method, method)})" if paid.get('outside') else 'pago'
note = f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}"
with_order = (payload.get('order') or {}).get('with_order')
if with_order:
note += f' · junto com o pedido de roupa nº {with_order}'
return note
STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES'
@@ -117,15 +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).
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 977493654}
# 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': 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
@@ -133,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
@@ -154,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"."""
@@ -169,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
@@ -201,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):
@@ -323,10 +367,12 @@ class TinyAuth:
operator = self._claim(c, state)
return self.authorize_url(operator, offline=False)
def status(self):
with self.connect() as c:
row = c.execute('''SELECT connected_by,connected_at,refresh_expires_at,updated_at,offline,
refresh_failed_at,refused_at FROM dtf_local.provider_tokens WHERE provider='tiny' ''').fetchone()
def status(self, c=None):
if c is None:
with self.connect() as c:
return self.status(c)
row = c.execute('''SELECT connected_by,connected_at,refresh_expires_at,updated_at,offline,
refresh_failed_at,refused_at FROM dtf_local.provider_tokens WHERE provider='tiny' ''').fetchone()
if not row:
return {'connected': False}
now = datetime.now(timezone.utc)
@@ -436,6 +482,48 @@ 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
name. Tiny's own search does the matching."""
text = str(query or '').strip()
digits = ''.join(ch for ch in text if ch.isdigit())
found = []
if digits and not any(ch.isalpha() for ch in text):
for form in search_forms(digits):
found += orders.request('GET', '/contatos', params={'cpfCnpj': form, 'limit': limit}).get('itens') or []
else:
found = orders.request('GET', '/contatos', params={'nome': text, 'limit': limit}).get('itens') or []
contacts, seen = [], set()
for entry in found:
if entry.get('id') in seen:
continue
seen.add(entry.get('id'))
contacts.append({'id': entry.get('id'), 'name': entry.get('nome') or '',
'document': entry.get('cpfCnpj') or '',
'email': entry.get('email') or '',
'phone': entry.get('telefone') or entry.get('celular') or ''})
return contacts[:limit]
def contact_payload(order, company=None):
"""A new contact, named after the company's razão social when the
registry gave it (app/cnpj.py), else the customer's name, else the
@@ -471,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
@@ -491,22 +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')
items.append({'produto': {'id': int(setting)}, 'quantidade': 1,
'valorUnitario': money(treatment['cents']),
'infoAdicional': 'Tratamento da arte pelo designer · +24 h'})
# 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'])
# 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'
@@ -518,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.
@@ -528,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'],
@@ -574,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."""
@@ -638,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):
@@ -653,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:
@@ -684,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 {}
@@ -718,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."""
@@ -746,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})
@@ -785,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,8 +5,10 @@ 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, unpaid
from . import mail, observability, unpaid
from .adapters import FakeTiny, LocalS3Storage, require_runtime
from .core.secrets import load as load_secret_files
from .core.db import connect
@@ -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']}/")
@@ -53,17 +90,37 @@ def cleanup():
c.execute("DELETE FROM dtf_local.security_events WHERE created_at<now()-interval '30 days'")
def tick():
"""Deliver at most one outbox job; True when there was one, False otherwise."""
global last_tick
processed = False
with connect() as c:
job = c.execute('SELECT * FROM dtf_local.outbox WHERE delivered_at IS NULL AND available_at <= now() ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1').fetchone()
if job:
processed = True
try:
receipt = adapters[job['provider']].deliver(job['event_key'], job['payload'])
c.execute('UPDATE dtf_local.outbox SET delivered_at=now(), receipt=%s, attempts=attempts+1, last_error=NULL WHERE id=%s', (Jsonb(receipt),job['id']))
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
def drain(limit=50):
"""Deliver up to `limit` outbox jobs in one pass, so a backlog leaves at
once instead of one job per second (Critical Corrections item 9)."""
for _ in range(limit):
if not tick():
return
def tiny_keepalive():
"""Keep a connected Tiny authorised even while no orders are sent.
@@ -115,10 +172,11 @@ def resolve_names():
names_thread.start()
def loop():
global last_cleanup
global last_cleanup, db_down_since
delay = 1
while True:
try:
tick()
drain()
if time.monotonic()-last_cleanup > 60:
cleanup()
# Approved quotes unpaid for 24 h expire on their own (front 9).
@@ -129,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):
@@ -151,6 +223,15 @@ class Health(BaseHTTPRequestHandler):
pass
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

@@ -27,6 +27,10 @@ x-app: &app
ALLOWED_HOSTS: ${ALLOWED_HOSTS:-localhost,127.0.0.1}
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-http://localhost:${SITE_PORT:-8080},http://localhost:${KANBAN_PORT:-8081},http://127.0.0.1:${SITE_PORT:-8080},http://127.0.0.1:${KANBAN_PORT:-8081}}
COOKIE_SECURE: "false"
# Sentry stays off locally unless real DSNs are set in .env.
SENTRY_DSN_API: ${SENTRY_DSN_API:-}
SENTRY_DSN_WEB: ${SENTRY_DSN_WEB:-}
SENTRY_ENVIRONMENT: ${SENTRY_ENVIRONMENT:-}
# Sandbox testing only: set PAYMENT_ADAPTER=mercadopago with the MP_* test
# credentials, or TINY_ADAPTER=tiny with a TINY_TOKEN, in .env. Never real
# production credentials on a developer machine.
@@ -98,7 +102,7 @@ x-app: &app
UPLOAD_PART_BYTES: ${UPLOAD_PART_BYTES:-8388608}
STORAGE_QUOTA_BYTES: ${STORAGE_QUOTA_BYTES:-53687091200}
OWNER_UPLOAD_QUOTA_BYTES: ${OWNER_UPLOAD_QUOTA_BYTES:-10737418240}
MAX_PENDING_UPLOADS: ${MAX_PENDING_UPLOADS:-10}
MAX_PENDING_UPLOADS: ${MAX_PENDING_UPLOADS:-30}
SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-2097152000}
networks: [local]
init: true
@@ -213,6 +217,10 @@ services:
api:
<<: *app
environment:
<<: *environment
# CI and local tests exercise the pool (Critical Corrections item 4).
DB_POOL: "on"
command: uvicorn app.app:app --host 0.0.0.0 --port 8000 --no-access-log
depends_on:
db-init: {condition: service_completed_successfully}
@@ -225,6 +233,10 @@ services:
worker:
<<: *app
environment:
<<: *environment
# CI and local tests exercise the pool (Critical Corrections item 4).
DB_POOL: "on"
command: python -m app.worker
depends_on:
api: {condition: service_healthy}
@@ -266,6 +278,7 @@ services:
# Empty unless testing Mercado Pago's card form; see docs/LOCAL_SETUP.md.
PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-}
PAYMENT_CHALLENGE_SOURCES: ${PAYMENT_CHALLENGE_SOURCES:-}
SENTRY_CSP_SOURCES: ""
ports:
# Published ports are host-wide even bound to loopback, so on a shared
# machine any of them can collide with something unrelated. CI overrides
@@ -291,6 +304,7 @@ services:
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:${STORAGE_PORT:-9000}}
PAYMENT_CSP_SOURCES: ""
PAYMENT_CHALLENGE_SOURCES: ""
SENTRY_CSP_SOURCES: ""
ports: ["127.0.0.1:${KANBAN_PORT:-8081}:80"]
networks: [local, edge]
depends_on:

View File

@@ -6,6 +6,8 @@ ARG PYTHON_BASE_IMAGE=python:3.12-slim@sha256:2f17fc044b579bab302c2e8054d3a686e2
FROM ${PYTHON_BASE_IMAGE}
ARG VCS_REF=unknown
# The commit this image was built from, as the Sentry release (app/observability.py).
ENV RELEASE=$VCS_REF
LABEL org.opencontainers.image.title="DTF Portal/API" \
org.opencontainers.image.revision="$VCS_REF" \
org.opencontainers.image.source="DTF System repository"

View File

@@ -27,7 +27,7 @@ server {
add_header Referrer-Policy no-referrer always;
add_header X-Frame-Options DENY always;
add_header Permissions-Policy "camera=(self), microphone=(), geolocation=()" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES} ${SENTRY_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
location = /health { access_log off; return 200 'ok'; }
location /api/ {
@@ -49,7 +49,7 @@ server {
# Always revalidate HTML/JS/CSS after a deployment. Without this, a browser
# can pair a new Kanban page with a cached older script after a rollout.
# The Site's product pages and cart are addresses of the same page (web/site-pages.js).
location ~ ^/(arquivo-por-metro|artes-avulsas|uv-arquivo-por-metro|uv-artes-avulsas|carrinho|pagamento|pagamento/pix)/?$ {
location ~ ^/(arquivo-por-metro|artes-avulsas|uv-arquivo-por-metro|uv-artes-avulsas|premium|carrinho|pagamento|pagamento/pix)/?$ {
expires -1;
try_files /index.html =404;
}

View File

@@ -15,6 +15,11 @@ PUBLIC_HOST=dtf.example.invalid
KANBAN_HOST=kanban-dtf.example.invalid
SITE_PORT=8080
KANBAN_PORT=8081
# API processes: 2 by default; 1 runs one process, as before. API only.
API_WORKERS=2
# Database connection pool: off keeps one connection per block, as before.
DB_POOL=off
DB_POOL_SIZE=20
R2_ENDPOINT=TBD
R2_PUBLIC_ENDPOINT=TBD
@@ -46,6 +51,10 @@ TINY_PRODUCT_TREATMENT=TBD
TINY_FORMA_ENVIO_RETIRADA=TBD
# true only at go-live, after the n8n DTFIMP designer branch is removed.
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>
@@ -69,6 +78,11 @@ BACKUP_SECRET_ACCESS_KEY=TBD
BACKUP_AGE_RECIPIENT=age1...
BACKUP_HOUR=3
# Sentry: empty DSNs keep it off; the environment defaults to production.
SENTRY_DSN_API=
SENTRY_DSN_WEB=
SENTRY_ENVIRONMENT=
# Names of external Portainer/Docker Swarm secrets, never their values.
DATABASE_URL_SECRET=TBD
DATABASE_ADMIN_URL_SECRET=TBD

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

@@ -8,6 +8,14 @@ x-app-environment: &app-environment
# Must differ from POSTGRES_PASSWORD: the runtime role is DML-only, and reusing
# the administrator credential would make that restriction meaningless.
DATABASE_PASSWORD: ${APP_DB_PASSWORD:?set APP_DB_PASSWORD}
# Reuse database connections per API/worker process when on; off keeps one
# connection per `with` block, exactly as before (the production default).
DB_POOL: ${DB_POOL:-off}
DB_POOL_SIZE: ${DB_POOL_SIZE:-20}
# Sentry: empty DSNs leave it off; the environment defaults to production.
SENTRY_DSN_API: ${SENTRY_DSN_API:-}
SENTRY_DSN_WEB: ${SENTRY_DSN_WEB:-}
SENTRY_ENVIRONMENT: ${SENTRY_ENVIRONMENT:-production}
S3_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
S3_BUCKET: ${R2_BUCKET:?set R2_BUCKET}
@@ -81,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
@@ -99,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:-}
@@ -116,6 +132,12 @@ x-app-environment: &app-environment
# Optional e-commerce channel id for Site orders. Without it the order still
# carries DTF-<n> as numeroPedidoEcommerce, with no channel.
TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-}
# 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
@@ -145,7 +167,7 @@ x-app-environment: &app-environment
# Sheets of several GB are the normal order, so room for many of them.
STORAGE_QUOTA_BYTES: "${STORAGE_QUOTA_BYTES:-536870912000}"
OWNER_UPLOAD_QUOTA_BYTES: "${OWNER_UPLOAD_QUOTA_BYTES:-53687091200}"
MAX_PENDING_UPLOADS: "10"
MAX_PENDING_UPLOADS: "30"
# ClamAV scans up to its own limit, 2000 MiB (infra/clamd.conf); a larger
# file, up to the 4 GB above, is released after the file-format check
# (app/scanning.py, check_large).
@@ -213,13 +235,20 @@ services:
api:
image: ${API_IMAGE:-gitea.blyzer.com.br/blyzer/dtf-api}:${IMAGE_TAG:-latest}
environment: *app-environment
environment:
<<: *app-environment
# Two uvicorn processes by default (Critical Corrections item 2, step 1):
# a slow 150 MB PDF check no longer holds every request in the only one.
# API_WORKERS=1 restores one process without a new image.
WEB_CONCURRENCY: "${API_WORKERS:-2}"
networks: [backend, egress]
read_only: true
# Swarm ignores the short `tmpfs:` key: a read-only container then has no
# writable /tmp at all. The long volume syntax is what a stack honours.
# 512 MiB, not 256: with two processes each may write a 150 MB PDF from the
# grade check at the same time.
volumes:
- {type: tmpfs, target: /tmp, tmpfs: {size: 268435456}}
- {type: tmpfs, target: /tmp, tmpfs: {size: 536870912}}
healthcheck:
test: [CMD-SHELL, 'python -c "import os,urllib.request; r=urllib.request.Request(\"http://localhost:8000/health\",headers={\"Host\":os.environ[\"PUBLIC_HOST\"]}); urllib.request.urlopen(r,timeout=3)"']
interval: 15s
@@ -228,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:
@@ -287,6 +317,8 @@ services:
# Mercado Pago's card form loads from these origins; empty keeps the
# Site at script-src 'self'. Set together with the Mercado Pago adapter.
PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-}
# The Sentry ingest origin(s) for connect-src; empty until the DSN exists.
SENTRY_CSP_SOURCES: ${SENTRY_CSP_SOURCES:-https://o4510863040905216.ingest.us.sentry.io}
# The bank's confirmation page for debit and other 3-D Secure cards is
# on the issuer's own domain, so it cannot be listed: "https:" lets
# frames and form posts reach it (never scripts). Empty turns it off.
@@ -305,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:
@@ -315,6 +348,8 @@ services:
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
PAYMENT_CSP_SOURCES: ""
PAYMENT_CHALLENGE_SOURCES: ""
# The Kanban reports to Sentry too; set from the browser DSN host.
SENTRY_CSP_SOURCES: ${SENTRY_CSP_SOURCES:-https://o4510863040905216.ingest.us.sentry.io}
networks: [backend]
ports:
- target: 8080
@@ -329,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

@@ -238,6 +238,24 @@ storage permits; otherwise reselect them. Saved quote IDs also survive reloads.
Clearing cookies loses a guest session, while registered customers can sign in
again. The operator can still inspect order records.
## Schema changes
`app/schema.sql` is the frozen baseline: every start runs it, and nothing new
is added to it. A schema change is a new file in `app/migrations/`, named with
a timestamp and a short slug, `YYYYMMDDHHMM_description.sql` (for example
`202611091607_checks-current-lists.sql`). `app/migrate.py` runs every file not
yet recorded in `dtf_local.migrations`, in name order, each recorded in the
same transaction and under an advisory lock; `app/bootstrap.py` and
`app/core/db.py` call it right after the schema and before the grants, so a
table a migration creates is granted to the runtime role. Never edit an applied
migration: add a new one instead. Any file in that folder whose name does not
match `^\d{12}_[a-z0-9-]+\.sql$` stops the start, so a typo is never skipped.
Widening a CHECK constraint is a DROP + ADD in a migration, with the full list;
`app/schema.sql` only creates the three initial ones when missing. A rollback
to an image at or after this change is safe: an older image ignores migration
names it does not know.
## Print files
Every paid order queues one print-file job per item. The worker renders a PDF

View File

@@ -173,7 +173,10 @@ affect stored data or retention.
In the Portainer stack variables, change `IMAGE_TAG` from `latest` to the full
SHA of the last known-good Gitea commit and redeploy. This rolls back Site, API,
Kanban, and worker code; it does not undo database migrations or restore data.
After recovery and a corrected release, return `IMAGE_TAG` to `latest`.
Rolling back to an image from before the timestamped migrations can still fail
if the data uses newer values; images from that change on ignore migration
names they do not know, so a rollback is safe. After recovery and a corrected
release, return `IMAGE_TAG` to `latest`.
## 6. Before opening to customers
@@ -207,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
@@ -223,6 +229,36 @@ If a service is refused, the contract uses other codes: set `CORREIOS_COD_PAC`
or `CORREIOS_COD_SEDEX`. Correios price by the box, so `JADLOG_CAIXA_CM` and the
package weights must be set (they already are for Jadlog).
## 9. API processes
`API_WORKERS` is how many uvicorn processes the API container runs (default 2;
`1` runs one process, as before). More than one keeps a slow checkout, such as
a PDF of up to 150 MB being checked, from holding every other request in the
only process; the API's `/tmp` is sized for two such checks at once. It applies
to the API only, never to the worker. Set it in the stack's environment and
redeploy.
## 10. Database connection pool
`DB_POOL` reuses database connections inside each API process and the worker
instead of opening one per `with` block (default `off`, the previous
behaviour). Set it to `on` in the stack's environment and redeploy to keep
between 1 and `DB_POOL_SIZE` connections per process (`DB_POOL_SIZE` defaults
to 20); set it back to `off` to return to one connection per block.
## 11. Sentry
Sentry is built into the API, the worker, the Site and the Kanban, and stays
off while the DSNs are empty. Set `SENTRY_DSN_API` and `SENTRY_DSN_WEB` in the
stack's environment, and optionally `SENTRY_ENVIRONMENT` (defaults to
`production`). The API and worker initialise from `SENTRY_DSN_API`; the browser
reads `SENTRY_DSN_WEB` from `/api/session` on the Site and from
`/api/operator/me` on the Kanban. When the DSNs exist, also set
`SENTRY_CSP_SOURCES` to the Sentry ingest origin, such as
`https://o123.ingest.sentry.io` (or `https://*.ingest.sentry.io`), so the CSP
`connect-src` allows the browser to send events. No image change is needed to
switch it on: update the stack variables and redeploy.
## Current blocker
This is the final deployment shape, but it is not authorized for production

View File

@@ -9,7 +9,7 @@ server {
add_header Referrer-Policy no-referrer always;
add_header X-Frame-Options DENY always;
add_header Permissions-Policy "camera=(self), microphone=(), geolocation=()" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES} ${SENTRY_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
location = /health { access_log off; return 200 'ok'; }
location /api/ {
limit_req zone=api_limit burst=100 nodelay;

View File

@@ -34,6 +34,7 @@ certifi==2026.10.19 \
# via
# httpcore
# httpx
# sentry-sdk
click==8.5.0 \
--hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \
--hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34
@@ -453,6 +454,10 @@ psycopg-binary==3.2.9 \
--hash=sha256:fa5c80d8b4cbf23f338db88a7251cef8bb4b68e0f91cf8b6ddfa93884fdbb0c1 \
--hash=sha256:fb7599e436b586e265bea956751453ad32eb98be6a6e694252f4691c31b16edb
# via psycopg
psycopg-pool==3.2.8 \
--hash=sha256:5474137f3a58e697e0141d0311e70ec067fc4466031496d7f9ef3e2c28a1dc09 \
--hash=sha256:854e17c2a637c3b9f8d8b24faad57d4cf850baf3fc03ca56ef7e5b4998e391b9
# via -r infra/requirements.txt
pydantic==2.13.5 \
--hash=sha256:346a034f080da3755d8e9cb5e00e8b07de1d39e4f6e2c87d8ab7cafa0b269a73 \
--hash=sha256:51a9c5f7b2f8e636f04c6cada605d9b6a3bf1348fdf945a3d8869b19bba0ee08
@@ -612,6 +617,14 @@ s3transfer==0.13.1 \
--hash=sha256:a981aa7429be23fe6dfc13e80e4020057cbab622b08c0315288758d67cabc724 \
--hash=sha256:c3fdba22ba1bd367922f27ec8032d6a1cf5f10c934fb5d68cf60fd5a23d936cf
# via boto3
segno==1.6.6 \
--hash=sha256:28c7d081ed0cf935e0411293a465efd4d500704072cdb039778a2ab8736190c7 \
--hash=sha256:e60933afc4b52137d323a4434c8340e0ce1e58cec71439e46680d4db188f11b3
# via -r infra/requirements.txt
sentry-sdk==2.74.0 \
--hash=sha256:40b205af015649df3ec9986e057ce24ce85956bee3fb75efa72c93aa7036bdff \
--hash=sha256:dd91d75aacaef636006b579ac3ddb2fdbc9dce35f00f4b353b6b1b110c6b256a
# via -r infra/requirements.txt
six==1.17.0 \
--hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \
--hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81
@@ -629,6 +642,7 @@ typing-extensions==4.16.0 \
# anyio
# fastapi
# psycopg
# psycopg-pool
# pydantic
# pydantic-core
# starlette
@@ -642,7 +656,9 @@ typing-inspection==0.4.4 \
urllib3==2.7.0 \
--hash=sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c \
--hash=sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897
# via botocore
# via
# botocore
# sentry-sdk
uvicorn==0.34.2 \
--hash=sha256:0e929828f6186353a80b58ea719861d2629d766293b6d19baf086ba31d4f3328 \
--hash=sha256:deb49af569084536d269fe0a6d67e3754f104cf03aba7c11c40f01aadf33c403

View File

@@ -2,8 +2,11 @@ fastapi==0.141.1
starlette==1.6.0
uvicorn==0.34.2
psycopg[binary]==3.2.9
psycopg-pool==3.2.8
boto3==1.38.23
httpx==0.28.1
pillow==13.0.0
pikepdf==10.13.0.post1
pypdfium2==5.14.0
segno==1.6.6
sentry-sdk==2.74.0

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

@@ -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');

View File

@@ -24,6 +24,7 @@ const chrome=spawn(process.env.CHROME_BIN||'/usr/bin/google-chrome-stable',[
const pause=ms=>new Promise(r=>setTimeout(r,ms));
let stderr='';chrome.stderr.on('data',data=>stderr+=data.toString());
const clients=[];
let kanban,testMachine;
async function waitFor(fn,description,timeout=30000){const end=Date.now()+timeout;while(Date.now()<end){if(await fn())return;await pause(200);}throw new Error('Timeout: '+description);}
class Page {
constructor(ws){this.ws=ws;this.next=0;this.pending=new Map();this.errors=[];
@@ -141,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.
@@ -157,18 +160,28 @@ try{
const qid=await site.eval('localStorage.getItem("dtf-quote")');
// The server charged what the Site showed.
assert.equal(await site.eval(`dtfApi('/quotes/'+${JSON.stringify(qid)}).then(q=>q.approved.items[0].total_cents)`),itemCents);
const kanban=await page(kanbanOrigin);
kanban=await page(kanbanOrigin);
await kanban.fill('#email',process.env.OPERATOR_EMAIL||'operator@example.test');
await kanban.fill('#password',process.env.OPERATOR_PASSWORD||'local-operator-only');
await kanban.eval('document.getElementById("login").requestSubmit()');
// Quotes live in their own tab; an automatic approval is listed as such.
await waitFor(()=>kanban.eval('!document.getElementById("app").hidden'),'Kanban sign-in');
// The test makes its own machine, so it runs on a fresh database and on its own.
testMachine=await kanban.eval(`api('/machines',{name:'Browser test '+Date.now(),products:['textil']}).then(r=>r.id)`);
await kanban.eval('load(true)');
await waitFor(()=>kanban.eval(`board.machines.some(m=>m.id===${JSON.stringify(testMachine)})`),'test machine on the board');
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');
@@ -222,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.
await waitFor(()=>kanban.eval(`board.machines.some(m=>m.active&&m.products.includes('textil'))`),'a textile machine');
const machineId=await kanban.eval(`board.machines.find(m=>m.active&&m.products.includes('textil')).id`);
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');
// 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;
// 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'){
@@ -270,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.
@@ -285,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});
@@ -335,6 +354,52 @@ try{
await waitFor(()=>site.eval('window.scrollY===0'),'screenshot scroll position');
await site.screenshot('output/local/site.png');
await kanban.screenshot('output/local/kanban.png');
// Números lives in its own file now: the tab must still load after kanban.js.
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
&& document.querySelector('#quote-list').children.length>0
&& document.querySelector('#reviews').children.length>0`),'Cotações tab and review panel');
// Usuários, machines and each machine's sheet live in their own file too.
await kanban.click('[data-tab="users"]');
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');
@@ -368,4 +433,10 @@ try{
console.log('Screenshots: output/local/site.png and output/local/kanban.png');
console.log('PASS: filename XSS escaping with CSP bypassed, no stored operator password, logout clears browser file blobs.');
}catch(error){console.error(error);if(stderr)console.error(stderr.slice(-1500));process.exitCode=1;}
finally{for(const p of clients)p.ws.close();chrome.kill();}
finally{
if(testMachine&&kanban){
try{await kanban.eval(`api('/machines/'+${JSON.stringify(testMachine)}+'/delete',{})`);}
catch(e){console.error('Could not delete the test machine '+testMachine+':',e.message||e);}
}
for(const p of clients)p.ws.close();chrome.kill();
}

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:

83
tests/grade_rules_test.py Normal file
View File

@@ -0,0 +1,83 @@
"""The art grade rules: the designer warning and the required treatment (8.5).
Run against the local stack: SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost
python -m tests.grade_rules_test
"""
import secrets
from uuid import uuid4
from app.core import db
from tests.print_file_test import artwork
from tests.smoke_test import Client, item_spec, upload_bytes
def quote_body(item, treatment, mail):
body = {'request_key': str(uuid4()),
'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail},
'items': [item], 'freight': {'service': 'pickup'}}
if treatment:
body['treatment'] = True
return body
def run():
tag = secrets.token_hex(4)
mail = f'grade-{tag}@example.test'
client = Client()
client.call('/session')
manager = Client()
manager.call('/session')
manager.call('/operator/me', operator=True)
manager = manager.operator_client
price_id = quote_id = upload_id = None
rules_set = False
treatment_enabled = True
try:
products = {row['id']: row for row in manager.call('/operator/site/products')['products']}
treatment_enabled = products['tratamento']['enabled']
manager.call('/operator/site/products/tratamento', {'enabled': True})
price_id = manager.call('/operator/site/products/tratamento/prices', {'unit_cents': 1000})['id']
manager.call('/operator/site/grade-rules', {'aviso': 100, 'tratamento': 100})
rules_set = True
rules = manager.call('/operator/site/grade-rules')
assert rules['aviso'] == 100 and rules['tratamento'] == 100, rules
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, aspect=2),
'quality_status': 'warning', 'quality_acknowledged': True}
refused = client.call('/quotes', quote_body(item, False, mail), expected=422)
assert refused['detail'] == ('Sua arte tem nota 50: para imprimir com qualidade, '
'o Ajuste Fino é obrigatório neste pedido.'), refused
made = client.call('/quotes', quote_body(item, True, mail))
quote_id = made['id']
assert made['status'] == 'approved', made
approved = client.call('/quotes/' + quote_id)['approved']
assert approved['grade_flags'] == {'aviso': 50, 'tratamento': 50}, approved
assert approved['treatment'] == {'cents': 1000, 'hours': 24, 'arts': 1,
'unit_cents': 1000}, approved
assert approved['total_cents'] == 9990, approved
print('PASS: the grade rule requires Ajuste Fino and flags the order with the worst grade')
finally:
if rules_set:
try:
manager.call('/operator/site/grade-rules', {'aviso': None, 'tratamento': None})
except Exception:
pass
with db.connect() as c:
if quote_id:
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote_id,))
if price_id:
c.execute('DELETE FROM dtf_local.product_prices WHERE id=%s', (price_id,))
if upload_id:
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s', (upload_id,))
try:
manager.call('/operator/site/products/tratamento', {'enabled': treatment_enabled})
except Exception:
pass
if __name__ == '__main__':
run()

99
tests/label_test.py Normal file
View File

@@ -0,0 +1,99 @@
"""The 10x15 thermal label at Finalizado (Fase 2, front 10).
Run inside the API container: python -m tests.label_test
"""
from urllib.error import HTTPError
from urllib.request import Request
from uuid import uuid4
from psycopg.types.json import Jsonb
from app.core import db
from tests.smoke_test import BASE, Client, with_host
from tests.users_test import PASSWORD, order_fixture
def label_page(client, order_id, expected=200):
"""GET the label as the browser does; returns the HTML (or the error body)."""
request = Request(BASE + '/api/operator/orders/' + order_id + '/label', headers=with_host())
try:
with client.opener.open(request, timeout=30) as response:
assert response.status == expected, (response.status, expected)
assert response.headers.get_content_type() == 'text/html', response.headers
return response.read().decode()
except HTTPError as error:
if error.code != expected:
raise AssertionError((error.code, expected, error.read().decode())) from error
return error.read().decode()
def user(superadmin, tag, role, name):
email = f'etiqueta-{tag}-{role}@example.test'
superadmin.call('/operator/users',
{'name': name, 'email': email, 'role': role, 'password': PASSWORD}, operator=True)
client = Client()
client.call('/session')
client.call('/operator/login', {'email': email, 'password': PASSWORD})
return client
def run():
su = Client()
su.call('/session')
su.call('/operator/me', operator=True) # the default superadmin
tag = uuid4().hex[:6]
revisor_email = f'etiqueta-{tag}-revisor@example.test'
revisor = user(su, tag, 'revisor', 'Revisor Etiqueta')
designer = user(su, tag, 'designer', 'Designer Etiqueta')
expedicao = user(su, tag, 'expedicao', 'Expedição Etiqueta')
owner = uuid4()
with db.connect() as c:
_, order_id = order_fixture(c, owner, 'file', metres='2.5')
snapshot = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone()['snapshot']
snapshot['customer']['name'] = 'Cliente Etiqueta'
snapshot['destination'] = {'recipient': 'Loja Etiqueta', 'street': 'Rua A', 'number': '10',
'complement': '', 'district': 'Centro', 'city': 'Franca',
'state': 'SP', 'postal_code': '14400000'}
snapshot['freight'] = {'service': 'jadlog', 'description': 'Jadlog .Package', 'total_cents': 1500}
c.execute("UPDATE dtf_local.orders SET snapshot=%s, state='fin' WHERE id=%s",
(Jsonb(snapshot), order_id))
c.execute("INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) "
"VALUES(%s,'rev','fin',%s,'')", (order_id, revisor_email))
number = c.execute('SELECT number FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone()['number']
oid = str(order_id)
# The first computer claims the automatic print; the second does not.
assert su.call(f'/operator/orders/{oid}/label/claim', {}, operator=True) == {'print': True}
assert su.call(f'/operator/orders/{oid}/label/claim', {}, operator=True) == {'print': False}
# A reprint always prints, on any computer.
assert su.call(f'/operator/orders/{oid}/label/reprint', {}, operator=True) == {'print': True}
# The page is the server's HTML: customer, what the order is, delivery, QR.
page = label_page(revisor, oid)
assert 'Cliente Etiqueta' in page, page
assert 'DTF · 1 folha · 2,50 m' in page, page
assert 'Envio · Jadlog .Package' in page, page
assert 'Revisor Etiqueta' in page, page
assert '<svg' in page, page
# No Tiny receipt: the order's own DTF number, also in the QR.
assert f'DTF-{number}' in page, page
# With the Tiny sale receipt, its number takes the big type and the QR.
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.outbox(event_key,provider,payload,receipt,delivered_at)
VALUES(%s,'tiny',%s,%s,now())''', (f'{oid}:paid:tiny', Jsonb({}),
Jsonb({'tiny_number': '98765'})))
page = label_page(revisor, oid)
assert '98765' in page, page
assert f'DTF-{number}' not in page, page
# Only the label profiles print it: the designer may not, Expedição may.
label_page(designer, oid, expected=403)
label_page(expedicao, oid)
print('PASS: the label page, one automatic print, reprint, Tiny number, designer refused '
'and Expedição allowed')
if __name__ == '__main__':
run()

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))

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