Compare commits

..

464 Commits

Author SHA1 Message Date
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
3d8be36d65 Merge front 8.3: discount coupons
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 6m28s
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 15:40:29 -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
60105e7cbe feat: Site videos up to 500 MB
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 6m23s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m6s
Dropstar uploads the six videos themselves; 100 MB was our own limit and
could stop a longer video in the videos area. ClamAV scans up to 2000 MiB,
so 500 MB is still scanned.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 15:26:36 -03:00
Cauê Faleiros
1d0353fe54 feat: discount coupons (front 8.3)
Gestão creates coupons in the Site tab: a code, a percentage or an amount
per billed metre, validity, a minimum of metres, use limits in all and per
customer, one product or all, and a note; they can be paused and deleted
(kept for history). The customer types the code at checkout; the server
checks it when the quote is made and again at approval, discounts only the
eligible items after the bands (never freight or the treatment) and keeps
the coupon on the order. Tiny gets the discount, the e-mail and receipt
show it, the order panel carries a badge and Números counts orders,
metres, discount and money per coupon.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 15:24:44 -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
07ee38d677 Merge front 8.2 and 8.4: price bands, videos in the Site tab
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 6m17s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m6s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 15:00:58 -03:00
Cauê Faleiros
2f85a38562 feat: the videos panel in the Site tab, captions optional (front 8.4)
Dropstar uploads the six videos themselves, so the panel moves from
Integrações to the Site tab, next to products and prices. A video can be
published without a VTT: the Site plays it without a captions track.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 14:50:18 -03:00
Cauê Faleiros
2a6732eb37 feat: progressive price bands per product (front 8.2)
A price may carry up to five bands, "from N m, R$ Y": the order's total
billed metres of that product chooses one price for its whole quantity,
the manual-file extra still on top. Bands start and become history with
their price row. The Site charges the same band for the cart, shows
"Faltam X m para R$ Y o metro" and lists the bands under the price
table; the Kanban's Site tab edits them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 14:30:15 -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
c5e7a80b64 Merge front 8.1: products and prices in the Site tab
All checks were successful
Build and deploy / Publish images (push) Successful in 1m6s
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 6m6s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

# Conflicts:
#	app/schema.sql
2026-11-09 14:10:56 -03:00
Cauê Faleiros
c88d81588e feat: products and prices from the database, edited in the Kanban's Site tab (front 8.1)
Gestão and the administrators switch each product on and off and set its
price from a start date; a price that has started is history and cannot
change, a scheduled one can be cancelled. The Site and the server read
the current price; with no row the code's prices and TREATMENT_CENTS
still apply, so nothing changes until someone sets one. A switched-off
product disappears from the Site and new quotes with it are refused.
Approved quotes and paid orders keep their price.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 13:50:45 -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
Cauê Faleiros
049f51b56a fix: orders from before the PNG print file are generated again, once
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 6m1s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m0s
An order generated before item 13 had a PDF print file and no strips,
so the 100% viewer opened it blank. Those still in Arte recebida, with
no approved final and no customer correction, are generated again once
as PNG with strips (migration png-regenerate-v1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 13:25:52 -03:00
Cauê Faleiros
a69b9f71c2 fix: camera, storage images and videos allowed by the page headers
Permissions-Policy forbade the camera, so the review's "Revisar"
(front 2) could never open it. img-src left out the storage host, so
the customer's review photo did not load. And the production CSP had no
media-src at all: the Site videos (front 4), served from storage, would
not play. The camera is allowed for the page itself only; microphone
and geolocation stay off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 13:25:52 -03:00
Cauê Faleiros
4219db8215 feat: Números per machine, month by month (front 1b)
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 1m4s
A new Números section, "Máquinas, mês a mês", one column per machine
and a month at a time: metres printed, metres per hour and hours
running (time shared by two orders counted once), hours stopped with
their reasons; metres per film roll, ink per 100 m by colour, powder
per 100 m; supplies, parts and total cost per metre; what the printed
orders sold, the month's contribution and since installation; and the
return in % and months to pay back once Gestão types the price.

Refills stand for consumption. Every ratio without data shows "—".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 12:50:48 -03:00
Cauê Faleiros
29518795a5 feat: each machine's sheet, counters and alerts (front 1a)
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 6m20s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m11s
The machine's name in Imprimindo (and "Ficha" in Usuários › Máquinas)
opens its sheet: metres since the last cleaning and since the last film
change, each supply's estimate, pending alerts and the entries. The room
enters supplies (film, ink by colour, powder; a supply without cost
takes the last one), parts (cap, damper, head, wiper, other) and events
(cleaning, head alignment, a stop with reason and minutes). Gestão types
the price, installation date and supply minimums.

Alerts appear when someone pulls the next card onto the machine, never
mid-print: 10 m since the last cleaning, 20 m after a film change
without aligning the head, and a supply at its minimum. Marked done it
records the event; postponed once it lets one more card through. The
server refuses the pull otherwise. Counters start when the sheet went
live (machines.log_since), not from everything printed before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 12:19:31 -03:00
Cauê Faleiros
b280e0cfa6 feat: review photo or video in Revisão (front 2)
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 6m4s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m6s
In Revisão the card gets "Revisar": a photo or a video of up to 30 s of
the printed sheet, from the computer's or the phone's camera in the
browser, or a file already recorded. It is attached to the order as
DTF-<n>-revisao-<seq> with when and who, kept 180 days, and copied by
the computers with the order folders to Kanban/Revisões/. A photo needs
1600 px on its longer side. An order above 1 m cannot reach Finalizado
without one. In Finalizado the customer's order page shows the photo.

The Revisor, Gestão and the administrators take it (capability
"inspect"). Dialogs opened from a card's face or the board (Revisar,
Editar tempos) now show over the page when the order panel is closed;
inside the closed panel they were invisible.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 11:39:15 -03:00
Cauê Faleiros
5aafd9ee91 fix: review of phase-2 stage 0 and fronts 5, 6 and 11
All checks were successful
Build and deploy / Publish images (push) Successful in 1m5s
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 5m7s
Build and deploy / Secret scan and release gate (push) Successful in 6s
- A paid treatment adds its 24 h to Arte recebida's acceptable time, on
  the card and in Números (fronts 5 and 11).
- TINY_PRODUCT_TREATMENT is a required Tiny setting once the treatment
  has a price, instead of every treated order failing at the Tiny.
- A quote reads each PDF once: Files caches the header and the DPI.
- A proof made from the parent's final split into parts uses the part
  that holds the finest stroke, not the last one (0.1).
- Prumo report: one format line per item, the time from the claim (kept
  on the finished print file), and the stroke class in customer words.
- The Site says the Prumo checks the art, and a too-tall PNG no longer
  says "Este PDF".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 10:45:43 -03:00
Cauê Faleiros
5a51084c8f ci: run the nine test files the phase-2 commits added
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 5m14s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m9s
finished_order_test, machine_pull_test, site_video_test and
treatment_gate_test join the integration suites; test_proof_cut,
test_proof_render, test_prumo, test_speed and test_printpng_validate join
the unit tests. All pass; until now nothing ran them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 10:09:47 -03:00
Cauê Faleiros
1a9611942d feat: an approved order nobody paid expires in 24 h (front 9)
All checks were successful
Build and deploy / Validate source (push) Successful in 1m15s
Build and deploy / Integration suite on a real stack (push) Successful in 5m10s
Build and deploy / Secret scan and release gate (push) Successful in 11s
Build and deploy / Publish images (push) Successful in 1m29s
An approved quote with no payment expires on its own after 24 h, never
while a Pix or card attempt is still live: the worker marks
quotes.expired_at, frees its files and e-mails the customer that the
order expired and can be sent again on the Site. The backlog from before
this front expires silently.

Kanban: Cotações › Aguardando pagamento shows when each one expires and
the review gets an "Abrir conversa" WhatsApp button; Números gets
"Pedidos sem pagamento" (made, paid, expired, waiting, abandonment rate).

release_files moves to app/payments.py so the worker can use it; an
expired quote no longer counts as open there. New tests/unpaid_test.py
in the integration job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 10:01:26 -03:00
Cauê Faleiros
448a7fa8c3 fix: a quote's review opens again
The originals list in a quote's review called download(uid, order.id)
after the proof-card change (d69e326), but a quote has no order: every
quote threw "order is not defined" and its review never opened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 10:01:10 -03:00
Cauê Faleiros
a712c69aca fix: align proof, treatment, metrics and site videos with PDF
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 5m44s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m22s
2026-11-06 15:27:48 -03:00
Cauê Faleiros
f4cd1842ca fix: Atrasados lists production stages and real orders only (front 11)
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 4m27s
Build and deploy / Publish images (push) Successful in 1m6s
A delivery is done when it leaves and a test card is not production. Only
pickup orders waiting in Finalizado can be late, and the top strip now
shows working columns; the finished pickup keeps its card colour and its
place in Números.
2026-11-06 13:15:30 -03:00
Cauê Faleiros
c8d03d3b94 feat: designer treatment as an optional paid line (front 5)
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 4m20s
Build and deploy / Publish images (push) Successful in 1m5s
TREATMENT_CENTS sets a fixed price per order; 0 keeps the option hidden.
The cart shows the designer treatment and adds 24 h; the quote total and
Tiny line carry it, and the card gets the "Tratamento pago" label. The
designer uploads the treated file through the existing card flow.
2026-11-06 13:07:22 -03:00
Cauê Faleiros
bdff73b76b feat: acceptable time per stage with late cards and alerts (front 11)
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 4m24s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m0s
Gestão edits the hours and the responsible for each column. A card past the
limit turns yellow, twice the limit red, and the board lists it under
Atrasados. Números compares the real median with the limit and counts the
passages that exceeded it in the period and today.
2026-11-06 12:52:53 -03:00
Cauê Faleiros
7e22262280 feat: the Site has a videos area and a floating product video (front 4)
All checks were successful
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 4m18s
Build and deploy / Publish images (push) Successful in 1m5s
The home lists the six DTF videos with their titles and state; a card opens
a modal player. A product page gets a muted, captioned 30 s floating video
when its file is configured. The files themselves are still to be recorded;
until then the cards say "Em produção".
2026-11-06 12:44:33 -03:00
Cauê Faleiros
b10eeead6e feat: Prumo tells the card and the customer what it did (front 6)
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 4m41s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m6s
Every order now carries a short report of the decisions that happened:
original format, conversion, resolution, background, residue, montage,
billed length, contraction, thin-stroke warning, parts and generation time.
The card shows it above the file; the payment summary shows the customer's
version. The upload keeps the original name so a renamed CDR/PDF is told.
2026-11-06 12:37:08 -03:00
Cauê Faleiros
25e4ac541a feat: the customer sees how long each site step is taking (0.12)
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 4m26s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m0s
The file card, the sheet preview and the analysis status now count the
seconds since the file arrived; the confirmation says the Prumo is
preparing the print file and the usual estimate per 10 m.
2026-11-06 12:18:02 -03:00
Cauê Faleiros
dc87d46801 fix: Prova OK gives the parent its Prumo final and queues it (0.1)
The proof answer is the parent's check: every ready full print file Prumo
generated becomes an active final, and the parent enters Arte conferida.
Items that still need hand preparation stay in Arte recebida.
2026-11-06 12:17:57 -03:00
Cauê Faleiros
c291f00e96 docs: note where the pricing parity test runs
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 6m44s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m36s
2026-11-06 11:41:15 -03:00
Cauê Faleiros
b97b895993 docs: the phase-2 roadmap records the completed stage 0 2026-11-06 11:39:55 -03:00
Cauê Faleiros
f78cb93ba7 test: the browser walkthrough follows the new final, residue and machine rules
The final file is a 300 DPI PNG; a ready sheet offers the residue
acceptance; an oversized PNG is refused; and the pull chooses the machine.
2026-11-06 11:39:23 -03:00
Cauê Faleiros
3d1293a3af test: a unique CNPJ in the search and the reset output (0.11) 2026-11-06 11:19:41 -03:00
Cauê Faleiros
2bcdb060fd feat: the launch reset keeps the order numbering and clears the folders (0.11)
The existing launch_reset now also empties the Kanban flow folders, keeps
Estampas/, and no longer restarts orders.number: DTF-1…DTF-15 already exist
in Tiny. It still refuses real money, counts first and needs APAGAR.
2026-11-06 11:11:36 -03:00
Cauê Faleiros
6351a094f4 feat: Números measures the site and the Prumo (0.12)
The browser records page load, upload speed and bytes, Prumo's check and
the loose-art montage; the quote keeps them and Números shows average and
p95 per period. Print generation and the payment-to-card time come from
the database. The upload bar already estimates its remaining time.
2026-11-06 11:09:36 -03:00
Cauê Faleiros
945c9e366a feat: the phase-2 reset script and the proof-order contact rule (0.11)
reset_board deletes orders, quotes, cards, uploads and their history, and
empties the Kanban flow folders while keeping Estampas and every setup
record. It is a dry run unless --yes is passed, and never resets the order
numbering. A proof order closes contact with Prova OK; orders without a
proof keep their "Contato feito" action.
2026-11-06 11:04:11 -03:00
Cauê Faleiros
054a642a61 test: the suite follows pull-only machines, the proof lock and 200 DPI
The old tests created orders with an automatic machine and moved them
without one. They now choose a machine or pass it to the pull, expect the
proof lock before any move, and use the 200 DPI clean grade.
2026-11-06 11:02:43 -03:00
Cauê Faleiros
392e7da85b fix: the proof crops the finest stroke and closes the contact wait (0.1)
The browser records where the thinnest stroke sits in the assembled film;
the proof takes a 15 cm window around it instead of always the top. A free
proof no longer fails the layout's billed-metres check, and answering the
proof card clears "Aguardando contato" and ends its timer.
2026-11-06 11:02:39 -03:00
Cauê Faleiros
d69e326125 feat: the proof card, machine pull and print file corrections (Dropstar, 05/11)
The proof card owns its final PNG, keeps its parent locked until the seller
answers, enters the queue first, and shares one machine with the parent.
The board no longer assigns a machine at payment; the puller records it.
A stalled print file times out with a card warning and a retry, finished
orders sort by completion, and finals are stored as PNG. The original
download carries the order number (items 0.1, 0.4 to 0.7 and 0.9).
2026-11-06 10:41:20 -03:00
Cauê Faleiros
0fc01315c7 feat: the site's third-round corrections on acceptance, DPI and the final file
Residue and thin strokes can be accepted on ready sheets and loose art,
with the consent and its time kept on the order. The resolution rule is
96/200 DPI, and a final file must be a transparent 300 DPI PNG. The art
score leaves the customer's cart and buy box (Dropstar, 2026-11-05).
2026-11-06 10:41:14 -03:00
Cauê Faleiros
94f1bfa733 fix: retention test reaches its file; items without a layout go to hand preparation
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 4m38s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m11s
The cleanup purges 50 expired files a pass, oldest first, and the suites
before the retention test now leave more than that: the test runs it until
its own fixture is reached. A print job for an item without a layout (an
order written straight to the database) is hand preparation, not a crash on
the footer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 20:57:42 -03:00
Cauê Faleiros
5520081184 feat: the proof card, a child order the seller answers (Dropstar, 30/10 and 03/11)
Some checks failed
Build and deploy / Validate source (push) Successful in 1m8s
Build and deploy / Integration suite on a real stack (push) Failing after 3m14s
Build and deploy / Publish images (push) Has been skipped
Build and deploy / Secret scan and release gate (push) Successful in 9s
An order with a proof (asked for at checkout, or above 10 m) gets a child
card "Prova": an order of its own (orders.parent_id), no sale, with the
film's first 30 cm as DTF-N-item-1-prova.png ("Prova do pedido DTF-N" in its
footer), which follows the flow up to Revisão like any card, hot folder
included. The order waits outside the queue, "Aguardando prova": it is not
pulled to Imprimindo, nor counted in the queue's places.

In Revisão the card is answered by the Vendedor, Gestão or the
Administrador (capability "proof"): Prova OK records who and when and puts
the order in Arte conferida when its finals are approved; Prova reprovada,
with its reason, sends the order back to Arte recebida, its final to be
approved again, and offers "Nova prova". Either way the card closes and
leaves the board. An order from before the cards keeps the old Prova OK.

The card is kept out of Tiny, e-mails, Números, the search, Finalizado and
the customer's account. Deleting an order takes its cards and their rows:
movements, order files and print files now cascade with their order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 20:39:52 -03:00
Cauê Faleiros
8b7d9f0bdb feat: "Abrir e conferir", the print file full screen, in pieces (item 7)
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 4m28s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m17s
The card's "Abrir e conferir" opens the order's print file full screen
(Dropstar's third round, item 7): zoom up to 100% real (one file pixel, one
screen pixel), the position in cm, the order's files one after the other
without closing, and the background behind the transparency light, dark or
checkered, remembered (Dropstar, 2026-10-30). Closed in Arte recebida, it asks
"Está OK?": the class of each item, prefilled with the measure, then
"Mover para Arte conferida" (the final approved, the class kept, the card
moved) or "Tratar a arte".

A 15 m film is loaded like a map: while the PNG is written, its strips of
512 rows go to storage at 100% and at each halving (app/printtiles.py,
originals/tiles/<upload>/), and the viewer (web/kanban-viewer.js) fetches
only those on screen. They go when their file expires. Storing a print file
that fails is now an attempt like a failed render, not a claim held for an
hour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 20:10:03 -03:00
Cauê Faleiros
e3a5ad6fa0 feat: printing files go into each machine's hot folder, part by part (item 10)
All checks were successful
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m13s
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 3m56s
Pulled to Imprimindo, an order's files go as a copy into
3. Imprimindo/<máquina>/<C1|C2|C3>/, the class of each item (chosen in the
Kanban, or measured by the Site), where FlexiPRINT takes them (Dropstar's
third round, item 10). A film in parts goes to the same machine, in order,
never more than two parts in its folder: the next is written when Flexi
takes one. The card says "Parte 3/7 imprimindo · 4/7 ripando".

The server decides what each folder gets (app/hotfolder.py,
dtf_local.hot_parts) and the Kanban's computers write it: each part is
claimed by one computer, so Flexi never gets it twice; a claim that did not
finish goes back to the queue; a part gone from its folder was taken and is
never written again; a card that leaves Imprimindo or is cancelled has what
Flexi did not take deleted. A part without a class waits for one, and the
class may still change in Imprimindo until its file is written.

The folder sync also follows files one by one, so the parts of a film over
15 m are no longer taken for replaced copies of each other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 17:05:08 -03:00
Cauê Faleiros
353935bed3 feat: the print file is a 300 DPI PNG, in parts of up to 15 m (item 13)
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 4m55s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m27s
FlexiPRINT's Spot OK 1 makes the white from transparency and reads it
reliably only from a PNG (Dropstar's third round, item 13): each order item
is now DTF-N-item-I.png, 300 DPI, RGBA on a transparent background, with its
footer; a film over 15 m leaves as DTF-N-item-I-pK.png parts, each with
"Parte K/N" in its footer, cut between pieces of loose art when it can be.

app/printpng.py never holds a whole sheet: the film is composed and written
in bands. Pillow encodes each band (it picks the PNG filters) and one zlib
stream takes them; a long PNG sheet is read band by band by wrapping its
compressed rows as small PNGs; a PDF page is drawn band by band at 300 DPI by
PDFium (pypdfium2, a self-contained wheel); loose art is turned and scaled
once. A 57 x 220 cm sheet peaks at 191 MB, a 15 m film at 279 MB.

The parts of an item are dtf_local.print_parts (print_files.upload_id stays
the first); the board, the final approval, the folders and the cleanup see
every part, and the Kanban approves and downloads them all. A large PNG or
PDF is now generated like any other; only other large formats go to hand
preparation, and the original no longer stands in as the print file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 16:53:35 -03:00
Cauê Faleiros
bd1e1772a7 feat: Dropstar's 03/11 answers on residue and item 16; wide areas count in the stroke
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 5m25s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m20s
- Residue: the acceptance stays on loose artwork only ("arquivo
  fracionado"), with their text. A ready sheet with residue goes back,
  as the designer cannot clean a closed sheet.
- Item 16, new rule, all three at once: thinnest stroke up to 4 px, at
  least 60% of the ink in areas 20 px or wider, at most 10% of the ink in
  strokes up to 4 px. One pop-up per file, on ready sheets and loose art,
  that does not block: "Imprimir assim mesmo (C1)" (default) or "Quero
  subir em dois arquivos". The ready sheet's three options are gone; the
  card notes that the customer was warned and printed as C1.
- The stroke reader counts the ink in wide areas with their edges and the
  ink in strokes up to 4 px, and areas wider than the measured distance now
  add axis samples: two edge pixels no longer make a solid art C1 ("Salmo
  91" was C1 at 3 px, now C3). The four test sheets still give 2, 5, 20
  and 4 px; the new rule triggers on 4 of the 9 real arts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:56:35 -03:00
Cauê Faleiros
a17f5fc08d fix: only the designer side approves files; specks are not strokes
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 3m52s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m14s
- "The designer approves every file" (Dropstar's rule D-16): the Operador
  leaves "produce", so it no longer approves final files, picks the
  contraction, treats the art or marks the contact wait. It pulls and
  prints. The order panel says the Designer approves and shows the
  contraction read-only; the profiles table follows.
- The stroke measure drops ink components under 30 px (at 300 DPI) before
  the distance, as Dropstar's method says (2026-10-30). Each strip keeps
  at least 30 rows of context, so a speck is always seen whole and a
  component cut by the strip is a stroke. One real order sheet went from
  C1 (2 px, specks) to C2 (5 px); Dropstar's four test sheets still give
  2, 5, 20 and 4 px. The artwork browser test checks widths 2, 5 and 6,
  and a C3 sheet with 300 specks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 11:10:23 -03:00
Cauê Faleiros
67fad3a2d7 fix: the profiles table says Financeiro only looks at Pagamentos
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 4m0s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m5s
Resolving a payment needs Gestão or Administrador (Dropstar, 2026-10-30:
Financeiro "vê Pagamentos"), and the table showed it as something Financeiro
does. It also lists registering an order paid outside the site, which
Administrador and Gestão do (D-35).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 10:37:35 -03:00
Cauê Faleiros
2615163fd3 feat: stroke class, residue per artwork, mixed strokes, sheets split by class
All checks were successful
Build and deploy / Validate source (push) Successful in 1m25s
Build and deploy / Integration suite on a real stack (push) Successful in 4m40s
Build and deploy / Secret scan and release gate (push) Successful in 12s
Build and deploy / Publish images (push) Successful in 1m38s
Round 3, items 9, 4, 16 and 17 (Dropstar, 2026-10-30).

- 9: the Site measures the thinnest stroke of each sheet and loose artwork
  (alpha > 40, chamfer distance in strips, width at local maxima, 1st
  percentile, at 300 DPI) and sends stroke_px and C1/C2/C3 with the item.
  The Kanban shows the class prefilled in the approve step; Produção may
  change it (POST /orders/{id}/contraction, who and when recorded), and the
  manifest carries it.
- 4: the residue check runs on each loose artwork, accepted per artwork; the
  sheet inherits what was accepted.
- 16: fine lines and solid areas in one file. Loose art: a pop-up with
  [Subir separado] [Continuar assim]. Ready sheet: protect the fine lines
  (default), protect the solid areas (stroke_choice client_c3, starts at C3)
  or go back and send two sheets, which holds the order.
- 17: loose art of fine (C1, C2) and solid (C3) strokes goes on separate
  sheets, each its own order item (split group/part/of) with its own file
  and class. Each sheet rounds to 10 cm and the 1 m minimum is charged once
  per group, since the customer did not choose the split. Cart, payment
  summary, portal, receipt and mail show it as such.
- The board loads quote views in two queries instead of two per quote.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 10:24:29 -03:00
Cauê Faleiros
388408d4d6 feat: drop a card on the machine it prints on; Pagamentos says who paid
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 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 57s
- Imprimindo: every active machine has its lane, and a card dragged
  from the queue onto a lane goes to that machine (if it prints the
  product and has a place), instead of the one it came with. The
  operator's pull still goes to the machine they are on (item 12).
- Pagamentos: each payment shows who tried to pay and what they were
  buying (the quote's customer and items, and its order if there is
  one); a click opens the customer's name, e-mail, CPF/CNPJ, WhatsApp
  and delivery, the quote, and Mercado Pago's id and status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:23:35 -03:00
Cauê Faleiros
a010b2507e fix: a stalled card says it only in red at its time, not as a mark too
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 3m41s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m1s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:03:23 -03:00
Cauê Faleiros
df601a7b6e fix: Números' rework meters are thin bars again
All checks were successful
Build and deploy / Integration suite on a real stack (push) Successful in 3m30s
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m11s
The panel filler and the meter's bar were both called .fill, so every bar
took the filler's 460 px; the filler is .fillbox now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:53:25 -03:00
Cauê Faleiros
67a9cd9533 fix: the item preview's tab says Montagem, so it fits beside Arte
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 3m25s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 53s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:17:35 -03:00
Cauê Faleiros
0b8eb143ad feat: the Kanban on the phone follows the phone mockup
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 3m40s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 56s
- Top bar with the logo, search and filters; at the bottom Produção,
  Cotações, Pagamentos, Números and "Mais" (Integrações, Usuários, the
  machine, the theme, the password, Sair) in a sheet.
- Produção: the stages as chips, the stage's metres and the session's
  machine over the cards, the queue's download as a button, the
  filters (product included) in a sheet.
- The order as a page: back, the order and its stage, the next step
  with its buttons at the bottom, the facts as rows, WhatsApp, Arquivos
  and Histórico; its actions in a sheet. A quote opens the same way.
- Pagamentos as cards, Números as the mockup's figures, chart and
  lists, Usuários as a list, Integrações as cards, the search as a page,
  dialogs as sheets, and the sign-in with the sheet rolling on top.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 15:00:08 -03:00
Cauê Faleiros
f5c8bcfb90 fix: Kanban panels keep their size; their lists scroll inside
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 3m35s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m1s
Creating users, machines or orders no longer changes the screen: Pessoas
and the Tiny log have a fixed height, Máquinas shows two and scrolls,
Pagamentos fills the window, Números' machines and treated art scroll in
their panels, and the board fills the window with each column scrolling
under its head. On the phone the pages scroll as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 14:42:18 -03:00
Cauê Faleiros
d2e340032e fix: the Kanban's login fits the window, the menus are the mockup's again
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 3m31s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m8s
- Sign-in: the page is the window's height, never scrolls; the sheet
  rolling under the marks is the design's (docs/design/folha-sapo-flor.svg).
- The account, refresh and order menus had lost their look with the old
  panel's rules; they are popovers again. The account menu leaves the
  theme to the rail's button, right above it.
- Números: panels of a row share their height; rework's lists by
  printer and waiting fold under a line.
- Cotações: the chips of the mockup (Têxtil, UV, Folha, Avulsa, Com
  ressalva), no field of its own; a customer from the top search shows
  as a tag that takes the filter off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 14:25:53 -03:00
Cauê Faleiros
6f294e168b feat: the Kanban's new screens, from the board to the phone (redesign, steps 2 to 8)
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 4m37s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m10s
- Board: product switch and a filters panel with counts, cards that say
  the next step and the most urgent mark, Imprimindo in one lane per
  machine with its free places, Finalizado as short cards.
- Order panel: the stage and codes on top, "Próximo passo" with its
  button, Pedido / Arquivos / Histórico tabs; going back, contact,
  rework and cancelling in a menu; every form in a dialog.
- Cotações, Pagamentos, Integrações, Números (a calendar for the
  period) and Usuários (who is on the system now, what each profile
  does, the machines) in the design's panels; the sign-in page.
- Phone: sections at the bottom, one stage at a time, the order and
  the dialogs over the whole screen.
- API: each session records when it was last used (at most once a
  minute), for "Ativo agora"; the board says who is on each machine.
- .dockerignore leaves the local test files out of the build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 13:58:05 -03:00
Cauê Faleiros
c76d2fa7f3 feat: the Kanban's frame, a rail of sections and a new top bar (redesign, step 1)
All checks were successful
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 54s
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Integration suite on a real stack (push) Successful in 3m54s
The sections move from tabs in the top bar to a rail on the left, with
an icon each, the counters for Cotações, Pagamentos and Integrações, the
light/dark switch and the account button at the bottom. Its menu holds
"Trocar de máquina", the theme, "Minha senha" and "Sair". The machine of
the session shows in the rail and as a chip in the top bar, both opening
the machine question.

The top bar carries the page's name (Produção also says what is open:
"13 pedidos, 17,40 m em produção"), the search, Tiny only when it needs
attention, and "Atualizado às 09:18": a click there sets how often it
updates by itself, over the same remembered setting, or updates now.
The pages' own headings are gone; on narrow screens the rail lies along
the top until their own layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 09:19:45 -03:00
Cauê Faleiros
05139b71ff feat: the Kanban's new base, dark and light (redesign, step 0)
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 4m29s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m25s
The design canvas's tokens replace the old palette, with a light theme
beside the dark one: the account menu switches them, and each browser
remembers its choice (web/theme.js, loaded in the head so the page never
flashes the other theme). Every hard-coded colour now goes through a
token, so the screens not redesigned yet read in both themes; their old
variable names map onto the tokens until each is rebuilt. Instrument
Sans and IBM Plex Mono replace Manrope, and the "filme descolando" logo
the D. The look before this is kept in git tag ui-v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:59:37 -03:00
Cauê Faleiros
ea3b2b29d1 test: drop the last check of the old operator assignment on machines
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 3m48s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m7s
Who is on a machine now comes from the sessions (item 12); the machine
form no longer carries operators, so "left out, they stay" is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 13:22:39 -03:00
Cauê Faleiros
db877c52e6 feat: the machine is chosen at sign-in, per session (Dropstar's third round, item 12)
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 2m32s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Has been skipped
After signing in, the Kanban asks "Em qual máquina você está?": required
for the operator, optional for Gestão and Administrador ("Não estou em
máquina"), never for the other profiles. The session keeps it until it
ends or is changed from the header, where the machine shows in green;
one person on two computers runs two machines. Someone else already on
the machine is a warning, not a refusal.

Operators see the whole board (no more per-machine filter). From Arte
conferida they pull any card, which becomes their machine's (a machine
that does not print its product refuses it); they move only their
machine's cards, and the others show without drag or buttons. Their
cards and their machine's row in Imprimindo are outlined in green. The
history records the machine with the person: "Imprimindo · Thales ·
máquina2". Usuários shows who is on each machine now, read-only; the old
operator/machine assignment is no longer read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 13:18:24 -03:00
Cauê Faleiros
8c053596b7 feat: the Financeiro profile (Dropstar, 2026-10-30)
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 4m44s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m12s
Financeiro sees the whole board, Pagamentos, Números and Cotações, and
cancels an order with its reason. It moves no card and touches no file;
resolving a payment stays with Gestão and Administração. Two narrower
capabilities carry it: "payments" (the Pagamentos list) and "cancel",
which used to need "manage". The order panel's menu shows each profile
only what it may do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 12:56:53 -03:00
Cauê Faleiros
6a312bec9c fix: the account button sits beside the refresh control, without a gap
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 3m57s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m13s
The panel menu's .morewrap rule (margin-left:auto), later in the file,
won over .account's, so the header's free space was split between the
search box and the account button. The account's rule is now specific
enough to win.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 11:33:54 -03:00
Cauê Faleiros
455c1a1fae feat: the order folders numbered in the flow's order, with Revisão and Imprimindo (Dropstar, 2026-10-30)
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 3m50s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m1s
The automatic folders are now 1. Arte recebida, 2. Arte conferida,
3. Imprimindo, 4. Revisão, 5. Finalizado and Recibos, all created when
the main folder is chosen. The file goes to 4. Revisão with the card
(before, it stayed in Arte conferida) and then to 5. Finalizado; 3.
Imprimindo is for the machines' hot folders. Files in the old
3. Finalizado move to 5. Finalizado keeping their 30 days, and the old
folder goes once it is empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 10:21:02 -03:00
Cauê Faleiros
c08136d87b feat: the Imprimindo column shows each machine's two places, not a row of counters
All checks were successful
Build and deploy / Validate source (push) Successful in 1m28s
Build and deploy / Integration suite on a real stack (push) Successful in 4m20s
Build and deploy / Secret scan and release gate (push) Successful in 15s
Build and deploy / Publish images (push) Successful in 1m38s
Each machine with something printing is one line: its name, the order
printing (green, as the card's Imprimindo label) and the one ripping
(blue, as Ripando), each opening its order, or a dashed "livre" place;
above the limit, the extra order shows in red. The machines with nothing
printing share one line, "Livres: máquina3 · máquina4", so an empty
column takes one line instead of a grid of "0/2" chips. In a narrow
column the places go under the machine's name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 10:08:59 -03:00
Cauê Faleiros
d962865944 feat: the pickup receipt in Recibos/ and "Retirado" on the card (Dropstar's third round, item 14)
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 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 59s
A pickup order reaching Finalizado has its receipt due: a PDF for the
80 mm roll with the order number large at the top, the customer and
CPF/CNPJ, each product and its metres, the amount and how it was paid,
the date issued, and the "Retirado em" and "Assinatura" lines
(app/receipt.py). The Kanban's folder saves it in Recibos/, where the
counter's print queue sends it to the Bematech. One computer claims each
receipt on the server before writing it, so it is never printed twice,
and gives it back if it could not save it. Orders sent by carrier have
none.

"Retirado" on a pickup in Finalizado records when and who handed it
over, with an optional photo of the signed receipt (kept 30 days). Anyone
but the seller may mark it (new "deliver" capability); the order panel
also opens the receipt to print it again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:39:17 -03:00
Cauê Faleiros
a5417d200e feat: a real progress bar per file while it uploads (Dropstar's third round, item 6)
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 3m42s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 56s
A file starts uploading as soon as it is on the product page, not once
the item is in the cart. Under the uploader, each file has its row:
"Enviando NOME · 62% · 1,2 MB de 2,0 MB", then the security check, then
"enviado"; a failure says why, with "Tentar de novo". Each part goes
through XMLHttpRequest, so the bytes move while a part is on its way
instead of once per 8 MB part. A file taken off the page, and in no cart
item, stops uploading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:18:56 -03:00
Cauê Faleiros
95e7c64501 feat: "Tratar a arte" on an order in Arte recebida (Dropstar's third round, item 8)
All checks were successful
Build and deploy / Integration suite on a real stack (push) Successful in 3m36s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 59s
Build and deploy / Validate source (push) Successful in 5s
The order panel shows where each item's file is in the orders folder,
with Copiar: 1. Arte recebida\DTF-N-item-K, named as the automatic
folders save it (GET /api/operator/orders/{id}/folder-files). The browser
knows only the folder's name, so each computer is told once where it is
and the whole path is copied. "Subir arte tratada" sends the file saved
over; it becomes the item's final, "Arte tratada" lights and the order
can move to Arte conferida.

Only the treated item changes: the others keep their approved final,
which the server now accepts beside a new one (still refused when
nothing is new).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 17:24:15 -03:00
Cauê Faleiros
7f2327aea9 feat: the customer may accept printing a ready sheet's residue dots (Dropstar's third round, item 5)
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 3m53s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m8s
A sheet with dots under 2 mm still stops the order, now with a box under
the warning: "Esta arte tem N pontos menores que 2 mm. Estou ciente e
aceito imprimir assim — eles podem se perder no recorte." Ticked, the
sheet goes on, and the item carries how many dots were accepted
(residue_accepted), kept through the review and shown on the Kanban card,
order panel and quote. A solid background still stops it, with no box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 17:10:28 -03:00
Cauê Faleiros
9c44cdf2a1 feat: two cards at most in Imprimindo per machine, one printing and one ripping (Dropstar's third round, item 11)
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 4m14s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m5s
A third pull onto the same machine is refused with "máquina5 já tem 2 em
Imprimindo", and so is changing a printing order to a full machine. On
the board, the first order to enter Imprimindo on its machine is labelled
Imprimindo and the next Ripando; the column shows each machine's count,
as "máquina5 · 2/2".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 16:19:04 -03:00
Cauê Faleiros
757008566c fix: image builds refresh OS packages once a day, so a cached layer cannot hide a new fix
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 4m6s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m3s
Run 219 was blocked by CVE-2026-111497 in brotli-libs 1.2.0: the fix (1.2.1)
was out, but the cached apk upgrade layer was reused. The build day is now
part of that layer in both images.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 14:57:58 -03:00
Cauê Faleiros
35b7701664 feat: the Site's product cards and uploader as Dropstar's third round asks (items 1 to 4)
Some checks failed
Build and deploy / Validate source (push) Successful in 1m27s
Build and deploy / Integration suite on a real stack (push) Successful in 4m14s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Failing after 1m14s
- the "Mais vendido" card has a thick green border
- the four "Enviar..." buttons share that green as the action colour
- the uploader sits on top of the file list, the newest file right under it
- with files in, the uploader stays big and highlighted instead of shrinking
  to a thin dashed line

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 14:46:29 -03:00
Cauê Faleiros
636c27ee88 feat: the customer's proof only on orders above 10 m (Dropstar, 2026-10-28)
All checks were successful
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m13s
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 4m6s
The checkout's "Quero aprovar uma prova" box shows only when the cart is
above 10 m, and the server keeps the request only then. Below 10 m there is
no proof; above it the room's own proof stays automatic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:12:59 -03:00
Cauê Faleiros
8257ac24ab feat: print files over 5,08 m are written at their real size
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 4m36s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m12s
PDF's /UserUnit scale kept long sheets within Acrobat's page limit, but
CorelDRAW, where Dropstar checks the files, ignores it and showed a 12,8 m
sheet at a third of its size. Long sheets now stay one page at real size;
PRINT_PAGE_SCALE=true in the stack goes back to the scale, for a RIP that
refuses pages over the limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:42:27 -03:00
Cauê Faleiros
ac22f9a2f6 feat: the print file's footer line is about 1 cm tall (Dropstar, 2026-10-28)
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 3m34s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m2s
It was 18 pt, about 0,6 cm. Now 31 pt, shrunk only when the line would not
fit the film's width (the 27 cm UV), measured with Helvetica's widths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:13:52 -03:00
Cauê Faleiros
ebe8b29db2 feat: UV is 27 cm wide (Dropstar, 2026-10-28)
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 3m27s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m0s
It was 28,5 cm. The Site's UV products, ready-sheet check, layout and size
shortcuts, the server's film-width check, the print file and the Tiny item
names follow; two pieces of up to 13,2 cm share a UV row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:08:07 -03:00
Cauê Faleiros
b08a258931 feat: the Administrador may release orders to Finalizado too
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 3m34s
Build and deploy / Secret scan and release gate (push) Successful in 4s
Build and deploy / Publish images (push) Successful in 1m1s
D-29 keeps the release with the Revisor, so nobody in the room releases
their own print; the Administrador, Dropstar's own login, may release as
well (the user, 2026-10-28). Gestao, Designer and Operador still cannot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:34:24 -03:00
Cauê Faleiros
ee6344dc74 feat: files up to 4 GB again (Dropstar, 2026-10-28)
All checks were successful
Build and deploy / Validate source (push) Successful in 1m5s
Build and deploy / Integration suite on a real stack (push) Successful in 5m22s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m24s
It was 5 GB, then 1 GB from 2026-10-21. ClamAV keeps scanning up to its own
2000 MiB limit; a larger file passes by the file-format check, as before
the 1 GB limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:58:42 -03:00
Cauê Faleiros
312e1e3aa3 docs: Tiny's e-commerce channel is API do ERP (9594); the store's channel refuses API orders
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 4m28s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m26s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:28:57 -03:00
Cauê Faleiros
874e53ae46 feat: the Tiny probe lists the account's users with their type and marks the integration's
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 3m28s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 58s
Read-only. Tiny's API does what the user who connected the integration may
do, so knowing which user that is, and its type, points at the permission.
The name and e-mail come from the access token's claims; the token is never
printed. It needs the app's Usuarios (Leitura) and a reconnect, and says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:02:55 -03:00
Cauê Faleiros
1ad761ec53 feat: the Tiny probe's diagnostico finds which part of an order Tiny refuses
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 3m46s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m6s
Tiny answered the test order with a bare 403. The command sends the same
test order whole, then without one part at a time (ecommerce, pagamento,
transportador, dataPrevista), then with only the essentials, stops at the
first version Tiny accepts and cancels it at once. It needs a contact that
already exists and never creates one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:56:56 -03:00
Cauê Faleiros
258128de9f feat: Dropflow orders reach Tiny in DTF DROPFLOW, and dinheiro and customer credit name their forma de recebimento
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 4m40s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m27s
Marcus's ids of 2026-10-27: the revenue category DTF DROPFLOW (987032506)
for Dropflow orders, which no longer stay out of Tiny, and the formas de
recebimento Dinheiro (919478944) and CORREÇÃO DTF (977493654) for the
customer's credit, on orders the team registers as paid outside the site.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:38:33 -03:00
Cauê Faleiros
5692804c6f feat: rework register, opened by Gestao with a locked cause and authorized by an Administrador (Dropstar's rules D-02 to D-04)
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 3m27s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m2s
Gestao opens a rework from the order panel with its cause (falha de
impressao, perfil de cor, erro de tratamento, erro de pedido, or arte
aprovada pelo cliente, outside the goal), the metres redone and a note; the
cause never changes. An Administrador authorizes or declines it with a
reason, never one they opened, and only an authorized rework counts. The
order keeps who printed it. Numeros shows the metres redone per cause over
the film printed, against 0,4% per cause and 1,6% for the house, by who
printed, and the reworks waiting for authorization. Vendedor goes back to
viewing only (D-30): registering orders paid outside is Administrador and
Gestao.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:09:56 -03:00
Cauê Faleiros
babd9e327c test: the D-13 check waits for the PDF sheet's ink check before changing product
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 3m31s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m0s
The check still running repainted the list after the switch to loose
artwork, so the next step found no size field (CI run 206).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 12:41:46 -03:00
Cauê Faleiros
c45e5f732b feat: the team registers an order paid outside the site, choosing its origin and payment (Dropstar's rule D-35)
Some checks failed
Build and deploy / Integration suite on a real stack (push) Failing after 3m26s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Has been skipped
Build and deploy / Validate source (push) Successful in 6s
On an approved quote in Cotacoes, Administrador, Gestao and Vendedor pick
the origin (Site, Dropflow, Atendimento) and how it was paid (Pix, cartao,
dinheiro, credito do cliente), neither preselected, with an optional note.
The price is the quote's, the Site's table price. The order is marked paid
outside, counts in Numeros, and goes to Tiny like a Site order with the
payment named in its internal note; a Dropflow order stays out of Tiny,
status updates and cancelling included, until its revenue category exists.
Auto-refresh waits while a register form on screen is half filled in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 12:36:40 -03:00
Cauê Faleiros
0319039328 feat: every order is born with its origin, shown, filtered and counted (Dropstar's rules D-21 and D-35)
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 3m21s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m1s
Orders carry site, dropflow or atendimento, required and with no default,
limited to the three. The Site's orders are marked site where they are
created; older orders became site. The Kanban shows the origin on each card
and in the order panel, filters by it, and Numeros has a Por origem table:
orders, metres, money and time from payment to Finalizado per way in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:39:08 -03:00
Cauê Faleiros
bba55a83f3 feat: a file's type comes from its first bytes, not its name (Dropstar's rule D-13)
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 3m37s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m11s
The Site reads the first bytes when a file is chosen and renames it to its
real extension: a .cdr that is a PDF is measured and priced as a PDF,
without the manual charge; a JPG called .png is refused, naming the file.
The scan does the same on the server and stores the real name, so every
decision that reads the name follows the content. A name its content agrees
with stays (an .ai is a PDF inside but is still handled by hand).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:17:20 -03:00
Cauê Faleiros
494925dff4 feat: time in "Aguardando contato" no longer counts in Números (Dropstar's rule D-38)
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 3m20s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m0s
Dropstar's internal rules (2026-10-26): waiting for a word with the customer
has no deadline and does not enter the time figures.

- each wait is kept, from the mark to "Contato feito" (and from checkout when
  the customer asks for a proof), in a new table; waits open today are
  recorded from their start
- the time in each stage and "Do pagamento ao Finalizado" leave those waits
  out, and the Números page says so

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:45:14 -03:00
Cauê Faleiros
6a921415ea feat: the folders catch up on what passed while the Kanban computer was off
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 3m27s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 56s
Dropstar's internal rules (2026-10-26): the folder must reproduce what passed,
not only what sits in the columns when the computer comes back, or a room
running 24 hours leaves a gap a week in the Finalizado archive.

- the Kanban remembers when the folders were chosen and asks for every order
  paid since then, whatever its stage; each file goes to its stage's folder,
  so an order finished while the computer was off lands in 3. Finalizado
- orders paid before the folders were chosen still stay out, so setting them
  up never pulls old orders back into the queue
- the server's file list for the folders and Baixar now loads only the orders
  that have a file, not every order in the stages

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:15:16 -03:00
Cauê Faleiros
35e64d77d7 feat: "Arte tratada" flags the orders whose final the team prepared, counted in Números
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 3m20s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 58s
Dropstar's internal rules (2026-10-26) asked how to tell art that arrived
ready from art the designer had to fix, and Marcus agreed on 2026-10-27 to
mark it automatically, for the designer's productivity.

- an order whose approved final is not the customer's art (not the file the
  system generated from it, not one of their originals, not a correction
  they sent) shows "Arte tratada" on its card and in the order, with who
  approved it
- Números counts the period's treated orders, the share of all orders, and
  how many each person approved
- the Kanban's cancel text: the money stays as the customer's credit, in
  Dropstar's financial control (rule D-15), no longer a refund
- Números' machine table shows the orders waiting in Arte conferida again;
  it still looked for the old print queue

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:01:35 -03:00
Cauê Faleiros
f77de40b7f feat: Gestão only pulls cards back, with a reason (Dropstar's rule D-20)
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 4m5s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m33s
Dropstar's internal rules of 2026-10-26: the coordination pulls back, never
forward, always with a reason. The Gestão profile now sends orders to
Correção from any stage and steps them back, and no longer moves them
forward. Admin, Dropstar's own login, keeps every move but Finalizado, which
stays the Revisor's (D-29).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 09:16:00 -03:00
Cauê Faleiros
19b8b8c509 feat: Site orders reach Tiny in the DTF SITE category
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 3m22s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m1s
Dropstar sent the category's id on 2026-10-26: 986932924, under RECEITAS,
in place of the store's DUPLICADO DROP. The same day they settled that the
print PDF's footer also gets the white spot, which needs nothing here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:38:20 -03:00
Cauê Faleiros
0088158dc0 feat: the three folders are created when the main one is chosen, numbered in the flow's order
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 3m31s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m4s
Tried on a local Kanban with Dropstar's flow: the folders appeared only with
the first file, and a listing showed Arte conferida before Arte recebida.

- "1. Arte recebida", "2. Arte conferida" and "3. Finalizado" are created
  as soon as the main folder is chosen or released, and again on every
  round if someone deletes one
- numbered, a folder listing shows them in the order the file moves

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:25:01 -03:00
Cauê Faleiros
ee1159065a feat: the orders' files in Dropstar's three folders: Arte recebida, Arte conferida, Finalizado
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 4m27s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m19s
Asked by Dropstar on 2026-10-23 and agreed on 2026-10-26. The automatic
folder becomes "Pastas dos pedidos": one main folder is chosen once, in
Chrome or Edge on a factory computer that reaches the server, and the
Kanban keeps three folders inside it, moved with the card.

- Arte recebida: the order's file as soon as the order arrives
- Arte conferida: the queue; the file moves there with the card and stays
  while it prints and is checked in Revisão
- Finalizado: when the order is released, kept 30 days
- Correção, a cancellation or a deletion takes the file out; a replaced
  final is swapped
- orders already printing when the folder is chosen are not downloaded; a
  file someone took out comes back only when its order moves on, so the
  server now returns the files of orders the folders hold while they print,
  are checked and finish
- Firefox, which cannot write into folders, still only downloads the files
  entering Arte conferida

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 16:31:20 -03:00
Cauê Faleiros
b6f20733fa feat: Dropstar's new flow: Arte conferida is the queue, Revisão and the Revisor
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 3m36s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m24s
The board Dropstar drew on 2026-10-23: Arte recebida, Arte conferida,
Imprimindo, Correção, Revisão, Finalizado.

- Fila de impressão leaves the board: Arte conferida is the queue. It takes
  an order only with every item's final approved, keeps the finals as
  approved, orders its cards for printing and has the room's "Baixar" and
  the automatic folder. Orders that were in the queue move there once, with
  a line in their history
- Revisão checks the printed sheet, and the new Revisor profile is the only
  one that sends an order to Finalizado (the superadmin too, for support)
- who moves what, from the server (MOVES): the designer the artwork, asking
  for corrections and bringing the new art back; the operator Arte conferida
  to Imprimindo to Revisão; admin and gestão everything else, Correção
  included; a step back belongs to whoever makes the move it undoes
- Tiny: Arte conferida is "Preparando envio" and Finalizado "Pronto para
  envio", for delivery orders too
- Prova OK still comes before Finalizado; the customer's portal shows the
  new steps

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 12:45:57 -03:00
Cauê Faleiros
93cb289940 feat: Site orders carry DTF-<n> as Tiny's numeroPedidoEcommerce
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 3m47s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m14s
Dropstar asked on 2026-10-23 for the Kanban number in numeroPedidoEcommerce.
It goes there on every order now, next to numeroOrdemCompra, which the
resend check still searches. Tiny's v3 model takes the e-commerce block
without a channel id; TINY_ECOMMERCE_ID adds one and can now be set in the
stack. The supervised test order reads the number back from Tiny and fails
if Tiny did not keep it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 11:47:21 -03:00
Cauê Faleiros
88819c3a5f feat: one price per product; the grade is shown but no longer prices
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 3m58s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m11s
Dropstar asked on 2026-10-23 to drop the five-band ladder by grade:
textile R$ 19,90 a ready sheet and R$ 21,90 loose art, UV R$ 79,90 and
R$ 89,90.

- the server charges PRICES (app/core/pricing.py) whatever the grade; the
  grade is still validated and kept with the item, and discount_cents is gone
- a file opened by hand pays the product's price plus MANUAL_FILE_EXTRA_CENTS
- the Site's PRECO replaces FAIXAS, TABELA and MONTAGEM; the top chip, the
  home example, the product cards, the selector and the price table read it
  (data-preco), so no page still says "a partir de R$ 14,90"
- no "Desconto pela nota", ladder, "cai até" or "sai mais barato" anywhere;
  the buy box shows "Nota da arte" on its own line, the 96 DPI refusal and the
  resolution warning stay
- the review reason "Nota informada sem análise da arte" is removed: it only
  stopped a discount. The server still checks the grade against the files,
  so the grade shown on the Kanban and in Tiny stays honest
- the Tiny probe's test order uses the single price
- docs/CONTEXT.md: Commercial rules and Still to do

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 11:07:00 -03:00
Cauê Faleiros
629628a522 docs: the project's state on 2026-10-26: what Dropstar settled and what is left
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 3m26s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 59s
The "waiting on Dropstar" list still named work that is done. It now says
what Dropstar settled on 23/10, and what is left: the single price per
product, the DTF number in Tiny's numeroPedidoEcommerce, and what waits on
them (the category id, the flow image, the rules document, the montador spec,
a written decision on the three server folders).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 10:03:47 -03:00
Cauê Faleiros
a9253d830a feat: Dropstar's answers of 23/10 that need nothing more from them
All checks were successful
Build and deploy / Validate source (push) Successful in 1m6s
Build and deploy / Integration suite on a real stack (push) Successful in 4m5s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 2m6s
- JPG is refused in every product, at upload and by the server: it has no
  transparency, so the background prints and loose art packs as a box
- a PDF over 150 MB says before payment that the Site cannot check it, as a
  file opened by hand does
- every piece that is not square is tried both ways; the 1 cm rule left
  19,5 x 18,5 cm standing, 2 to a row instead of 3
- a mirrored order (UV only) is flagged on its card and panel, and its print
  file's footer ends in ESPELHADO, in bold
- print files are named DTF-23-item-1, and the order panel copies DTF-23-,
  so the code pasted into the folder's search finds them
- the proof: up to 30 cm, from the thinnest lines, a piece of each different
  artwork, at most three per order, free
- a file opened by hand costs R$ 2,00 more a metre by default, and the Site
  says so

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:33:22 -03:00
Cauê Faleiros
c21497d71b feat: the print PDF footer starts with Dropstar's logo
All checks were successful
Build and deploy / Validate source (push) Successful in 15s
Build and deploy / Integration suite on a real stack (push) Successful in 4m25s
Build and deploy / Secret scan and release gate (push) Successful in 13s
Build and deploy / Publish images (push) Successful in 1m49s
Dropstar sent the logo on 2026-10-23: black on transparent, so the room's
white-base profile prints nothing around it. It is drawn 1,3 cm high at
the start of the footer band, in place of the brand's name, followed by
"Pedido DTF-123 · Item 1/2 · date · metres". Without the file, the footer
falls back to the name in bold.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:15:23 -03:00
Cauê Faleiros
56e5462647 perf: a ready sheet is decoded once for its check, with the progress shown
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 3m23s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m8s
Drawn from the <img>, a large sheet was decoded again for each strip the
residue check reads. Decoded once into an ImageBitmap and reused for the
thumbnails, the check of a 57 x 50 cm sheet at 300 DPI drops from 4,7 s to
1,4 s, and the bar moves while it runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:06:03 -03:00
Cauê Faleiros
88181b755d test: the smoke order, above 10 m, marks Prova OK before 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 3m27s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m20s
The print proof rule stops an order above 10 m at Finalizado until the
print room marks Prova OK; the smoke test's 40 m order now does that, and
checks the refusal first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:41:07 -03:00
Cauê Faleiros
1dc8cf1efb feat: the print proof: Prova OK before Finalizado, and a proof the customer can ask for
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Failing after 56s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Has been skipped
Dropstar's items 15 and 16 (2026-10-21).

- an order above 10 m prints 20 cm of proof first; the room checks it and
  marks "Prova OK", without stopping the order, and without that mark the
  order cannot reach Finalizado
- at checkout, "Quero aprovar uma prova antes de imprimir", for any length:
  the paid order arrives marked "Aguardando contato" with what to do, and
  waits for the customer's word on the photo sent by WhatsApp
- the card shows Prova / Prova OK, the panel gives the next step, and
  "Prova a conferir" is a board filter; the designer cannot mark it
- the proof is not billed, as Dropstar leans; rounds and which part of the
  sheet wait for their answer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:21:26 -03:00
Cauê Faleiros
f6bdbe006e fix: checkout and the Kanban take layout version 3
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 3m9s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m20s
The layout rule of 2026-10-21 records version 3, but checkout still
refused any item not on version 2, so no order could be quoted (CI's
browser test timed out at the upload), and the Kanban marked new quotes
"Montagem antiga". Both now take versions 2 and 3, as the server does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:05:35 -03:00
Cauê Faleiros
c8c49ed57e feat: the DTF's own terms at /termos, linked as "Trocas e privacidade"
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 4m3s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Has been skipped
Dropstar's item 12 (2026-10-21): the footer link opened the clothing
store's terms. The DTF's page says what Dropstar listed: the art is
printed as sent and is the customer's responsibility, files are kept for
30 days, and a personalised product has no exchange for regret; and what
the customer's data is used for and where it goes. Waiting for Dropstar's
approval of the text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:56:53 -03:00
Cauê Faleiros
18120e686f feat: the print PDF ends in a footer naming the order, item, date and length
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 3m55s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Has been skipped
Dropstar's item 4 (2026-10-21): the PDF had no text at all, so a sheet cut
off or dropped in the room was guesswork. A 1,5 cm band after the last
piece, outside the billed length and never over artwork, carries one line
in black with no background:

  DROPSTAR · Pedido DTF-123 · Item 1/2 · 21/10/2026 · 0,90 m

The order is named by its Kanban number, the purchase order Tiny keeps,
since Tiny's own number may not exist yet when the PDF is made. The brand
is text until Dropstar sends the logo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:50:31 -03:00
Cauê Faleiros
e3c31e43e5 feat: residue and a solid background stop a ready sheet before payment
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Failing after 4m10s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Has been skipped
Dropstar's items 2 and 3 (2026-10-21): both were warnings the customer
could pay past; now one dot is enough to stop the order.

- every pixel is read (images in strips at 1:1, large PNGs while they
  stream, PDFs rendered in strips at about 0,2 mm): the old check shrank
  the image first and could miss a small dot, or sampled every n-th pixel
- a residue is ink under 2 mm on both sides, measured from where the ink
  starts and ends in each cell: the same dot gets the same verdict wherever
  it falls on the grid, from 0,5 to 4 mm (his acceptance test)
- a solid background is under 1,5 % of transparent pixels; a JPG sheet
  always has one
- the sheet says how many dots there are, circles them on the preview, and
  asks to erase them and send again; the order waits for the check to end
- the page no longer offers JPG for a ready sheet

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:37:46 -03:00
Cauê Faleiros
fe7bf4ef07 fix: textile artwork can no longer be mirrored
Some checks failed
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 4m26s
Build and deploy / Publish images (push) Has been skipped
A textile transfer is pressed face down, so a mirrored one prints
backwards on the garment (Dropstar, 2026-10-21). The Site no longer offers
"Espelhar" on textile artwork and the server refuses a mirrored textile
layout. UV keeps the button until Dropstar decides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:23:41 -03:00
Cauê Faleiros
289151214b fix: Site orders reach Tiny tagged SITE DTF
Dropstar's corrections of 2026-10-21 replace the KANBANDTF marcador with
SITE DTF, the string Kondado reads for Power BI. The new category and
seller still wait for their ids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:23:41 -03:00
Cauê Faleiros
9849ae5c14 fix: the layout lines up its columns and keeps 5 mm margins (layout version 3)
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 3m59s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Has been skipped
Dropstar's item 5 (2026-10-21). The engine placed pieces on a 5 mm grid,
rounding each up: two 28,2 cm pieces needed 57,5 cm on a 57 cm film, so the
second column slid 8 cm down, rows ended 8,6 mm apart and nothing was left
at the edges. Order 1 came out 97,14 cm long.

- pieces are laid out in rows with their exact sizes: 5 mm at the top, the
  bottom and between rows; across the width 5 mm at the edges and between
  pieces, or, when that does not fit, the space left shared out equally,
  never under 1,5 mm (order 1: 2 mm each, 89,42 cm long)
- each artwork stands or lies down, whichever gives the shorter sheet
- the shape packing (pieces fitting into each other) is kept only when it
  saves at least 1 cm; otherwise the columns stay aligned
- the order records layout version 3; quotes made with version 2 still pass
- the preview says the spacing really used

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:17:21 -03:00
Cauê Faleiros
fc3c08aced feat: the board's filters in one panel: product, machine, delivery and situation, combined
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 3m20s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m8s
The row of fifteen chips, one filter at a time, becomes a Filtros button
with four lists. The choices combine (Têxtil on máquina2, waiting for
contact), each option says how many orders it would show, and the
filters in use stay beside the button as tags taken off with a click.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:39:59 -03:00
Cauê Faleiros
3ae453f47a fix: Números measures what Dropstar asked: machines by film printed, stages by order
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 3m23s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m7s
- a machine's metres are the film printed, not the metres billed, which round
  up to one metre and made small orders look like fast printing
- orders in Imprimindo together on one machine count that time once
- a stage's median time is per order, the sum of its passages, so rework
  reads as one slow order instead of quick passages

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:25:08 -03:00
Cauê Faleiros
80975b9424 fix: the home example keeps its 0,60 m; only the price was asked to change
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 4m8s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m9s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 14:41:37 -03:00
Cauê Faleiros
d4494a0654 feat: Dropstar's corrections of 21/10 that need no answer from them
All checks were successful
Build and deploy / Validate source (push) Successful in 1m30s
Build and deploy / Integration suite on a real stack (push) Successful in 4m2s
Build and deploy / Secret scan and release gate (push) Successful in 14s
Build and deploy / Publish images (push) Successful in 1m48s
- the home example priced as the ready sheet it shows (nota 92, R$ 14,90)
- opening hours 7h to 18h, and art sent at any time
- uploads up to 1 GB, every file scanned
- a Designer profile: artwork and corrections on every order, moving only
  among Arte recebida, Arte conferida and Correção
- Números by date range, per machine, and orders apart from passages

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 10:09:15 -03:00
Cauê Faleiros
a2382f4834 feat: the Tiny test order cancels itself, and a guarded cancel for test orders left open
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 3m19s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m7s
Tiny has no delete, and the team's users cannot cancel by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:42:18 -03:00
Cauê Faleiros
c266bea684 fix: Tiny contacts and orders are searched by the punctuated CPF/CNPJ, as Tiny keeps them
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 3m17s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m2s
An existing customer was not found by the bare digits, so each Site order
would have created a duplicate contact, and a resent order a duplicate order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:08:31 -03:00
Cauê Faleiros
a093b7d82a fix: Pillow 13 and certifi 2026.10.19, for the critical advisories that blocked publishing
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 3m41s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m1s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 14:29:50 -03:00
Cauê Faleiros
578a90bcc9 fix: e-mails carry a Date header, which spam filters expect
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 3m21s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Failing after 54s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 14:08:34 -03:00
Cauê Faleiros
abae1c29a1 feat: Site orders reach Tiny in the DUPLICADO DROP category, tagged KANBANDTF
Some checks failed
Build and deploy / Validate source (push) Successful in 1m29s
Build and deploy / Integration suite on a real stack (push) Successful in 5m8s
Build and deploy / Secret scan and release gate (push) Successful in 13s
Build and deploy / Publish images (push) Failing after 1m34s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:15:12 -03:00
Cauê Faleiros
53c6234feb feat: machines share the work by metres open, with an optional limit, their load on show and operators set from the machine
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 3m31s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 59s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:28:13 -03:00
Cauê Faleiros
df30046027 feat: Integrações buttons only for the superadmin; the folder downloads in Arte recebida by default
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 3m7s
Build and deploy / Secret scan and release gate (push) Successful in 4s
Build and deploy / Publish images (push) Successful in 47s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 09:55:31 -03:00
Cauê Faleiros
c8857a5bf5 feat: the team no longer gets alert e-mails; the Kanban user form drops the option
All checks were successful
Build and deploy / Validate source (push) Successful in 47s
Build and deploy / Integration suite on a real stack (push) Successful in 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m20s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 09:37:41 -03:00
Cauê Faleiros
14a43f2ada docs: the operator guide asks for 8 characters in a new user's password
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 3m8s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 58s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 16:16:04 -03:00
Cauê Faleiros
12d5ba8d15 feat: passwords need 8 characters or more, on the Site and in the Kanban
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 3m28s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m2s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:31:59 -03:00
Cauê Faleiros
ea3c20ba1e docs: the launch status, and the guides' screenshots made reproducible
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 3m18s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m0s
CONTEXT.md records what is live and what is left before go-live.
docs/guias/telas holds the seed of fictional orders and the screenshot script
the guides' images came from, with the steps to take them again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:54:13 -03:00
Cauê Faleiros
b2e718449b feat: Site orders reach Tiny filled in as the store's own
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 3m6s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 58s
Read from two of Dropstar's store orders: a paid order now carries its
forma de recebimento (Pix or credit card) with one parcel on the day, the
carrier with freight paid by the sender (Correios with the contract's PAC or
SEDEX, Jadlog's .PACKAGE, or the DropStar carrier with "Retirar
pessoalmente" and "Retirar em loja" for pickup), and the expected date in
working days. Formas de envio and de frete are looked up by name and code;
the two formas de recebimento and the carrier, which the app may not list,
are Dropstar's ids. Category, seller and tag wait for Dropstar's answer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:34:41 -03:00
Cauê Faleiros
7f7b684dbd fix: the Tiny probe shows Tiny's own answer when a lookup is refused
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 3m46s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:14:22 -03:00
Cauê Faleiros
f8cd6c148f docs: both guides for today's system, with new screenshots
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 3m14s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 48s
The operator guide and the Site guide move to dropstardtf.com.br and cover
what changed since they were written: CPF or CNPJ and the customer's name,
Jadlog with Correios PAC and SEDEX, up to 3 card instalments, the account's
e-mailed codes and password recovery, orders found by CPF/CNPJ and e-mail,
the customer e-mails, "Arte conferida" and "Aguardando contato", the
folder's "Baixar ao chegar", Tiny following the board, and the backup. The
screenshots come from a local stack seeded with fictional customers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:14:42 -03:00
Cauê Faleiros
3879754397 feat: customer e-mails in the Site's look, and an order confirmation
All checks were successful
Build and deploy / Validate source (push) Successful in 49s
Build and deploy / Integration suite on a real stack (push) Successful in 3m23s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m17s
The account e-mails (signup and e-mail change codes, new password, an
address that already has an account, the changed-e-mail notice) gain an
HTML version beside their plain text: the DROPSTAR header, a white card,
orange buttons, the customer greeted by first name. Built with tables and
inline styles only, so Gmail, Outlook and phone apps show it the same.

A paid order now also e-mails the customer "Recebemos seu pedido #N": the
items, delivery and total, the stages to come, and a link to the order in
the account. Not for an operator's test order. A code's or a recovery
link's HTML is erased with its text once sent. The team's alerts stay plain
text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 09:18:20 -03:00
Cauê Faleiros
5910d3161f feat: the Tiny probe reads what a complete order needs
Some checks failed
Build and deploy / Validate source (push) Successful in 7s
Build and deploy / Integration suite on a real stack (push) Failing after 50s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Has been skipped
"campos" tries each lookup a complete order needs (formas de recebimento,
financial categories, sellers, intermediaries) and names the app permission
to release when Tiny refuses one; it also shows Correios and Jadlog as Tiny
keeps them, with their freight options. "exemplo NUMERO" prints an existing
order's payment, carrier, seller, category and tags, without the customer or
the address, so Site orders can copy the store's. Both only read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:46:49 -03:00
Cauê Faleiros
dbf1efc112 feat: Tiny follows printing and cancellation
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
With TINY_STATUS_UPDATES on, an order entering Imprimindo becomes
"Preparando envio" in Tiny, and a cancelled order "Cancelada", next to the
"Aprovada" on payment and the pickup "Pronto para envio" there already.
Neither sends a WhatsApp in the client's n8n. An order the team already
moved further in Tiny is never moved back, and an invoiced one is not
cancelled here: its nota fiscal is cancelled in Tiny. Cancelling a paid
order now tells Tiny, which it did not before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:45:23 -03:00
Cauê Faleiros
1f2358c8b5 feat: the cart and the account ask for the customer's name
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 4m49s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m15s
The Site asked only for CPF/CNPJ, WhatsApp and e-mail, so a person's Tiny
contact was named after the recipient or the e-mail, and the WhatsApp notices
the client's n8n sends from Tiny greeted "Olá, fulano@gmail.com". The cart's
"Seus dados" and the signup now ask for a name, the account page can change
it, and it names a CPF customer's Tiny contact (a CNPJ keeps the registry's
razão social), the Kanban card and the team's alerts. Orders placed before
have none, as the server still accepts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:38:09 -03:00
Cauê Faleiros
7eb7d90f8b refactor: remove the WhatsApp integration
All checks were successful
Build and deploy / Validate source (push) Successful in 15s
Build and deploy / Integration suite on a real stack (push) Successful in 4m24s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m11s
The system will not send WhatsApp messages: the client's n8n already does,
from Tiny's status changes. Paid orders and stage changes now queue only
the Tiny delivery; the fake WhatsApp adapter, its setting and secret, the
Integrações row and the send log's Destino column are gone, and the old
WhatsApp log rows are removed. The customer's WhatsApp number, the
"Avisar no WhatsApp" link for corrections and the contact links stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 17:49:50 -03:00
Cauê Faleiros
fb576e52d7 fix: the logo goes to the DTF Site's home page
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 4m37s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m33s
On the Site and the account page the logo led to the wholesale store; it
now opens the DTF home page (inside the Site, without reloading). The store
stays a click away in the header menu and the footer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 17:16:55 -03:00
Cauê Faleiros
6919383d37 feat: "Fazer backup agora" in Integrações
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 4m40s
Build and deploy / Secret scan and release gate (push) Successful in 13s
Build and deploy / Publish images (push) Successful in 1m29s
The backup row gets a button that asks for a backup outside the daily hour,
for after a failure or before a risky change. The Kanban records the
request; the backup service, which alone may read the whole database, looks
every minute and runs it. The row says it was asked for until it runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 17:09:00 -03:00
Cauê Faleiros
bd718796c5 fix: an image still being read after leaving the product page no longer throws
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 4m19s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m19s
"Voltar" closes the product page but leaves the artwork list; an image
whose reading finished afterwards repainted it with no product chosen and
threw (MODOS[null].larg). It now paints nothing. The artwork browser test
caught it now and then, failing CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 16:42:03 -03:00
Cauê Faleiros
8df35049f7 fix: production containers get a writable /tmp again
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 4m27s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m27s
The stack runs on Swarm, which ignores the short `tmpfs:` key, so the
read-only api, worker and backup containers had no writable /tmp: the
backup failed with "No usable temporary directory", and the worker could
not render print files. The api and backup get a tmpfs in the long volume
syntax a stack honours (the backup's in memory, since a restore writes the
private key there), and the worker a disk volume, as print files can be
hundreds of MB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 16:30:21 -03:00
Cauê Faleiros
4f49ace867 fix: accounts confirmed more than a day ago also bring their orders
Some checks failed
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Failing after 4m2s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Has been skipped
The signups that marked an account as confirmed are deleted after a day, so
an older account was left unconfirmed and brought nothing. The code e-mail
sent before the account existed stays in the queue and now counts too. A
password reset, whose link came by e-mail, also confirms the address and
brings the orders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:51:25 -03:00
Cauê Faleiros
1a7736dc8b feat: an account brings the orders bought without it with its CPF/CNPJ and e-mail
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 4m44s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m22s
At signup (once the e-mailed code confirms the address), on an e-mail
change and at every sign-in, a confirmed account takes over the guest
orders placed with the same CPF/CNPJ and the same e-mail, from any browser,
with their carts and files. A CPF or CNPJ alone, which others may know,
brings nothing; neither does an account whose e-mail was never confirmed.
Accounts already confirmed by a code are marked as such.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:35:07 -03:00
Cauê Faleiros
4a2ce72764 feat: the folder can download as the order arrives, and removes cancelled orders' files
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 5m5s
Build and deploy / Secret scan and release gate (push) Successful in 11s
Build and deploy / Publish images (push) Successful in 1m23s
Integrações gets "Baixar ao chegar" next to "Baixar na Fila". On arrival the
file (the generated print file, or the final once approved) goes into a
Recebidos folder inside the chosen one and moves up when the order enters
the queue. Files of orders cancelled, deleted or sent back for correction,
and files replaced by another final, leave the folder.

The launch reset now restarts order numbers at #1 by itself: the worker's
role may set the orders' number sequence, and nothing else.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:07:29 -03:00
Cauê Faleiros
b83e60ef0c feat: customers buy with a CPF or a CNPJ
All checks were successful
Build and deploy / Validate source (push) Successful in 1m38s
Build and deploy / Integration suite on a real stack (push) Successful in 4m57s
Build and deploy / Secret scan and release gate (push) Successful in 13s
Build and deploy / Publish images (push) Successful in 2m1s
The cart and the account signup take either document, each with its own
mask and check digits. Tiny gets a person (F) for a CPF, Mercado Pago the
matching identification type, and only CNPJs go to the company registry.
The Kanban, the account page and the alerts show which one it is.

Also pins the Correios test's clock: its fake token expired today, so the
suite failed from Oct 16 on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:33:50 -03:00
Cauê Faleiros
37246917b9 test: the folder check waits for the round to end before looking for half files
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 4m22s
Build and deploy / Secret scan and release gate (push) Successful in 12s
Build and deploy / Publish images (push) Successful in 1m23s
In CI the browser test failed on "no .baixando file left": the earlier
suites leave other orders in the print queue, and the folder was still
downloading one of them when the test's own file had arrived. The check now
waits until the folder's round is over, which is what it means to assert.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:25:29 -03:00
Cauê Faleiros
a747d9a968 fix: shorter delivery texts: "Jadlog", and the time only in its option
Some checks failed
Build and deploy / Validate source (push) Successful in 8s
Build and deploy / Integration suite on a real stack (push) Failing after 3m52s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Has been skipped
The cart showed Jadlog's internal service name ("Jadlog .PACKAGE"), a
"Receber em casa" line naming every carrier, and the delivery time again in
the order summary, where it wrapped. Now the option is "Jadlog", the line
says only to type the CEP, and the summary reads "Frete · Correios SEDEX".
The Kanban's Frete row lists the options and pickup in one sentence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 14:41:23 -03:00
Cauê Faleiros
90e3126075 feat: the cart offers Correios PAC and SEDEX next to Jadlog
All checks were successful
Build and deploy / Validate source (push) Successful in 1m48s
Build and deploy / Integration suite on a real stack (push) Successful in 4m25s
Build and deploy / Secret scan and release gate (push) Successful in 15s
Build and deploy / Publish images (push) Successful in 1m54s
Dropstar sent its Correios contract. The cart now asks every carrier at once
for the CEP and lists each option with its delivery time, cheapest first and
chosen by default: Jadlog .PACKAGE, Correios PAC and Correios SEDEX, plus
pickup. A carrier that does not answer is left out instead of blocking the
others, and the server quotes the customer's choice again at approval. The
order summary, the Kanban and Minha conta name the carrier chosen.

app/correios.py follows the CWS manuals: a token from the posting card (kept
until shortly before it expires, renewed once if refused), the contract's own
prices by its DR, and the delivery time. Each box is one object priced by its
sides; Correios work out the cubic weight. All carriers price the same
package, now in app/package.py. Only CORREIOS_CODIGO_ACESSO goes in the
stack; the user, card and contract are its defaults. python -m
app.correios_probe checks the contract and its service codes on the account.

Tested: tests/test_correios (token, contract parameters, prices in Brazilian
format, boxes, a code override, a failing carrier), the full suite in a
CI-style stack, and the cart in Brave on desktop and phone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 13:47:53 -03:00
Cauê Faleiros
69997f4598 fix: the database starts again after an e-mail change notice exists
schema.sql defined the e-mail kinds constraint twice: the signup commit's
copy without "notice", and the e-mail change commit's with it. The schema
runs on every start, so once a "notice" e-mail existed the first copy was
refused and db-init restarted for ever. It is defined once now, and
tests/test_schema fails on any constraint added twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 13:18:21 -03:00
Cauê Faleiros
7383e44ff4 feat: a new account e-mail is confirmed with a code, and the old one is told
Changing the e-mail in Dados da conta took effect at once, with nothing
checking the new address: a typo locked the customer out, and anyone at a
signed-in computer who knew the password could move the account to their own
e-mail and then reset its password. Now the code goes to the new address, the
account changes only once it is entered (same screen and limits as signup,
and only the account that asked can complete it), and the old address gets
"O e-mail da sua conta foi trocado", with the WhatsApp to call if it was not
them. Without e-mail on, it changes at once as before.

Signup and e-mail change share one code check (expiry, five attempts, the
60 s resend wait). Tested: mail_test (wrong password, same and taken e-mail,
wrong code, another account's attempt, resend wait, the notice), the full
suite in a CI-style stack, and the screen in Brave.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:32:46 -03:00
Cauê Faleiros
95be624cca feat: a new account is confirmed with a code sent to its e-mail
All checks were successful
Build and deploy / Validate source (push) Successful in 17s
Build and deploy / Integration suite on a real stack (push) Successful in 4m25s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m22s
Anyone could open an account on someone else's e-mail. Now "Criar conta"
e-mails a 6-digit code, and the account exists only once it is entered: one
big field that takes a paste or the phone's autofill and confirms by itself,
"Reenviar código" after 60 s, "Trocar e-mail", and the sign-in box hidden
meanwhile.

Security: 15 minutes per code, 5 wrong attempts, at most 5 codes, limits per
address and per source; the password is hashed at the first step and the code
stored only as a hash, its e-mail erased once sent. An address that already
has an account gets the same answer on screen and a "você já tem conta"
e-mail instead of a code, so the form does not reveal who is registered.
Without e-mail (MAIL_ADAPTER=off) the account is created at once, as before.

The browser test reads the code from a local-only endpoint that exists only
where e-mail stays in the log. Tested: mail_test (wrong, locked, resent,
expired codes, existing address, erasure after SMTP), the full suite and the
browser test in a CI-style stack, and the screens in Brave on desktop and phone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:18:37 -03:00
Cauê Faleiros
5a431f8422 fix: Tiny's test order names a new customer as the real orders do
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 3m30s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m7s
The supervised test order would have created Dropstar as a Tiny contact named
after its e-mail: the console tool did not look the CNPJ up in the company
registry as the worker does. It now uses the same lookup, and the preview says
which name the new contact will get.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 13:38:46 -03:00
Cauê Faleiros
5a2e2db49a feat: Tiny order sending is switched on from the stack, after the test order
Some checks failed
Build and deploy / Validate source (push) Successful in 7s
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
TINY_ADAPTER was written as fake in docker-compose.yml, so sending paid
orders to Tiny needed a code change. It is now a stack setting, still fake by
default, to set to tiny once the supervised test order has passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 13:36:14 -03:00
Cauê Faleiros
f8d76ed27d fix: Tiny's pickup is "Retirar pessoalmente", even with "Retirar na loja" there
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 4m9s
Build and deploy / Secret scan and release gate (push) Successful in 12s
Build and deploy / Publish images (push) Successful in 1m42s
Dropstar's Tiny has two formas de envio named like "retirar": "Retirar
pessoalmente", the one its team uses, and an unused "Retirar na loja", so
the lookup by name asked for a setting. The exact name now decides; two
other "retirar" methods still ask.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 13:25:21 -03:00
Cauê Faleiros
44458aea3e fix: Tiny uses Dropstar's SKUs and finds the pickup method without settings
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 3m40s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m4s
"Testar conexão" in production said every product and the pickup forma de
envio were "sem id": the SKUs and the pickup id only existed as stack
settings nobody had set. They are Dropstar's fixed catalogue, checked against
its Tiny export: Têxtil as DTFIMP.TX.100CM plus DTFIMP.TX.0010CM to 0090CM,
UV as DTFIMP.UV.1MT plus DTFIMP.UV.010CM, for the ready sheet and loose
artwork alike. These are now the defaults, and the pickup forma de envio is
the one named like "retirar" in Tiny; the test says so when there is none,
or more than one. The settings still override both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 11:17:24 -03:00
Cauê Faleiros
3c9f05041e fix: Tiny's connection test no longer times out listing orders
All checks were successful
Build and deploy / Validate source (push) Successful in 1m38s
Build and deploy / Integration suite on a real stack (push) Successful in 4m33s
Build and deploy / Secret scan and release gate (push) Successful in 11s
Build and deploy / Publish images (push) Successful in 1m51s
"Testar conexão" asked Tiny for one order with no filter, and on the
client's account Tiny answered 400 "Sua consulta levou muito tempo". It now
asks for orders since yesterday, which proves the same permission.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:54:19 -03:00
Cauê Faleiros
914c55c329 docs: card installments are 3x with interest paid by the customer
Wagner confirmed it. Mercado Pago's card form already shows the rates and the
order checks the price, not the total with interest, so nothing changes in the
code; the Mercado Pago account must keep "parcelamento sem juros" off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:49:11 -03:00
Cauê Faleiros
8387d7ef3a feat: the "Arte tratada" stage is now "Arte conferida"
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 4m29s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m13s
With "Aguardando contato" as a mark on the card, the stage only means the
team has checked the file, and its name now says so. The Kanban and the
customer's Minha conta both take stage names from the server, so this one
name changes both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:18:16 -03:00
Cauê Faleiros
cf12566e86 feat: an order can be marked "Aguardando contato" until the customer is reached
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 4m8s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m7s
The 7 October meeting asked for a way to flag orders whose file needs a word
with the customer before printing: rename Arte tratada, or tag the card. A tag
keeps the stage meaning "file checked" and the order where it is in the
queue. In the order panel, "☎ Aguardando contato" asks what has to be agreed;
the card then shows the mark, the board has an "Aguardando contato" filter,
and the panel shows the note, who marked it and when, the customer's WhatsApp
and "Contato feito", which clears it. The customer is not told. Sellers see
the mark but cannot set it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:41:59 -03:00
Cauê Faleiros
bcce64fff8 docs: the operator guide covers users, the automatic folder and e-mail
All checks were successful
Build and deploy / Validate source (push) Successful in 1m40s
Build and deploy / Integration suite on a real stack (push) Successful in 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 11s
Build and deploy / Publish images (push) Successful in 1m34s
The meeting asked for the operator guide to be sent to the team, and it did
not cover what was built since 5 October. New pages: the print queue's
automatic folder (setting it up in Chrome or Edge, releasing it after a
browser restart, Brave and Firefox) and Usuários (profiles, machines, alerts).
Integrações is described as the new list with "Detalhes", the CDR charge is
mentioned where hand preparation is, and the FAQ answers the "!" on
Integrações and forgotten passwords. Screenshots use fictional people.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 11:48:24 -03:00
Cauê Faleiros
3664fe827e feat: password recovery by e-mail, team alerts, and a price for files opened by hand
Pilot customers had no way to reset a forgotten password, and the 7 October
meeting asked for two things that only needed the client's inputs to go live.

Password recovery: "Esqueci minha senha" in Minha conta sends a link that
works once, for an hour (/conta/redefinir#token, in the fragment so it never
reaches a server or a Referer). Only the token's hash is stored, the e-mail's
text is erased once sent, the answer never says whether an account exists,
and a reset signs out every other session. Limited per address and source.

Team alerts: Kanban users who tick "Receber alertas por e-mail" in Usuários
get one when an order is paid, a cart waits for review, or a payment needs
attention. Messages are queued in the transaction that caused them and sent
by the worker with retries (app/mail.py). Integrações shows an E-mail row
with "Enviar teste".

E-mail is off in production (MAIL_ADAPTER=off; recovery keeps offering
WhatsApp) until the client's SMTP account exists; then it is only settings
(docs/PORTAINER.md). The local stack keeps messages in the database and log.

Files opened by hand: a finished sheet in CDR, AI, PSD or TIFF (or with a
length the customer typed) pays the full price plus MANUAL_FILE_EXTRA_CENTS
per metre, to steer customers to PNG as the meeting asked. It is 0 until
Marcus gives the amount. The Site shows it before checkout, the server
charges it, Tiny gets it in the unit price, and the Kanban says it.

Tested: new tests/mail_test (reset flow, SMTP delivery against a local SMTP
server, retry, who gets alerts), pricing unit tests, and the browser test now
checks the Site total equals the server's, run with the charge at 0 and at
R$ 5,00. The full CI suite passes in a CI-style stack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 11:48:24 -03:00
Cauê Faleiros
86507ed7b5 fix: Integrações is a tidy list, with the long text under "Detalhes"
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 2m43s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m2s
The page was a grid of cards stuffed with paragraphs (Tiny's dates, the
freight's box and cubage, the Firefox how-to), so the cards had uneven
heights and left gaps. Each integration is now one row: name, state, one
line of summary and its main button. Everything else (dates, numbers,
how-tos, secondary buttons like Reconectar or Trocar pasta) opens under
"Detalhes", below its own row, without moving the others around; what is
open stays open through the automatic refresh. Mercado Pago's "Verificar
conta" now shows its result there instead of a 60-second message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:44:52 -03:00
Cauê Faleiros
58ce0a4166 feat: the print queue's automatic folder is switched on in Integrações
All checks were successful
Build and deploy / Validate source (push) Successful in 1m8s
Build and deploy / Integration suite on a real stack (push) Successful in 3m20s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m2s
The folder was a small icon beside "Baixar" in Fila de impressão, easy to
miss, and in Brave it silently fell back to downloads that Brave blocks.
It is now a card in Integrações, which operators also see (only that card):
choose the folder FlexiPRINT reads, or the internal server's share, and
every order that enters the queue has its final files saved there.

- Brave hides the folder API behind a flag; the card says so, shows the
  flag's address with a copy button, and points to Chrome or Edge.
- After a browser restart, a "!" on the Integrações tab and a "Liberar
  pasta" button ask for the one click the browser requires.
- The folder checks the queue every 30 s on its own, so an order moved on
  another computer is saved even with the board's auto-refresh off.
- A browser that cannot rename the finished file copies it instead of
  leaving it as .baixando; errors stay on the card until the next success.

Tested in Brave (flag off: the card explains; flag on: 12 queued files
saved, and an order moved by another session saved 23 s later), and the
browser test now checks that an order entering the queue lands in the folder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:15:59 -03:00
Cauê Faleiros
87cd7d77fb feat: in Firefox, the print queue's files download by themselves
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 3m31s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m27s
Firefox cannot write into a folder a site chose, so the folder button was
hidden there. It now appears in every browser: in Firefox it switches on
automatic downloads, each file that enters Fila de impressão downloaded
once, named after its order, into Firefox's download folder, which the
dialog explains how to point at FlexiPRINT's. Firefox writes .part and
renames when whole, so FlexiPRINT never reads half a file either.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 14:26:11 -03:00
Cauê Faleiros
1216998914 feat: the Kanban saves the print queue's files into a folder the operator chose
All checks were successful
Build and deploy / Validate source (push) Successful in 1m26s
Build and deploy / Integration suite on a real stack (push) Successful in 3m31s
Build and deploy / Secret scan and release gate (push) Successful in 11s
Build and deploy / Publish images (push) Successful in 1m27s
The meeting asked that files moved to Fila de impressão land in the print
room's folder by themselves, instead of each one being downloaded from the
cloud. Beside "Baixar" in that column, a folder button lets the operator
pick a folder (FlexiPRINT's, or the internal server's share). While the
Kanban is open in Chrome or Edge, every final file that enters the queue is
saved there, named after its order, written under a temporary name and
renamed only when whole so FlexiPRINT never reads half a file. A file
already saved is not fetched again, even after FlexiPRINT moves it away.
The folder is remembered; after the browser restarts the button turns
orange and one click releases it. A machine's operator gets only that
machine's queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:42:02 -03:00
Cauê Faleiros
2a2a783ff7 feat: deleting an order frees its files from storage
A deleted order's files stayed in R2 until they expired on their own, up
to 30 days. Deleting now expires its finals, the customer's corrections
and the generated PDFs at once, and its originals too unless it was a
test order, whose quote can still be paid. A file another order or an
open quote still uses is kept. The worker removes them within a minute.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:25:18 -03:00
Cauê Faleiros
3db528a373 feat: UV goes to Tiny as whole metres of DTFIMP.UV.1MT, then DTFIMP.UV.010CM
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 3m12s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 58s
The client registered UV as a metre SKU and a 10 cm SKU. With
TINY_SKU_METRO_<MODE> beside TINY_SKU10_<MODE>, 2,30 m goes as 2 × the
metre SKU and 3 × the 10 cm one, at the price the customer paid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 15:00:00 -03:00
Cauê Faleiros
44cb6ccc16 feat: credit card payments in up to 3 installments
Dropstar sells in up to 3 installments. The card form offers no more, and
the server refuses a payment asking for more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 15:00:00 -03:00
Cauê Faleiros
c75c40ff28 feat: Kanban profiles, a Usuários page, and machines that route orders
Every operator could do everything, and accounts were made from the
console. Each account now has a profile, checked by the server on every
action: Administrador (everything, plus users and machines), Gestão
(everything but users), Operador (moves cards and handles artwork) and
Vendedor (reads orders, quotes and Números, changes nothing). The
superadmin is the system's own account, set from the console and kept by
the account OPERATOR_EMAIL seeds; administrators cannot change it, and
nobody can delete, disable or demote themselves.

The Usuários tab creates, edits, disables and deletes users with a first
password (there is no e-mail yet), and registers machines with the
products each prints. An order goes to the first active machine that
prints its product, or to the one chosen in its panel; an operator tied
to machines sees and downloads only their orders. Everyone changes their
own password in the account menu, which now holds the name and Sair too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 15:00:00 -03:00
Cauê Faleiros
6c2dcc77b0 docs: the Site guide for today's Site, with its source in the repository
The 24/09 guide said files go up to 128 MB (5 GB now), that the team
reviews every quote before payment (the Site approves it), that payment
is PIX or card (credit card or PIX, on a page of its own), that WhatsApp
notices go out at four moments (two do; the team sends the correction
notice), and showed the order number customers no longer see. It lacked
Minha conta, freight by CEP, choosing which cart items to pay and the
refusal messages, and its status page was from week 2. Rebuilt in the
operator guide's format, source in docs/guias/site, new screenshots from
the local stack with fictional customers; imprimir.sh prints both guides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:42:29 -03:00
Cauê Faleiros
5063c152c2 fix: the Site no longer promises a review before payment, notices at every step, or boleto
The home page's steps said "Conferimos a metragem e liberamos o pagamento"
and "Aviso no WhatsApp a cada etapa": carts are now approved by the Site
and paid at once, and WhatsApp notices go out when the payment is approved
and when the order is ready. They read "Pague na hora: cartão de crédito ou
PIX" and "Acompanhe em Minha conta, com aviso no WhatsApp quando ficar
pronto". The footer listed boleto, which the Site does not take.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:42:28 -03:00
Cauê Faleiros
959ed37b15 feat: a refused payment says what happened and what to do, in plain Portuguese
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 4m10s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m11s
A refused card showed Mercado Pago's code ("Pagamento recusado pelo Mercado
Pago (cc_rejected_insufficient_amount)"), a request it refused showed its
cause list, and some errors were in English ("Quote is already paid",
"Payment provider unavailable; try again"). Each now becomes one sentence:
"O cartão não tem limite suficiente para este valor. Use outro cartão ou
pague com PIX." The codes still go to the log and, on the Kanban's "Cartão
recusado" badge, beside the same sentence. A form check the customer cannot
read is replaced by a general one, and every error a customer or operator
can meet in the quote, upload, account and artwork routes is in Portuguese.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 15:54:14 -03:00
Cauê Faleiros
172544b173 feat: a Tiny order can sell UV as the client's one SKU per 10 cm
All checks were successful
Build and deploy / Validate source (push) Successful in 15s
Build and deploy / Integration suite on a real stack (push) Successful in 3m26s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m7s
Dropstar sells UV only as DTFIMP.UV.010CM, per 10 cm. TINY_SKU10_<MODE>
names such a SKU: 2,30 m goes to Tiny as 23 of it at the price the customer
paid, with a rest that does not divide on a line of its own so the order
adds up to the cent. "Testar conexão" and tiny_probe conferir check it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 15:27:45 -03:00
Cauê Faleiros
43d9a3c637 feat: the Site takes credit card and PIX only, no debit
Dropstar does not take debit cards, and Mercado Pago never enabled debit on
the account, so a customer who chose "Cartão de débito" met an error. The
payment page offers credit card and PIX, the card form accepts only credit
cards, and the server refuses a debit method sent around the page. The
adapter still knows how to pay by debit, should it be offered again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 15:27:45 -03:00
Cauê Faleiros
ac1d8743b1 docs: the operator guide for today's Kanban
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 3m14s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m3s
Rewritten for what changed since 25/09: quotes are approved by the Site and
only those over 50 m or with a grade that does not match reach the team;
the order panel's next-step box approves the final file, a customer's
correction or the generated PDF in one click; cards show the company name
and what is missing; columns are queues with "Baixar" for the print queue;
a correction is announced with a WhatsApp message ready to send; orders are
cancelled and deleted from the "⋯" menu; the new Números tab; and the board
refreshes by itself. New screenshots from a throwaway stack with four
fictional companies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:09:09 -03:00
Cauê Faleiros
545a8c0f2d fix: card pictures load reliably, and the queue button fits its column
A picture had no size until it loaded, and a lazy image with no size may
never be loaded, so some cards showed the layout drawing instead. Pictures
now take their whole box from the start (object-fit keeps the look). A
picture dropped by a re-render while loading no longer counts as missing,
which removed it from every later render until a reload.

"Baixar todos" spilled out of the Fila de impressão header at 1440 px; it
is "Baixar" now, with the full description in its tooltip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:09:09 -03:00
Cauê Faleiros
8997e22f5e fix: CNPJ name lookups run on their own thread, so a slow registry never delays orders
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 3m36s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m10s
The worker looked names up inside its main loop, which also sends orders to
Tiny and asks Mercado Pago about payments. Without internet, or with the
registry slow, five lookups could hold that loop for most of a minute.
They now run on a thread of their own, one batch at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:31:25 -03:00
Cauê Faleiros
b3c5f63553 feat: customers show by their company's name, taken from the CNPJ registry
The Site asks for e-mail, CNPJ and WhatsApp only, so the Kanban showed an
e-mail where a name belongs and a new Tiny contact was named after it. The
worker now looks up each customer's CNPJ in the public registry (BrasilAPI,
no key) a few at a time, never while a customer waits, and keeps the razão
social and trade name in dtf_local.cnpj_names; a failed lookup is retried a
day later. Cards, the order panel, quotes and the search results show the
trade name (else the razão social) above the e-mail, the search finds
orders and quotes by either name, and a new Tiny contact gets the razão
social as its name and the trade name as fantasia.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:19:35 -03:00
Cauê Faleiros
581fbe6be4 feat: a one-off job makes the artwork pictures for orders from before them
The customer's browser makes each upload's picture, so older orders show
"sem prévia" on the Kanban. ops.backfill_thumbnails, run once from the
worker's console, reads each PNG, JPEG or WebP an order or live quote still
refers to and stores a WebP the Site's size. PDFs and CorelDRAW files need
a renderer the server does not have and keep the layout drawing; images
over 100 million pixels are skipped so the worker's memory stays bounded.
Running it again only looks at uploads that still have no picture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:11:02 -03:00
Cauê Faleiros
b1fbaad2bd feat: a launch cleanup that clears the test orders, run once by hand
ops.launch_reset counts the orders, quotes, payment attempts and
notifications, and with --confirmar APAGAR removes them, with their moves,
files and notices. The artwork files are marked expired so the worker
deletes them from storage. Operators, the Tiny connection and the backups
stay; --contas also removes customer accounts. It refuses if any payment
was made with real money. Order numbers restart at #1 with the database
administrator's rights, so the script prints the psql line for the db
container when the worker's role cannot do it.

The test runs last in CI, since it empties the order tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:07:24 -03:00
Cauê Faleiros
1b445f0459 feat: a Números tab with the production numbers the board already records
Every paid order and every move is recorded, but nobody could see the
totals. The new tab shows, for the last 7, 30 or 90 days: paid orders,
metres sold, money received, the average ticket, how many orders needed a
correction, and the median time from payment to Finalizado. A column per
day charts the metres sold (with a table under it), and a table gives each
stage's median time and what waits in it now, with the oldest order.
Test and cancelled orders stay out.

The header now has five tabs: the search box narrows first, the refresh
picker keeps its width, and the operator's e-mail moves to Sair's tooltip
on narrower screens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:01:03 -03:00
Cauê Faleiros
f567e6da89 feat: "Baixar todos" downloads every final file in the print queue, named after its order
To import a day's work into FlexiPRINT the operator opened each order in
Fila de impressão and downloaded its final. The column now has "Baixar
todos": the approved finals of every order in the queue, in queue order,
each named pedido-<n>-item-<i>-<original>. They download one by one from
storage with short-lived links; a zip of multi-GB sheets would go through
the server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:48:57 -03:00
Cauê Faleiros
c5b1bd37a6 feat: an order in correction offers the customer's WhatsApp with the message written
Customers are not told automatically that their artwork needs a fix: Tiny
has no situação for it. An order in Correção now opens with the reason and
"Avisar no WhatsApp", which opens the customer's chat with the message
ready: the order code, the reason and the link to send the new file in
Minha conta. "Copiar mensagem" covers orders without a WhatsApp number.
The board carries each corrected order's last reason and the Site's address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:42:49 -03:00
Cauê Faleiros
e81b2b1681 feat: a Tiny order can be the client's own SKUs per length, 1 metro plus the rest
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 2m31s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 59s
Dropstar's catalogue sells film as SKUs per length, and an order is a sum of
them: 1,30 m is one "1 metro" (DTFIMP.TX.100CM) and one "30 cm"
(DTFIMP.TX.0030CM). The adapter sent one product with the metres as the
quantity. TINY_SKU_<MODE> names a mode's SKU prefix; the order then carries
N times the metre SKU and one 10 cm SKU for the rest, at the price the
customer paid, the last line taking what is left of the item so the order
adds up to the cent. Each code is looked up once by its exact SKU among the
active products. "Testar conexão" and tiny_probe conferir check all ten, and
tiny_probe pedido takes --metros to show a split test order.

Modes without the setting keep their product id: UV and artes avulsas stay
that way until their SKUs are confirmed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 10:46:07 -03:00
Cauê Faleiros
a5c1ca53c0 feat: approving the final file is the Kanban's next step, at the top of the order
All checks were successful
Build and deploy / Validate source (push) Successful in 1m11s
Build and deploy / Integration suite on a real stack (push) Successful in 3m7s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m24s
An order in Arte tratada without an approved final showed "Mover para Fila
de impressão" as its main button, which the server refused, while the
approval sat folded at the bottom of the panel. Now the top of the panel
says what comes next: approve the final, with the file that would be
printed and a link to download it. A customer's correction or the
generated PDF is approved with one click; otherwise the upload form opens
in place. Once approved, the main button becomes the move to the queue.

A customer's correction can be approved as the final itself, without
downloading and sending it back. The board carries each order's approved
items and corrections, so cards say "Falta aprovar o final", "Correção
recebida" or "Final aprovado", and the item card shows the correction
instead of the stale reason the generated file could not be made.

Going back a stage is a small link, and cancelling or deleting a test
order moved into a "⋯" menu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 10:06:03 -03:00
Cauê Faleiros
4b804a2c85 feat: the Kanban refreshes by itself, every 10 s to 15 min, and says what is new
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 2m37s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 52s
Beside "Atualizar", a picker sets how often the Kanban reloads by itself (off,
10 s, 30 s, 1, 5 or 15 min; 30 s by default, remembered by each browser). It
waits while the operator types, drags or has an order open, and with the tab
hidden it still looks at most once a minute. A new order in "Arte recebida"
or a new quote to review shows a notice, and the count goes into the tab's
title until the operator looks at it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 18:03:21 -03:00
Cauê Faleiros
c3c56a7f21 fix: keep the payment confirmation on screen; only a new checkout drops a paid quote
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 3m3s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m10s
bc1fb60 forgot the paid quote as soon as the confirmation showed, so the next
refresh of the page (the cart emptying) found no quote and replaced "Pagamento
confirmado" with "Nenhum pedido aguardando pagamento". The confirmation keeps
its quote again; the paid one is dropped only when the customer asks to pay a
cart identical to it, which then becomes a new order. The browser test waits
for the confirmation, and checks no "Pedido #" is shown, instead of catching
the momentary "Pedido #N criado" line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 17:07:46 -03:00
Cauê Faleiros
bc1fb60468 fix: a new cart goes to payment instead of showing the last order already paid
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Failing after 3m19s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Has been skipped
After a payment the browser kept the paid quote as its draft, so a cart
identical to it (the same test repeated) opened the old "Pagamento
confirmado" instead of a payment. The confirmation now forgets the draft, and
a draft found already paid when the customer asks to pay starts a new order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 17:02:35 -03:00
Cauê Faleiros
894e75fd94 feat: Kanban columns are queues, and a card can be dragged up or down
Some checks failed
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Integration suite on a real stack (push) Failing after 3m24s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Has been skipped
Each column is sorted explicitly by payment time, first paid on top, however
the board's list was put together (older finished orders, one opened from the
search). A card dragged within its column lands between the two it was
dropped between (queue_key, halfway between their keys) and keeps that place
for everyone; moving to another stage clears it. Reordering is not activity:
the stalled clock keeps running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 16:57:31 -03:00
Cauê Faleiros
d7b1eaae6d feat: customers see an order code, not the sequential number
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 3m2s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Has been skipped
"Minha conta" lists and opens orders as "Pedido 1E867B56" (the first 8
characters of the order's id) and searches by that code, so a customer never
sees how many orders the store has. The Kanban shows the code beside the #
number, with a copy button, and its search finds an order by the code a
customer reads out. Tiny keeps its reference (DTF-<number>): it is how a
resent order is found there instead of duplicated, and the WhatsApp notices
the client sends from Tiny use Tiny's own number.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 16:50:26 -03:00
Cauê Faleiros
c19941555e fix: the payment confirmation no longer shows the order's sequential number
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 3m15s
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 <noreply@anthropic.com>
2026-10-02 16:43:40 -03:00
Cauê Faleiros
8236ad8f0a feat: a cancelled order can be deleted
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 2m55s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m2s
"Excluir pedido" now also works on a paid order once it is cancelled; one in
progress must be cancelled first, with its reason. Deleting a cancelled order
also discards its quote, so it neither returns to Cotações as unpaid nor can
be paid again. The payment stays recorded and the audit log keeps who deleted
which order and the cancellation reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 16:32:26 -03:00
Cauê Faleiros
dfa297d9b5 fix: "Excluir pedido de teste" asks before deleting instead of failing
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 2m51s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Has been cancelled
The order panel kept the "Enviar para correção" button in a variable named
`confirm`, which hid window.confirm from the new delete button ("confirm is
not a function"). It is renamed, as is the same name in the final-files form,
and every question to the operator calls window.confirm explicitly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 16:28:40 -03:00
Cauê Faleiros
05da6d78ad feat: discard an unpaid quote, delete a test order, cancel a paid one
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 2m44s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 54s
Cotações (now subtitled "pedidos ainda não pagos") can discard a quote: it
leaves every list and the search, and a payment for it is refused like an
expired one. A test order can be deleted with its history; its quote is unpaid
again. A paid order is cancelled with a required reason: it leaves the board
for a "Cancelados" chip, keeps its payment and history, can no longer move,
and the customer's account shows it as cancelled. Refunds stay at Mercado
Pago and Tiny is not told; the cancel form says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 16:20:27 -03:00
Cauê Faleiros
7877489563 feat: an approved payment becomes the order by asking Mercado Pago, not only by its notice
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 3m14s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 55s
Production approved a test card while every notification was refused by
signature, and the order never appeared. payments.reconcile() asks the
provider about the payments of open quotes and applies its answer through the
same path as the webhook: the amount must match the reviewed quote, and the
event id (payment id and status) makes a notice and a lookup one delivery,
applied once. The payment page's polling checks an approved card at once; the
worker checks every minute for the rest, such as a PIX paid after the page was
closed. The webhook stays; it is no longer the only way in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 15:58:40 -03:00
Cauê Faleiros
0218f119aa fix: Mercado Pago's signed notifications verify with a pasted secret and close formats
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 2m43s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 54s
Production refused every notification, all current-format (data.id, type),
signed and fresh, though the event and the secret looked right. The secret is
now trimmed (a space or line break pasted into the stack changes every HMAC),
and a few close variants of the signed text are tried besides the documented
one (without the request id, the id's own case, the id from the body); each
still needs the secret. The one that matched, and whether the secret was
trimmed, go to the audit log so the real format can be settled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 15:43:34 -03:00
Cauê Faleiros
ca7cf7f701 chore: say what a refused payment notification looked like
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 3m8s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 57s
"payment_webhook_rejected reason=signature" did not tell an unsigned old-style
IPN notice (topic/id, which Mercado Pago may send alongside the signed webhook
when a notification_url is given) from a real signature mismatch. The audit now
records the query parameter names, source_news, whether the signature and
request-id headers came, and the signature's age; never values or secrets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 15:18:51 -03:00
Cauê Faleiros
67825a983d fix: payment errors show in red, not in the green of a success
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 2m38s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 54s
The payment page's one message line was always green, so "O Mercado Pago
recusou o pagamento" looked like good news. Each message now has a tone: an
error (a refusal, a form error, a missing field) in red, a changed cart or an
expired quote in amber, a created order in green, the rest neutral.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 13:56:07 -03:00
Cauê Faleiros
90c574a673 docs: the Jadlog freight checked against the old site and confirmed by the client
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 3m5s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m1s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 13:27:10 -03:00
Cauê Faleiros
5616db1345 feat: Cotações shows the last payment attempt and fits the window
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 2m43s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 53s
Each quote shows its latest payment attempt as a badge ("PIX gerado · expira
12:22", "PIX expirou sem pagamento", "Cartão recusado"), so "tried to pay" is
told apart from "never tried"; quote_view carries the PIX expiry and the
attempt's time for it. The quote stays payable for its 24 hours: a new PIX is
for the same quote.

Cotações now fills the window and never scrolls: a page holds as many quotes
as the list's height fits, measured after each render and on resize, and the
page bar sits at the bottom of the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 11:55:59 -03:00
Cauê Faleiros
1fb2e5d55a feat: expired quotes leave the Kanban, and the buyer's name comes before the e-mail
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 2m42s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 57s
A quote approved more than QUOTE_VALID_HOURS ago can never be paid; it no
longer shows in Cotações, its count or the search. Wherever a customer is
shown, the name comes first (the customer's, else whoever receives the
delivery) with the e-mail under it; with no name, the e-mail alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 11:31:50 -03:00
Cauê Faleiros
7a908060fc fix: the Kanban shows the package's real weight and what Jadlog charges it as
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 2m40s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 57s
"Frete Jadlog · 4,541 kg" read as if 2,30 m of film weighed 4.5 kg. It now
reads "0,47 kg · cobrado como 4,54 kg pela caixa" when the box's cubed weight
is what Jadlog charges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 11:25:26 -03:00
Cauê Faleiros
b7abd401ec feat: Kanban badges: grade pills, product and warning badges, facts in a grid
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 3m17s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m13s
One badge system on every screen (canvas "Kanban DTF — redesign", v2). The
grade is a pill coloured by the price ladder's bands (90/75/60/40); product,
status and warnings are pills with text, so colour never carries meaning alone.

Quote rows: grade, product, metres, delivery city and age on one line; the
"Aprovada automaticamente" line is gone (only a team review is noted), and a
dot marks quotes from the last ten minutes. The quote detail has a status
badge, the total in large type, a copyable CNPJ, a WhatsApp button, facts in a
grid and items and freight apart. Board cards carry the grade, product, place
and a row of warning badges; columns take their stage colour and filter chips
their counts. The order panel shows what was paid and whether it is stalled at
the top, customer and delivery as cards, a print problem as a callout, the
final-file form behind a "next step", and dates on the right of the history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 11:09:13 -03:00
Cauê Faleiros
4b8b00443e feat: a Jadlog quote counts one box per 60 m of film
All checks were successful
Build and deploy / Validate source (push) Successful in 1m20s
Build and deploy / Integration suite on a real stack (push) Successful in 3m11s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m19s
The client corrected the box to 63 x 15.5 x 15.5 cm and said one box holds
about 60 m. JADLOG_METROS_POR_CAIXA quotes a longer order as several boxes,
each with its packaging weight and volume. UV ships in the same box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 10:04:54 -03:00
Cauê Faleiros
26c46ccc1d feat: Jadlog quotes by the larger of the real and the cubed weight
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 3m5s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m1s
The client's box is 56 x 14 x 14 cm and weighs 0.30 kg; the film is 0.075 kg
per metre. Jadlog charges the larger of the real and the cubed weight, and this
box is large for its weight, so quoting the real weight alone would price
below what Jadlog charges. JADLOG_CAIXA_CM and JADLOG_CUBAGEM_KG_M3 (both or
neither) give the cubed weight; the quote sends the larger. Until the
contract's factor is set, the Kanban's Frete card says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 16:20:44 -03:00
Cauê Faleiros
b9ebdc0fdb fix: "Criar pedido de teste" works again, and the quote list is wider
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 3m22s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m8s
A checkbox label named `confirm` in the quote panel hid window.confirm from
the test-order button, which failed with "can't access lexical declaration
'confirm' before initialization". The quote list takes about a third of the
screen (up to 640 px) and cuts long e-mails with an ellipsis.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 15:43:55 -03:00
Cauê Faleiros
2c664a1cc8 style: the Site at 88% on computers, 10% bigger than before
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 2m57s
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 <noreply@anthropic.com>
2026-10-01 13:44:10 -03:00
Cauê Faleiros
352590e63a feat: Kanban shows each order's artwork, filters quotes and searches orders and quotes
All checks were successful
Build and deploy / Validate source (push) Successful in 1m25s
Build and deploy / Integration suite on a real stack (push) Successful in 3m16s
Build and deploy / Secret scan and release gate (push) Successful in 13s
Build and deploy / Publish images (push) Successful in 1m29s
The customer's browser sends the small picture it already makes of each file
(at most 300 KB, WebP/JPEG/PNG read from the bytes, own uploads only); it goes
when the file's bytes go. Board cards, quote rows, the order panel and the
quote detail show it, with the layout drawing as a second view and as the
fallback for files without a picture.

Cotações gets a customer filter (e-mail, CNPJ, WhatsApp) and product, layout
and resolution-warning chips, with the page bar always shown. The board adds
Entrega, Retirada and stalled-order chips. The top search now covers orders in
any stage and unpaid quotes; CNPJ and phone match by digits only when nothing
but digits and punctuation was typed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 11:46:33 -03:00
Cauê Faleiros
b54c635cfc fix: remove three explanatory lines from Dados da conta
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 10:02:05 -03:00
Cauê Faleiros
f6ce624b29 chore: a local demo customer for looking around Minha conta
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 09:41:23 -03:00
Cauê Faleiros
ef95dcc327 fix: the page's centred blocks keep their full width in the column layout
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 2m44s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m2s
Making the body a column to keep the footer at the bottom shrank every
block centred with auto margins (the account area, and two of the Site's
sections) to the width of its content. They take the full width again, up
to their max-width, exactly as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:34:09 -03:00
Cauê Faleiros
0b86fe79fc fix: the footer stays at the bottom of the screen on short pages
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 2m51s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 56s
On a short page (sign-in, an empty cart) the footer followed the content
and the rest of the screen was left blank below it, more so with the Site
drawn at 80%. The body is now a column at least the screen's height with
the footer pushed to its end; under the 80% zoom that height is 125vh,
because the zoom scales viewport units too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:12:55 -03:00
Cauê Faleiros
24ee4e9eab feat: Minha conta with sign-in, overview, orders and account details
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 3m7s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m6s
The order page becomes the customer's area, one page at four addresses:

- /conta/entrar: sign in or create an account, side by side. "Esqueci
  minha senha" points to the Dropstar WhatsApp until e-mail can be sent.
- /conta: the counts of orders waiting for payment, in production, in
  correction and finished, and the latest one.
- /conta/pedidos: every order and the cart waiting for payment in one list,
  newest first, filtered by group, order number and period, ten per page.
  The cart shows "Aguardando pagamento" and its "Pagar" goes to the PIX
  page when a PIX code is open. An order opens in place with its progress,
  items, delivery, history, files and the correction form. A guest sees
  the orders paid in this browser.
- /conta/dados: WhatsApp and a saved delivery address (the CNPJ is locked),
  e-mail and password changes, both confirmed with the current password;
  a password change signs the other devices out.

The cart fills in the account's details and saved address. New API routes
for the details, and the order list takes filters and pages and returns
the counts; only the newest unpaid quote whose files still exist is listed.
The Site's "Minha conta" and "Ver meus pedidos" point to the new addresses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:57:37 -03:00
Cauê Faleiros
223854e392 feat: the order page in the Site's look, and no search box
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 2m37s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 59s
"Meus pedidos" was still the prototype's plain page. It now has the Site's
stripe, header and footer, and its type, colours and cards: each order shows
its status, a progress line through production (or the correction the team
asked for), the items with metres and price, where it goes, and on request
the history, the files to download and the correction form. Carts waiting
for payment are listed with a button to pay. Sign-in and account creation
are side by side.

The header, stripe, menu, footer and tokens moved from index.html's inline
style to site-shell.css, which both pages load. The header's search box,
which did nothing, is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:13:35 -03:00
Cauê Faleiros
0b55ebce7f style: the Site at 80% on computers, and seconds instead of "quase pronto"
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 2m43s
Build and deploy / Secret scan and release gate (push) Successful in 4s
Build and deploy / Publish images (push) Successful in 58s
The text sizes were chosen looking at the Site with the browser at 80%; at
100% everything felt too big. On screens 1100 px and wider the Site is now
drawn at 80% (CSS zoom); phones and tablets keep their sizes. The time left
while reading a large file shows the seconds under 10 s ("faltam 7 s")
instead of "quase pronto".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:39:50 -03:00
Cauê Faleiros
bee7f8f245 feat: the preview of a large file says how long is left, not a percentage
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 3m2s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m0s
Reading a large PNG in the browser for its preview showed "gerando a
prévia… 87%". It now shows the time left, worked out from how long the
reading has taken so far: "faltam cerca de 25 s", "faltam cerca de 3 min",
"quase pronto". The bar still fills as it goes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:18:21 -03:00
Cauê Faleiros
c5db1375de test: reload only after the cart is saved, instead of after 800 ms
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 2m50s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m2s
The browser suite reloaded the page a fixed 800 ms after the last field
was typed. The cart save waits for typing to stop and writes the files to
the browser's storage, so under load the reload came first and the cart was
not recovered ("persistent cart recovery", and once "Inspected target
navigated or closed"). It now waits until the cart is in storage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:55:19 -03:00
Cauê Faleiros
3d8bca3af7 feat: the upload bar says how long is left, not a notice before it
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 2m42s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m2s
The product page's notice about the upload time is gone. The cart's upload
bar now reads "Enviando seus arquivos · faltam cerca de 6 min", measured
from the upload's own speed (a range from the size for the first seconds),
with a line saying the time depends on the internet and to keep the page
open. The header and the pay button show the same time instead of a
percentage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:43:30 -03:00
Cauê Faleiros
f3fc733352 fix: the upload-time notice leaves with the files, and says it in one line
All checks were successful
Build and deploy / Integration suite on a real stack (push) Successful in 2m37s
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 56s
The notice stayed on the product page after the item went to the cart,
showing the last file's size on the next order. It is now redrawn wherever
the files are cleared and hidden when no product is open. The text is one
line: "Envio: até 8 min (501,2 MB), conforme sua internet. Mantenha a
página aberta."

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:25:50 -03:00
Cauê Faleiros
4ce44feb70 fix: mark the required fields instead of a message about the address
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 2m46s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Has been cancelled
Removes "Complete o endereço de entrega para ir ao pagamento." The required
fields (CNPJ, WhatsApp, e-mail, and the delivery address except the
complement) carry a red asterisk, and aria-required for screen readers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:22:13 -03:00
Cauê Faleiros
01b94da36d feat: choose which cart items to pay, with a thumbnail of each
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 3m22s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m13s
Each cart item has a checkbox and a thumbnail of its first file (or its
extension when there is none). Only checked items are priced, quoted,
uploaded and paid; an unchecked item stays in the cart, dimmed, for a later
order, and stays there after the others are paid. The header count is the
whole cart; the summary counts what is being paid.

Also removes the "A conta nasce aqui…" and "Carrinho salvo neste
navegador…" texts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:57:16 -03:00
Cauê Faleiros
25fa890e92 style: one more step up for the text and icons
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 2m36s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m6s
Every Site text size up to 18 px grows another pixel, the Kanban's up to
14 px half a pixel, and the icons one pixel. The pay button grows to two
lines when "Pagar os N itens de uma vez" no longer fits on one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:37:20 -03:00
Cauê Faleiros
4386fc0737 style: larger text across the Site and the Kanban, and icons to match
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 2m47s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m5s
Most of the text was 11 to 13 px and hard to read. Every size up to 16 px
grows: by 1.5 px up to 12.5, 1 px up to 14 and 0.5 px up to 16 on the Site,
and a little less on the denser Kanban. Headings and prices keep their size.
Icons grow by 2 px so they stay in proportion with the text beside them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:26:00 -03:00
Cauê Faleiros
70a76feb23 feat: icons on the buttons, delivery, payment, status and Kanban
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 2m40s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 53s
- Buttons: add to cart (bag with plus), go to payment (lock), remove from
  the cart (bin).
- Delivery: a pin for pickup in Franca, a truck for home delivery.
- Payment: card and QR code on the methods, copy on the PIX code, a clock on
  its countdown, a check on the confirmation.
- Status: a check when the files are sent, check, alert, redo and cross in
  the quality list instead of Unicode symbols, and a check on finished steps.
- Kanban: a truck or pin for where an order goes, a speech bubble on the
  WhatsApp link, a download arrow on the file buttons.

All Lucide shapes drawn inline, as in the header.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:13:45 -03:00
Cauê Faleiros
20982a945f feat: icons in the header and on the Montagem controls
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 2m50s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m18s
The header's search, account and cart get icons, with the item count on the
cart instead of "Carrinho (N)"; on phones only the icons show. The upload
zone, remove, rotate and mirror buttons used Unicode symbols that look
different, or are missing, depending on the system's fonts; they are now
Lucide icons (ISC licence) drawn inline, so nothing new is loaded and the
CSP is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:56:01 -03:00
Cauê Faleiros
37715ef223 feat: the server checks the grade against the files before approving
All checks were successful
Build and deploy / Validate source (push) Successful in 1m23s
Build and deploy / Integration suite on a real stack (push) Successful in 3m13s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m25s
The price depends on the grade, which the browser worked out and the API
took on trust. Before a cart is approved at checkout the API now recomputes
it from the uploaded files by the Site's own rules: the pixel size in a
PNG, JPG or WebP header across the printed width (rotation included), and
the area-weighted DPI of the images placed in a PDF of up to 150 MB, 300
for vectors. Sheets take the worst grade, artworks the average. A claim more
than 2 points above the file's grade, or a discount on a file the server
cannot grade, waits for an operator, with the reason on the Kanban.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:24:37 -03:00
Cauê Faleiros
b7e2ea12d0 feat: accept large JPG and WebP artworks instead of refusing them
Above 150 MB the browser cannot read JPG or WebP in parts, so a large
artwork was refused. It is now measured from its header, graded and priced
with the discount like any other, and placed on the sheet as a full box,
which is exact for JPG. The card says there is no preview and that the team
checks the art before printing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:14:04 -03:00
Cauê Faleiros
933bd30cbd feat: an unpaid cart's files are kept 2 days, a paid order's 30
Files are uploaded before payment so the price and the security check use
the file itself, but an abandoned cart kept them for 30 days. Now a finished
upload is held 2 days, a quote waiting for review 7, an approved quote 2 more
to be paid, and the paid order keeps its originals for 30 days from upload.
A payment never starts for files that are gone; one under way holds them a
day. Files attached to an order take the order's window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:09:02 -03:00
Cauê Faleiros
eb254da501 feat: tell the customer how long the upload takes before it starts
When files are picked, the product page shows the range the upload takes
between a slow (10 Mbps) and a fast (150 Mbps) connection, and asks to keep
the page open. The cart shows the same range until the real speed is
measured, then the measured time left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:09:02 -03:00
Cauê Faleiros
8786a33c8d fix: the cart keeps only its items, never the customer's details
The browser put the CNPJ, WhatsApp, e-mail, CEP and address back after a
reload without telling the page, which then showed them but could not pay
until they were typed again. The fields are now emptied on load and marked
autocomplete="off", and the saved cart holds only the items: the details and
address are typed again after a reload or a closed tab. The payment page
already takes them from the server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 09:23:18 -03:00
Cauê Faleiros
20403c5132 feat: daily encrypted database backup to a bucket of its own
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 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m2s
A backup service runs pg_dump every day at 03:00 Brasília, checks the archive,
encrypts it with age to a public key and uploads it with a token for that
bucket only. The server cannot read or delete backups: the private key stays
with the owner, the bucket's lifecycle rule expires copies and its lock stops
early deletion. Each run is recorded and shown on the Kanban's Integrations
tab. tests/backup_test.py backs up, restores into a scratch database and
compares the rows in CI. Setup and restore: docs/BACKUP.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 18:49:21 -03:00
Cauê Faleiros
1b57313496 feat: give Artes avulsas the file card of Folha já montada
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 2m49s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 54s
Each artwork gets the same card as a finished sheet: "Suas artes" with the
count of artworks and copies, a thumbnail, the size in cm with pixels,
format and weight, a DPI chip and how many fit per row, the resolution or
width hint, then width in cm, a copies stepper, rotate and mirror, and the
usual sizes. Packing, pricing and the hints are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:49:22 -03:00
Cauê Faleiros
a02711ef2b fix: keep every Dúvidas link in its row, one answer open at a time
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 2m24s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 52s
Opening a question moved its link out of the row into the answer, and only
that heading closed it again. The four questions are now a row of links
that always stays: the open one is highlighted, its answer shows below,
another link switches to its answer and the same link closes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:55:25 -03:00
Cauê Faleiros
8dddf0fa25 feat: redesign the Montagem page, with thumbnails, check chips and a DPI price scale
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 2m31s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m0s
The product page is rebuilt around mockup 1. The two ways to send are
cards under the title; the PNG/CDR route choice is gone (it never changed
the price, and the picker now takes every allowed format). Each file card
has a thumbnail, its size, check chips with a plain sentence for any
problem, a "Ver detalhes da conferência" link and a copies stepper; a CDR
file says "Conferência manual · preço cheio" and asks for the length. The
buy box shows the price scale in DPI with the customer's step, the metre
and 10 cm length, the total and what the resolution saved, and "Sai em N
partes" only above 20 m. Folha já montada gets "Ampliar" instead of zoom.
Pricing, grade and checks are unchanged.

Fixes on top: the card thumbnail is a small image made once, not the full
preview re-parsed on every repaint; sizes from 1 GB up read in GB; a failed
upload is shown with "Tentar de novo" instead of retrying silently on every
cart change. The browser suites wait for the product and the reloaded page
instead of racing them, and the artwork suite delays imagemDaArte, which
the packing now uses, fixing the CI failure of f4aacb5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:36:41 -03:00
Cauê Faleiros
f4aacb5776 feat: pack large artworks in Artes avulsas from a streamed copy
Some checks failed
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Failing after 2m36s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Has been skipped
Artes avulsas decoded every file whole, and the packing decoded each one
again on every repaint, so a large artwork failed to load. A PNG over 150
MB is now measured from its header (pixel size, so DPI and grade stay
exact) and packed from a 1200-pixel copy read as a stream, with progress on
its card; every artwork's image is loaded once and reused by the packing.
A large JPG or WebP asks for a PNG, and the grade card no longer calls a
file unreadable while it is still being read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:02:35 -03:00
Cauê Faleiros
64e47ee481 feat: skeletons where the page waits, no flicker while a sheet is read, repeated copies in the preview
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 2m30s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 57s
Reading a large sheet repainted the list and "Sua folha" on every progress
step, so the preview flickered; progress now moves the bar in place and
"Sua folha" shows a skeleton until the preview is ready. A sheet printed
N times is shown N times (up to six, then a count). The payment page shows
skeletons while the order loads and until the card form is ready.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:52:58 -03:00
Cauê Faleiros
2b313a1cc8 feat: show upload progress with a bar, time left and a header badge
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 2m27s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 45s
Uploads of several GB ran behind one grey line in the cart. The order
summary now has a progress bar with the percentage, size and an estimate of
the time left from the recent speed; the header shows "enviando 45%" on
every page while it runs; the payment button says what it is waiting for;
and leaving the page mid-upload asks first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:34:57 -03:00
Cauê Faleiros
7116ebe50a feat: preview and check large PNG sheets by reading them as a stream
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 2m33s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m0s
A large sheet had no preview and no automatic check of pieces, residue,
gaps and background, because decoding it whole would crash the browser.
A PNG over 150 MB is now inflated as a stream (DecompressionStream) and
unfiltered row by row, keeping every n-th pixel: a 600-pixel-wide copy in
about 100 MB of memory whatever the file's size (6.6 s for 500 MB, 22.7 s
for 2.4 GB of random pixels, identical to Pillow's output for RGB, RGBA,
grey, grey+alpha, palette and 16-bit). The copy is the preview and what
the sheet check reads; the grade still comes at once from the header.
The preview note promising a server-side re-nesting that does not exist
is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:25:13 -03:00
Cauê Faleiros
9e69c48d2d feat: let operators create test orders from approved quotes
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 2m28s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 47s
Without an approved card payment there was no way to try the board, the
files and the print flow in production. "Criar pedido de teste" on an
approved quote creates the order through the same path as a paid one, marked
TESTE on its card and panel and audited; neither it nor its stage moves
queue anything for Tiny or WhatsApp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 14:50:40 -03:00
Cauê Faleiros
64c1260a9f feat: report Mercado Pago's notifications in the account check
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 2m16s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 45s
Without access to the Mercado Pago panel, "Verificar conta" now also says
how many payment notifications arrived and passed the signature in the last
24 hours, how many were refused by it, and the last one received: the PIX
payments created in test mode notify the webhook, so this shows whether
Mercado Pago reaches the server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 14:35:47 -03:00
Cauê Faleiros
b5bb03cbb4 feat: check the Mercado Pago account from the Kanban
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 2m18s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 44s
"Verificar conta" on the Mercado Pago card of the Integrations tab runs the
read-only account check (whether the token is a test user's, the card
methods, how the test card is classified) without a container console.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 14:18:45 -03:00
Cauê Faleiros
2495edf188 fix: keep the payment page's styles off Mercado Pago's card form
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 2m22s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 47s
The rule sizing the PIX code field applied to every input in the payment
area, turning the card form's instalment radios into tall boxes; the
heading rule likewise reached the form's own headings. Both now apply only
to the page's own elements.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 14:14:06 -03:00
Cauê Faleiros
f5fed013ab fix: ask 3-D Secure of debit cards only, and send the cardholder as the card payer
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 2m13s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m9s
A credit card payment with the test credentials was refused with 10113
("the payment method is excluded by a rule"). Every card was sent with
three_d_secure_mode, which only debit needs, and with the order's CNPJ as
payer instead of the cardholder's document from the card form. Debit
methods keep 3-D Secure, and the card form's document is the payer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 13:57:19 -03:00
Cauê Faleiros
593ddf82c8 feat: add a read-only Mercado Pago account probe
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 2m3s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 45s
Card payments with the test credentials are refused with 10111 and 10113,
which depend on the account behind the token. python -m
app.mercadopago_probe shows that account (and whether it is a test user),
the card methods it accepts, and how Mercado Pago classifies a card's first
digits: type, issuer and instalments. It creates and charges nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 13:47:39 -03:00
Cauê Faleiros
8b5aafa299 fix: let Mercado Pago take the card issuer from the card number
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 2m9s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 50s
Paying with Mercado Pago's own test card failed with 10111 ("the issuer
does not have the BIN configured"): the issuer_id suggested by the card
form did not match the card. issuer_id is optional, and without it Mercado
Pago resolves the issuer from the BIN.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 13:37:16 -03:00
Cauê Faleiros
e47f88a6d6 test: expect the 5 GB limit in the browser suite, and grade a large sheet from its header
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 2m16s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 51s
The artwork suite still asserted the old 128 MB refusal. It now refuses a
file above 5 GB and checks that a 3 GB sheet is graded from the pixel size
in its PNG header (300 DPI, 3 m) without being decoded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 13:31:21 -03:00
Cauê Faleiros
5f2be7ea20 feat: accept sheets of up to 5 GB end to end
Some checks failed
Build and deploy / Validate source (push) Successful in 12s
Build and deploy / Integration suite on a real stack (push) Failing after 2m36s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Has been skipped
Sheets of several GB are the normal order. The upload limit is now 5 GB.
ClamAV scans files up to 2 GB; a larger file is released only when its
first bytes match the format its name claims, and a disguised file is
refused. The Site grades a sheet over 150 MB from the pixel size in its
PNG, JPEG or WebP header without decoding it, and reads large PDFs in
ranges. The worker never opens a source over 300 MB: a finished sheet
placed whole becomes its own print file, which the Kanban offers to approve
as the final, and anything else goes to hand preparation. Files start
uploading as they enter the cart, with progress in the summary, and each
part renews the reservation so slow uploads do not expire. Quotas grow to
50 GB per customer and 500 GB in total; the Swarm config for ClamAV is
renamed because a deployed config cannot change in place.

Verified locally with a 386 MB and a 1.8 GB PNG (scanned, paid, original
as print file), a 2.3 GB PNG (format check) and a disguised 2.3 GB file
(refused).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 13:18:18 -03:00
Cauê Faleiros
4437232d27 fix: show why a card payment failed instead of leaving the form spinning
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 3m0s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 56s
When creating the card payment failed, the form's onSubmit rejected with no
message and Mercado Pago's button kept spinning. The page now shows the
reason above the form. A payment Mercado Pago refuses is logged with its
status, message and cause codes (payment_intent_refused) and answered 422
with that reason; other failures log their type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:58:56 -03:00
Cauê Faleiros
8bc57195e8 feat: open the customer's WhatsApp from the order panel
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 2m13s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 43s
The number in the Kanban's order panel is now a formatted wa.me link, so a
correction or a question about the artwork can be sent by hand in one
click.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:51:15 -03:00
Cauê Faleiros
0a575a3be7 fix: drop the repeated total from the PIX instructions
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 2m19s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 50s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:21:57 -03:00
Cauê Faleiros
15abd589a8 ci: download the vulnerability database once, and tell a failed scan from a finding
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 2m22s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 55s
The CRITICAL scan of dtf-api failed on a 404 from the database mirror and
was reported as a CRITICAL vulnerability. The image step now downloads the
database once into a cache volume, with three attempts, scans all four
times from it, and exits 5 only on findings: a scan that does not run fails
with its own message, and nothing is published unscanned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:10:58 -03:00
Cauê Faleiros
32c060e1b0 fix: hide the card form's own title on the payment page
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 2m39s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m50s
Mercado Pago's form titled both card options "Cartão de crédito ou débito";
the option above it already names the card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 11:04:37 -03:00
Cauê Faleiros
6f5d183365 fix: show the real freight status on the Kanban
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 2m16s
Build and deploy / Secret scan and release gate (push) Successful in 18s
Build and deploy / Publish images (push) Failing after 1m25s
The Integrations tab always said freight was not configured. It now reads
the server's adapter and, with Jadlog on, shows the package weight rule and
the production days the Site prices with.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 10:57:34 -03:00
Cauê Faleiros
2215da8d5e fix: centre the arrow in the upload box; record that CDR/AI/PSD stay manual
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 2m24s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m43s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 10:49:11 -03:00
Cauê Faleiros
88e65290e1 fix: quote freight on its own, and drop the Calcular button
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 2m20s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m46s
Going back to home delivery with a CEP already typed, or restoring a saved
cart, now quotes the freight again by itself; before, only pressing Calcular
did. With every case covered, the button is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 10:40:55 -03:00
Cauê Faleiros
690b15ece1 feat: fill the delivery address from the CEP and quote freight as it is typed
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 2m21s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m47s
A complete CEP now looks up its address on the server (ViaCEP, rate
limited, keeping the Site's CSP to its own origin) and fills street,
district, city and state, moving the cursor to the first field left, and
quotes the freight without pressing Calcular. The CEP keeps its mask when
the cart is restored. Freight and its delivery time appear in the order
summary instead of a line under the CEP, the delivery option says it ships
with Jadlog, and the address reminder is a hint rather than an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 10:31:41 -03:00
Cauê Faleiros
e20c8673bb fix: send the Jadlog account exactly as configured
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 2m19s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m33s
Jadlog issues the account as 000000-0 and documents a six-character field;
stripping the dash sent seven digits. The value now goes as typed, so the
accepted form can be found on the account without a new release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 10:00:44 -03:00
Cauê Faleiros
4de2151e9a feat: price home delivery with Jadlog
All checks were successful
Build and deploy / Validate source (push) Successful in 1m18s
Build and deploy / Integration suite on a real stack (push) Successful in 2m33s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m42s
FREIGHT_ADAPTER=jadlog prices "Receber em casa" through Jadlog's Simulador
de Frete from the order's billed metres and value, adding production days
to Jadlog's delivery time. The package weight is a base plus a weight per
metre from the client, with no default: the adapter refuses to start
without it and without the credentials. The cart re-quotes when the package
changes, and approval quotes again from the server-priced items. The
production stack takes the Jadlog settings, so the read-only probe runs
from the worker's console.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 09:34:01 -03:00
Cauê Faleiros
641aafc87d feat: PIX codes expire after 30 minutes, with a countdown
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 2m50s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m54s
A PIX is created with a 30-minute date_of_expiration, and the PIX page
counts down to it. When it runs out the page says the code expired and
offers a new one. The API keeps one open code per quote: the same code
until it expires, then exactly one new attempt (serialised per quote, with
its own idempotency key), the old one marked expired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 15:40:26 -03:00
Cauê Faleiros
875a7ef9c7 fix: drop the change-method button from the PIX page
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 2m10s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m37s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 14:18:18 -03:00
Cauê Faleiros
c436936fed fix: drop the confirmation-time promise from the PIX note
Some checks failed
Build and deploy / Integration suite on a real stack (push) Successful in 2m3s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Validate source (push) Successful in 6s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 14:15:08 -03:00
Cauê Faleiros
0ed6de4bd5 fix: shorten the PIX note on the payment page
Some checks failed
Build and deploy / Validate source (push) Successful in 8s
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 <noreply@anthropic.com>
2026-09-28 14:13:20 -03:00
Cauê Faleiros
eae3dad306 feat: offer credit card, debit card and PIX, with the bank's 3-D Secure step
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 2m3s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m31s
The payment page lists credit card (preselected), debit card and PIX. Each
card option limits Mercado Pago's form to its kind; debit is paid at once.
Card payments ask for 3-D Secure when the issuer requires it, and a
challenge opens the bank's page in a frame, which needs
PAYMENT_CHALLENGE_SOURCES=https: (frames and form posts only). A card left
waiting for that confirmation stops blocking a new attempt after ten
minutes, and a refusal reported by the notification returns the customer to
the payment choice. Written from the documentation; not yet run with a real
debit card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 13:24:06 -03:00
Cauê Faleiros
7b6675d4d4 feat: two-column payment page with card by default and PIX on its own page
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 2m19s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m38s
The payment page puts paying on the left and the order summary on the
right (above it on phones). Card is preselected and paid on the page with
Mercado Pago's form, in the Site's colours and with the order's e-mail;
choosing PIX shows a Pagar button that opens /pagamento/pix with the QR code
and copy-and-paste code, waiting there for the confirmation. A confirmed
payment shows "Pagamento confirmado" with the order number and a button to
the customer's orders. The payment buttons no longer restyle every button
inside the form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 13:10:05 -03:00
Cauê Faleiros
4df74221d2 fix: drop the validated-total line from the payment page
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 2m10s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m44s
The summary above already shows the total; the line stays only beside the
local stack's simulated payment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 12:15:00 -03:00
Cauê Faleiros
43043c361c feat: give payment its own page
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 2m12s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m35s
The PIX and card choices appeared under the cart, on the same page as the
customer's details. "Ir para o pagamento" now sends the order and opens
/pagamento, step 3 of the progress bar: the server's order summary, then PIX
or card, each opening below. The cart keeps only the sending progress and its
errors; a changed cart is sent again instead of offering the old quote.
Portal links open the payment page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 11:45:44 -03:00
Cauê Faleiros
536510b148 fix: version the Site's scripts by content so a release never meets a cached old one
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 2m9s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m44s
The proxy in front of production caches .js and .css for hours. After the
last release the Site got the new index.html with the old site-flow.js,
which wrote to an element the new page no longer has; the error left
"Adicionar ao carrinho" disabled. The web build now addresses every local
script and stylesheet by a hash of its content, replacing the hand-kept
?v= markers, so a new release always loads its own files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 11:27:55 -03:00
Cauê Faleiros
a1877bdf0a fix: remove the pickup and invoice notes from checkout; document R2 CORS
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 2m15s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m41s
The pickup notice under the delivery options and the invoice and retention
note under the purchase summary are gone. PORTAINER.md records the R2 CORS
policy the browser's direct uploads need: without it the preflight is
refused and checkout fails with a NetworkError before payment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 11:10:52 -03:00
Cauê Faleiros
275ebf72c4 feat: approve priced carts at checkout so customers can pay at once
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 2m22s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m34s
Every quote waited for an operator before it could be paid, so an order
placed at night waited for the morning. A cart the Site priced is now
approved when the quote is created, through the same server pricing the
operator's approval uses (app/quote_review.py). Orders above
QUOTE_AUTO_MAX_METRES (50 m) and items claiming a discount on art the Site
could not analyse still wait for review; the Kanban shows which quotes were
approved automatically and why the others wait.

The grade is still computed in the browser (roadmap 3.2, 3.9), so the
discount remains a customer-supplied value until the server computes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 11:02:56 -03:00
Cauê Faleiros
9bea187ea4 feat: add a read-only Jadlog price probe
All checks were successful
Build and deploy / Validate source (push) Successful in 1m20s
Build and deploy / Integration suite on a real stack (push) Successful in 2m49s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m51s
app/jadlog.py prices one package through Jadlog's Simulador de Frete as the
API manual v2.3 describes it; app.jadlog_probe prices test weights to six
regions on the client's account to confirm token, account and contract.
Tested against a fake transport. The roadmap records the Jadlog data and the
Mercado Pago account setup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 10:41:18 -03:00
Cauê Faleiros
bd56170248 feat: let production select Mercado Pago and acknowledge simulated notifications
The production compose hard-coded the fake payment adapter; it now takes
PAYMENT_ADAPTER and the MP_* settings from the stack's environment, so the
sandbox can run with test credentials. A signed notification about a payment
Mercado Pago does not have, such as the panel's "Simular notificação", is
acknowledged instead of answering 500 and being retried; any other lookup
failure still raises.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 10:41:18 -03:00
Cauê Faleiros
60b7336b37 docs: commit the operator guide's source and record the Week-2 report
The operator guide is now built from docs/guias/operador/ by
docs/guias/imprimir.sh, with the corrections on Tiny and the WhatsApp
notices. The roadmap records the guide, the history fix found while
writing it, and the Week-2 report as sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 10:07:58 -03:00
Cauê Faleiros
04e4cbc953 fix: hide operators' internal back-move reasons from the customer's order history
A move back undoes an operator's mistake and its reason is internal. The
customer's history now omits back moves and shows a reason only for a
correction; the smoke test checks both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 10:07:58 -03:00
Cauê Faleiros
aec5b1d054 feat: send order situações to Tiny for the client's WhatsApp notices
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 2m5s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m45s
The client already sends WhatsApp notices from Tiny's order situação
(Tiny webhook -> middleware -> n8n). With TINY_STATUS_UPDATES on, a paid
order is set to "Aprovada" once and a finished pickup order to "Pronto
para envio"; pickup orders carry the client's pickup forma de envio
(TINY_FORMA_ENVIO_RETIRADA). The ready event now carries the order and
the Tiny id from the sale's receipt. Off by default until go-live, when
n8n stops sending the DTFIMP designer message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 14:17:00 -03:00
Cauê Faleiros
8b42e684ca docs: record the Tiny account and product findings
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 2m46s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m46s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 13:40:28 -03:00
Cauê Faleiros
e768dcb489 feat: keep the Tiny connection alive and show when it is not
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 2m29s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m49s
Connecting now asks for offline_access, retrying once without it if Tiny
refuses the scope. Renewal failures are stored: a refused refresh token
marks the connection lost and is not sent again (the Kanban previously
still said "conectado"), a transient failure shows as a warning until the
next renewal, and a session grant with under 12 hours left is flagged.
Tiny errors on the callback return to the Kanban instead of a 422.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:04:23 -03:00
Cauê Faleiros
122c645f72 fix: stop Site timers from running after a product is closed
The grade check and the layout preview run on short timers. When the
item went to the cart inside that window, no product was open and both
threw in the customer's browser, which also failed the browser tests
intermittently. Each now returns when no product is open. The cart test
waits for the empty state, which is painted on the next animation frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:04:23 -03:00
Cauê Faleiros
988b252f9d feat: check Tiny products and add a supervised order test
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Integration suite on a real stack (push) Successful in 2m39s
Build and deploy / Publish images (push) Successful in 1m43s
"Testar conexão" now also reads the four configured Tiny products and
requires each to be active. app/tiny_probe.py runs from the worker console
to list products, confirm the configured ids, and create one marked test
order through the worker's own delivery path, proving the duplicate guard
by search before a second delivery. Nothing is sent without --confirmar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 10:23:07 -03:00
Cauê Faleiros
56021d8451 docs: add the operator and Site guides and bring the roadmap up to date
All checks were successful
Build and deploy / Validate source (push) Successful in 1m39s
Build and deploy / Integration suite on a real stack (push) Successful in 2m32s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m58s
The operator guide covers the Kanban flow from quote review to finished
order; the Site guide walks through the customer journey, prices and the
current state of each integration. The roadmap records the Kanban and Site
redesigns, the guides, and what is left for the last day of Week 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 09:07:50 -03:00
Cauê Faleiros
b6a90411f1 feat: let customers remove items and empty the cart, with undo
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 2m2s
Build and deploy / Secret scan and release gate (push) Successful in 4s
Build and deploy / Publish images (push) Successful in 1m33s
Each cart item has a visible "Remover" button instead of a faint ×, and
carts with two or more items get "Esvaziar carrinho". Both show a
"Desfazer" notice for 8 seconds, so a wrong click costs nothing. The
browser test covers remove and undo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 18:18:10 -03:00
Cauê Faleiros
cbbbdb351a feat: rebuild the Site product page around a buy box
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 2m46s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m46s
Artworks on the left; on the right a box that stays in view with the live
sheet, the grade, the price per metre, the metres charged, the total, the
resolution note and "Adicionar ao carrinho". The separate quality and
preview panels, the second sheet preview, the per-row mini sheets, the
summary box and the repeated findings list are gone: each piece of
information now appears once.

Each artwork row carries at most one hint (resolution first, otherwise a
width that saves film), the ready-sheet/loose-artwork choice is a toggle
beside the title, the upload area is one bar and the tips are collapsed.
The box only shows the item the page already priced, so it always matches
the cart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 18:02:45 -03:00
Cauê Faleiros
b81ff8d03d feat: give each Site product and the cart its own page
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 2m28s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m52s
The home, each product's Montagem and the cart now have their own
addresses (/artes-avulsas, /arquivo-por-metro, /uv-artes-avulsas,
/uv-arquivo-por-metro, /carrinho) and show only their own content, with
Back, Forward, reload and direct links working as in any store. They stay
one document so uploaded artworks survive moving between pages; nginx
serves index.html for these addresses.

"Adicionar ao carrinho" puts the item in the cart and opens it, and an
empty cart says so. Portal quote links open in the cart. Also fixes the
"57 cm" line break on the ready-sheet option, returns "Novo pedido" to
the home, and says PDF depends on the product.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 16:56:58 -03:00
Cauê Faleiros
177882e77b feat: redesign the Site order flow and fix the cart layout
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 2m23s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m48s
New landing (hero with a sheet preview, four steps, product cards priced
from the checkout table, price table and benefits), a progress bar that
follows the order through Montagem, Dados e entrega and Pagamento, the
live sheet beside the artworks, and a running total bar on phones.

The cart's saved-in-browser note no longer takes a grid column, which had
pushed the order into a narrow strip and the summary below it. The
previous look is kept in tag ui-v1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 16:33:06 -03:00
Cauê Faleiros
2e03b0362b feat: undo mistaken moves, numbered pagination, and quieter Kanban messages
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 2m33s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m48s
Moves: an order can go back one stage (BACK in app/runtime.py) with an
internal reason, flagged in the history as movements.back. The customer is
not notified and approved finals stay; "production started" and "ready" are
now enqueued once per order, so undoing and redoing a move sends nothing
twice. Dragging only goes forward and highlights the allowed column. Move
errors are in Portuguese.

Lists: the send log, payments (open, resolved as history, all) and quotes
are paged on the server with a total, 20 rows by default (10/20/50/100),
first/previous/page/next/last. The send log filters by destination, status,
event and order. Older finished orders load on demand. The board no longer
carries the send log or payment rows, only the open-payment count.

Kanban: Pagamentos and Integrações are separate tabs; messages are brief,
bottom notifications that clear themselves; wording is shorter.

Full CI integration sequence passes locally, with new checks for undo, paging
and filters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 16:01:31 -03:00
Cauê Faleiros
99a558ddd9 feat: redesign the Kanban and keep test wording out of production
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 3m3s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m51s
Kanban: tabs for production, quote review and payments/integrations; compact
cards with products, metres, print-file status, delivery and time in stage;
an order panel with stage progress, one main action, a correction reason in
place, items with a preview drawn from the approved layout, final-file
approval and the history as a timeline. Quote review gets a list and a pane;
payment issues resolve in place; integrations show their real state, Tiny's
connection with a read-only "Testar conexão", and a readable send log. The
previous Kanban is kept in git tag ui-v1 and is no longer served.

Production wording: the customer portal no longer says it is a local test
environment outside the local stack; the checkout no longer tells customers
to use the Kanban or shows internal stage codes; sign-in, session, quota and
print-file messages are Portuguese and never say "local". A simulated freight
price is refused outside the local stack until a real freight provider
exists, so production only offers pickup.

The browser suite drives the new tabs and panel and still checks the whole
upload, quote, payment and production journey. Full CI sequence passes locally.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:28:04 -03:00
284 changed files with 40208 additions and 2752 deletions

View File

@@ -14,3 +14,14 @@ staging/staging.env
deploy/portainer.env
portal
kanban
# Local test files in the repository root, kept out of every build context:
# pasta-teste-download alone is 1.5 GB and made each image build wait on it.
pasta-teste-download
pasta-teste-3-pasta
pasta-3-teste-producao
manifesto-pedido-1
imagens-teste
teste-4m
/*.png
/*.cdr
/dtf-site*.html

View File

@@ -18,6 +18,8 @@ OPERATOR_EMAIL=operator@example.test
OPERATOR_PASSWORD=local-operator-only
APP_ENV=local
PAYMENT_ADAPTER=fake
# Designer treatment, fixed per order in cents; 0 hides the option.
TREATMENT_CENTS=0
FREIGHT_ADAPTER=fake
TINY_ADAPTER=fake
# Sandbox only (see docs/LOCAL_SETUP.md, "Provider sandboxes"):
@@ -37,13 +39,25 @@ TINY_ADAPTER=fake
# TINY_PRODUCT_UV_FOLHA=...
# TINY_PRODUCT_UV_AVULSA=...
# TINY_ADAPTER=tiny # only once connected and tested: creates real orders
WHATSAPP_ADAPTER=fake
# Jadlog price quotes go in jadlog.env, not here (see app/jadlog_probe.py):
# JADLOG_TOKEN=...
# JADLOG_CNPJ=... # the "Usuário" Jadlog issued, the CNPJ that contracts freight
# JADLOG_CONTA=... # conta corrente
# JADLOG_CONTRATO= # only if Jadlog issued a contract number
# E-mail stays in the database and the worker log (MAIL_ADAPTER=log). To send
# through a real server: MAIL_ADAPTER=smtp with the settings below.
# MAIL_FROM=DTF Dropstar <nao-responda@exemplo.com.br>
# SMTP_HOST=smtp.exemplo.com.br
# SMTP_PORT=587
# SMTP_SECURITY=starttls
# SMTP_USER=...
# SMTP_PASSWORD=...
STORAGE_ADAPTER=s3-local
MOCK_FREIGHT_CENTS=1500
MAX_UPLOAD_BYTES=5368709120
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,13 +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:
@@ -66,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
@@ -73,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 quote_pagination_test print_file_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 \
@@ -86,13 +101,14 @@ 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_mercadopago tests.test_tiny -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: |
$COMPOSE exec -T api python -m tests.retention_test
$COMPOSE exec -T api python -m tests.runtime_security_test
$COMPOSE exec -T api python -m tests.tiny_oauth_test
$COMPOSE exec -T backup python -m tests.backup_test
# Run Chrome on the Compose network. It must resolve the same storage:9000
# hostname used in presigned URLs, and absence of Chrome must fail CI.
@@ -106,7 +122,7 @@ jobs:
if: failure()
run: |
$COMPOSE ps || true
$COMPOSE logs --tail 200 api worker site kanban || true
$COMPOSE logs --tail 200 api worker backup site kanban || true
- name: Tear down
if: always()
@@ -188,7 +204,7 @@ jobs:
set --
[ -n "$PYTHON_BASE_IMAGE" ] && set -- --build-arg PYTHON_BASE_IMAGE="$PYTHON_BASE_IMAGE"
docker build --file deploy/Dockerfile.api "$@" \
--build-arg VCS_REF="${{ gitea.sha }}" \
--build-arg VCS_REF="${{ gitea.sha }}" --build-arg PACKAGES_DAY="$(date -u +%F)" \
--tag "$image:latest" --tag "$image:${{ gitea.sha }}" .
- name: Build web
run: |
@@ -197,7 +213,7 @@ jobs:
[ -n "$PYTHON_BASE_IMAGE" ] && set -- --build-arg PYTHON_BASE_IMAGE="$PYTHON_BASE_IMAGE"
[ -n "$NGINX_BASE_IMAGE" ] && set -- "$@" --build-arg NGINX_BASE_IMAGE="$NGINX_BASE_IMAGE"
docker build --file deploy/Dockerfile.web "$@" \
--build-arg VCS_REF="${{ gitea.sha }}" \
--build-arg VCS_REF="${{ gitea.sha }}" --build-arg PACKAGES_DAY="$(date -u +%F)" \
--tag "$image:latest" --tag "$image:${{ gitea.sha }}" .
# CRITICAL blocks, HIGH is reported. Both images carry zero CRITICAL after
# the base pinning and OS upgrades, so this gate holds the line already
@@ -206,24 +222,47 @@ jobs:
- name: Image vulnerabilities
run: |
image="${TRIVY_IMAGE:-aquasec/trivy:0.58.1}"
failed=0
# One database download for the four scans, kept in a volume between
# runs and retried: a failed download from the mirror used to fail
# the gate as if a CRITICAL vulnerability had been found.
trivy() { docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \
-v dtf-trivy-cache:/root/.cache/trivy "$image" "$@"; }
for attempt in 1 2 3; do
trivy image --download-db-only --no-progress && break
if [ "$attempt" -eq 3 ]; then
echo "::error::The vulnerability database could not be downloaded; the release images were not scanned."
exit 1
fi
echo "Database download failed (attempt $attempt); retrying in 30 s."
sleep 30
done
# Findings exit 5; any other failure means the scan did not run.
found=0; broken=0
for target in \
"gitea.blyzer.com.br/blyzer/dtf-api:${{ gitea.sha }}" \
"gitea.blyzer.com.br/blyzer/dtf-web:${{ gitea.sha }}"; do
echo "--- $target (HIGH, reported)"
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock "$image" \
image --image-src docker --scanners vuln --severity HIGH --no-progress \
trivy image --skip-db-update --image-src docker --scanners vuln --severity HIGH --no-progress \
--format table --exit-code 0 "$target" ||
echo "::warning::Could not scan $target for HIGH findings"
echo "--- $target (CRITICAL, blocking)"
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock "$image" \
image --image-src docker --scanners vuln --severity CRITICAL --no-progress \
--format table --exit-code 1 "$target" || failed=1
set +e
trivy image --skip-db-update --image-src docker --scanners vuln --severity CRITICAL --no-progress \
--format table --exit-code 5 "$target"
verdict=$?
set -e
if [ "$verdict" -eq 5 ]; then found=1
elif [ "$verdict" -ne 0 ]; then broken=1; echo "::error::The CRITICAL scan of $target did not run (exit $verdict)."
fi
done
if [ "$failed" -ne 0 ]; then
if [ "$found" -ne 0 ]; then
echo "::error::A CRITICAL vulnerability was found in a release image."
exit 1
fi
if [ "$broken" -ne 0 ]; then
echo "::error::A release image could not be scanned; nothing is published unscanned."
exit 1
fi
- name: Publish validated images
run: |

View File

@@ -12,14 +12,25 @@ from botocore.exceptions import ClientError
def require_runtime():
"""Validate the supported local and R2-backed deployment modes.
Real payment, freight, ERP, and WhatsApp providers are deliberately not
enabled yet. A non-local deployment keeps those adapters fake and disables
checkout until their audited implementations are added.
Each provider is fake until its settings are complete; a real one refuses
to start without them.
"""
environment = os.environ.get('APP_ENV', 'local')
for name in ('FREIGHT', 'WHATSAPP'):
if os.environ.get(f'{name}_ADAPTER') != 'fake':
raise RuntimeError(f'{name} must use the currently supported fake adapter')
freight = os.environ.get('FREIGHT_ADAPTER')
if freight == 'jadlog':
from .jadlog import required_settings as jadlog_settings
for name in jadlog_settings():
if not os.environ.get(name):
raise RuntimeError(f'{name} is required for the Jadlog adapter')
elif freight != 'fake':
raise RuntimeError('FREIGHT must use the fake or jadlog adapter')
# Correios is on when its access code is set; it prices the same package.
if os.environ.get('CORREIOS_CODIGO_ACESSO', '').strip():
from .correios import required_settings as correios_settings
from .package import WEIGHT_SETTINGS
for name in (*correios_settings(), *WEIGHT_SETTINGS, 'JADLOG_CAIXA_CM'):
if not os.environ.get(name):
raise RuntimeError(f'{name} is required for Correios freight')
tiny = os.environ.get('TINY_ADAPTER')
if tiny == 'tiny':
from .tiny import required_settings
@@ -37,6 +48,16 @@ def require_runtime():
raise RuntimeError(f'{name} is required for the Mercado Pago adapter')
elif payment != 'fake':
raise RuntimeError('PAYMENT must use the fake or mercadopago adapter')
mail = os.environ.get('MAIL_ADAPTER', 'off')
if mail == 'smtp':
from .mail import required_settings as mail_settings
for name in mail_settings():
if not os.environ.get(name):
raise RuntimeError(f'{name} is required for e-mail by SMTP')
if os.environ.get('SMTP_SECURITY', 'starttls') not in ('starttls', 'ssl', 'none'):
raise RuntimeError('SMTP_SECURITY must be starttls, ssl or none')
elif mail not in ('off', 'log'):
raise RuntimeError('MAIL_ADAPTER must be off, log or smtp')
if environment == 'local':
if os.environ.get('STORAGE_ADAPTER') != 's3-local':
raise RuntimeError('Local runtime requires local S3 storage')
@@ -106,6 +127,11 @@ class FakePayment:
def create(self, quote_id: str, total_cents: int, customer: dict, method: dict | None = None) -> dict:
kind = (method or {}).get('type', 'pix')
if kind == 'pix':
from datetime import datetime, timedelta, timezone
expires = (datetime.now(timezone.utc) + timedelta(minutes=30)).isoformat(timespec='milliseconds')
return {'provider': 'fake', 'id': f"local-{quote_id}-pix-{(method or {}).get('attempt', 1)}",
'status': 'pending', 'total_cents': total_cents, 'expires_at': expires}
return {'provider': 'fake', 'id': f'local-{quote_id}-{kind}',
'status': 'pending', 'total_cents': total_cents}
@@ -143,10 +169,13 @@ class FakePayment:
'status': 'paid', 'total_cents': total_cents}
class FreightAdapter(Protocol):
def quote(self, service: str, postal_code: str) -> dict: ...
def quote(self, service: str, postal_code: str, metres=None, declared_cents: int = 0) -> dict: ...
class FakeFreight:
def quote(self, service: str, postal_code: str) -> dict:
name = 'fake'
services = {'mock-standard': 'Entrega simulada'}
def quote(self, service: str, postal_code: str, metres=None, declared_cents: int = 0) -> dict:
if service == 'pickup':
return {'provider': 'fake', 'service': 'pickup', 'total_cents': 0, 'postal_code': ''}
if service != 'mock-standard' or len(postal_code) != 8 or not postal_code.isascii() or not postal_code.isdigit():
@@ -155,20 +184,47 @@ class FakeFreight:
if cents < 0:
raise ValueError('Invalid mock freight configuration')
return {'provider': 'fake', 'service': service, 'postal_code': postal_code,
'total_cents': cents, 'description': 'Local simulated freight'}
'total_cents': cents, 'description': 'Entrega simulada'}
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'}
class FakeWhatsApp:
def deliver(self, event_key: str, payload: dict) -> dict:
return {'provider': 'fake-whatsapp', 'event_key': event_key,
'event': payload['event'], '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: ...
@@ -181,6 +237,8 @@ class ObjectStorage(Protocol):
def store(self, key: str, path: str, content_type: str): ...
def health(self): ...
def discard(self, key: str, upload_id: str, complete: bool): ...
def discard_prefix(self, prefix: str): ...
def view(self, key: str, content_type: str, expires: int = 3600) -> str: ...
class LocalS3Storage:
def __init__(self):
@@ -188,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):
@@ -198,7 +262,7 @@ class LocalS3Storage:
raise
self.client.create_bucket(Bucket=self.bucket)
self.client.put_bucket_lifecycle_configuration(Bucket=self.bucket, LifecycleConfiguration={
'Rules': [{'ID': 'local-artwork-retention', 'Status': 'Enabled', 'Filter': {'Prefix': ''},
'Rules': [{'ID': 'local-artwork-retention', 'Status': 'Enabled', 'Filter': {'Prefix': 'originals/'},
'Expiration': {'Days': 30}, 'AbortIncompleteMultipartUpload': {'DaysAfterInitiation': 1}}]})
def health(self):
@@ -229,11 +293,11 @@ 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):
from urllib.parse import quote
@@ -242,6 +306,25 @@ class LocalS3Storage:
'ResponseContentDisposition': "attachment; filename*=UTF-8''" + quote(name, safe=''),
'ResponseContentType': 'application/octet-stream'}, ExpiresIn=300)
def view(self, key, content_type, expires=3600):
"""A link to show an object in the page, not download it: the Kanban's
viewer reads a film's pieces for as long as it is open (item 7)."""
return self.public.generate_presigned_url('get_object', Params={
'Bucket': self.bucket, 'Key': key, 'ResponseContentType': content_type}, ExpiresIn=expires)
def discard_prefix(self, prefix):
"""Delete every object under `prefix`, such as a print file's pieces."""
token = None
while True:
page = self.client.list_objects_v2(Bucket=self.bucket, Prefix=prefix,
**({'ContinuationToken': token} if token else {}))
keys = [{'Key': item['Key']} for item in page.get('Contents', [])]
if keys:
self.client.delete_objects(Bucket=self.bucket, Delete={'Objects': keys, 'Quiet': True})
if not page.get('IsTruncated'):
return
token = page['NextContinuationToken']
def discard(self, key, upload_id, complete):
if not complete:
try:

View File

@@ -6,38 +6,49 @@ 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 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()
@router.post('/api/operator/orders/{oid}/uploads')
def begin_final(oid: UUID, body: UploadStart, user=Depends(operator)):
def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
if not body.name.lower().endswith('.png'):
raise HTTPException(422, 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.')
with db.connect() as c:
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
row = c.execute('SELECT id,state,parent_id,proof_ok_at FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
if not row: raise HTTPException(404, 'Order not found')
if row['state'] not in ('rec','tra','cor'): raise HTTPException(409, 'Order is not in artwork review')
if row['parent_id']:
raise HTTPException(409, 'A prova recebe o PNG final automaticamente.')
if not proof.manual_source_needed(c, row):
proof.require_unlocked(c, row)
if row['state'] not in ('rec','cor'): raise HTTPException(409, 'Order is not in artwork review')
return begin_upload(body, session_id=operator_identity(user))
@router.get('/api/operator/uploads/{uid}')
def final_status(uid: UUID, user=Depends(operator)):
return upload_status(uid,session_id=operator_identity(user))
# 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(operator)):
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(operator)):
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(operator)):
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')
@@ -45,9 +56,42 @@ 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(operator)):
def final_files(oid: UUID, body: ArtworkSubmission, user=Depends(can('produce'))):
with db.connect() as c:
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (oid,)).fetchone()
if not order: raise HTTPException(404, 'Order not found')
if order['parent_id']:
raise HTTPException(409, 'O arquivo final da prova é gerado automaticamente. Use Gerar de novo se falhar.')
if not proof.manual_source_needed(c, order):
proof.require_unlocked(c, order)
return submit_files(c,order,body,operator_identity(user),'final',user)

View File

@@ -1,17 +1,23 @@
"""Customer accounts, their orders, and the corrections they submit."""
import hashlib
import secrets
from datetime import datetime, timedelta, timezone
from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from typing import Literal
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from psycopg.errors import UniqueViolation
from psycopg.types.json import Jsonb
from ..core import db
from ..artwork import submit_files
from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner,
login_failed, password_hash, password_matches, session_row, throttle, transfer_guest)
from ..core.models import ArtworkSubmission, Login, Register
from ..runtime import STATES, file_rows, owned_order, storage
from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner, login_failed, password_hash,
password_matches, rate_limit, session_row, throttle, transfer_guest)
from ..core.models import (ArtworkSubmission, EmailChange, EmailCode, EmailResend, ForgotPassword, Login,
PasswordChange, PasswordReset, ProfileUpdate, Register, SignupCode, SignupResend)
from .. import mail, mail_html
from ..runtime import ENVIRONMENT, PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage
from ..scanning import require_clean
router = APIRouter()
@@ -22,6 +28,87 @@ def current(request):
except HTTPException: return None
# Signup: with e-mail on, the account exists only once the code sent to the
# address is entered, so nobody opens an account on someone else's e-mail. The
# answer is the same whether or not the address already has an account: that
# address gets a notice to sign in instead of a code, and no code works.
CODE_ATTEMPTS = 5
CODE_SENDS = 5
RESEND_SECONDS = 60
def signup_code(c, signup_id, email, name):
"""A fresh code for a signup (or the notice for an address that already has
an account, greeting that account's owner), queued by e-mail. Returns the
code's hash, None for the notice."""
existing = c.execute('SELECT profile FROM dtf_local.accounts WHERE email=%s', (email,)).fetchone()
if existing:
owner = existing['profile'].get('name')
login = f'{PUBLIC_ORIGIN}/conta/entrar'
mail.queue(c, 'account', email, 'Você já tem conta · DTF Dropstar',
f'{mail_html.greeting(owner)}\n\nAlguém tentou criar uma conta no DTF Dropstar com este e-mail, '
'mas ele já tem conta.\n\n'
f'Para entrar: {login}\n'
'Esqueceu a senha? Na mesma página, clique em “Esqueci minha senha”.\n\n'
'Se não foi você, ignore este e-mail: nada muda na sua conta.',
mail_html.account_exists(owner, login))
return None
return send_code(c, signup_id, email, 'signup', name)
# What a code is for: the text, the e-mail's heading, and what stays the same
# if it was not the customer who asked.
CODE_PURPOSES = {
'signup': ('criar a sua conta no DTF Dropstar', 'Confirme seu e-mail', 'nenhuma conta é criada sem ele.'),
'email': ('trocar o e-mail da sua conta no DTF Dropstar', 'Confirme seu novo e-mail',
'o e-mail da conta continua o mesmo.'),
}
def send_code(c, key, email, purpose, name=''):
"""A fresh 6-digit code by e-mail for `purpose` (CODE_PURPOSES); returns its hash."""
text, heading, unchanged = CODE_PURPOSES[purpose]
code = f'{secrets.randbelow(10 ** 6):06d}'
mail.queue(c, 'code', email, f'{code} é o seu código · DTF Dropstar',
f'{mail_html.greeting(name)}\n\nO seu código para {text} é:\n\n{code}\n\n'
f'Ele vale por {mail.CODE_MINUTES} minutos. Se não foi você, ignore este e-mail: {unchanged}',
mail_html.code(name, heading, text, code, mail.CODE_MINUTES, unchanged))
return code_digest(key, code)
def checked_code(c, table, key, code, request, extra=''):
"""The pending row a code confirms, locked, or the refusal to raise. A wrong
code counts against the row; the caller raises after its block commits."""
row = c.execute(f'SELECT * FROM dtf_local.{table} WHERE id=%s AND done_at IS NULL {extra} FOR UPDATE',
key).fetchone()
if not row or row['expires_at'] <= datetime.now(timezone.utc):
return None, HTTPException(410, 'Este código venceu. Clique em “Reenviar código”.')
if row['attempts'] >= CODE_ATTEMPTS:
return None, HTTPException(429, 'Muitas tentativas com este código. Clique em “Reenviar código”.')
if row['code_hash'] and secrets.compare_digest(row['code_hash'], code_digest(row['id'], code)):
c.execute(f'UPDATE dtf_local.{table} SET done_at=now() WHERE id=%s', (row['id'],))
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), 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”.'))
def resend_wait(row):
"""Why another code cannot go yet, or None."""
wait = RESEND_SECONDS - (datetime.now(timezone.utc) - row['sent_at']).total_seconds()
if wait > 0:
return HTTPException(429, f'Aguarde {int(wait) + 1} s para pedir outro código.')
if row['sends'] >= CODE_SENDS:
return HTTPException(429, 'Limite de códigos atingido. Comece de novo em alguns minutos.')
return None
def code_digest(signup_id, code):
return hashlib.sha256(f'{signup_id}:{code}'.encode()).hexdigest()
@router.post('/api/account/register')
def register(body: Register, request: Request, response: Response):
email = body.customer.mail.strip().lower()
@@ -29,22 +116,109 @@ def register(body: Register, request: Request, response: Response):
# Registration attempts keep counting against the email, as before.
login_failed(email)
previous = current(request)
encoded = password_hash(body.password)
identity = uuid4()
profile = body.customer.model_dump()
profile['mail'] = email
with db.connect() as c:
if previous and c.execute('SELECT id FROM dtf_local.accounts WHERE id=%s', (previous['owner'],)).fetchone():
raise HTTPException(409, 'Saia da conta atual antes de criar outra.')
if mail.configured():
rate_limit('signup-account', email, CODE_SENDS, 3600)
signup_id = uuid4()
with db.connect() as c:
digest = signup_code(c, signup_id, email, profile.get('name'))
c.execute('''INSERT INTO dtf_local.account_signups(id,email,profile,password_hash,code_hash,expires_at)
VALUES(%s,%s,%s,%s,%s,now() + %s * interval '1 minute')''',
(signup_id, email, Jsonb(profile), password_hash(body.password), digest, mail.CODE_MINUTES))
audit('account_signup_started', ip=client_ip(request))
return {'verify': str(signup_id), 'email': email, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
# Without e-mail there is no code to send: the account is created at once.
return create_account(profile=profile, password=password_hash(body.password), previous=previous, response=response)
def claim_orders(c, identity, profile):
"""Orders bought without an account with this account's CPF/CNPJ and
e-mail, from any browser. Only for an e-mail confirmed with a code: a
CPF or CNPJ alone, which others may know, never brings anyone's orders.
Each order comes with its cart and the customer's files."""
document = ''.join(ch for ch in str(profile.get('cnpj') or '') if ch.isdigit())
if not document:
return 0
orders = c.execute('''SELECT o.id,o.owner,o.quote_id,o.snapshot FROM dtf_local.orders o
WHERE o.owner<>%s AND NOT EXISTS (SELECT 1 FROM dtf_local.accounts a WHERE a.id=o.owner)
AND regexp_replace(coalesce(o.snapshot->'customer'->>'cnpj',''),'\\D','','g')=%s
AND lower(trim(o.snapshot->'customer'->>'mail'))=%s
FOR UPDATE''', (identity, document, profile['mail'].strip().lower())).fetchall()
for order in orders:
uploads = [uid for item in order['snapshot'].get('items') or [] for uid in item.get('uploads') or []]
uploads += [row['upload_id'] for row in c.execute(
'SELECT upload_id FROM dtf_local.order_files WHERE order_id=%s', (order['id'],)).fetchall()]
c.execute('UPDATE dtf_local.orders SET owner=%s WHERE id=%s', (identity, order['id']))
c.execute('UPDATE dtf_local.quotes SET owner=%s WHERE id=%s AND owner=%s', (identity, order['quote_id'], order['owner']))
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), c=c)
return len(orders)
def create_account(profile, password, previous, response, verified=False):
identity = uuid4()
try:
with db.connect() as c:
if previous and c.execute('SELECT id FROM dtf_local.accounts WHERE id=%s', (previous['owner'],)).fetchone():
raise HTTPException(409, 'Sign out before registering another account')
c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile) VALUES(%s,%s,%s,%s)', (identity,email,encoded,Jsonb(profile)))
c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile,email_verified) VALUES(%s,%s,%s,%s,%s)',
(identity, profile['mail'], password, Jsonb(profile), verified))
if previous: transfer_guest(c, previous, identity)
if verified: claim_orders(c, identity, profile)
new_session(c, response, identity)
except UniqueViolation:
raise HTTPException(409, 'An account already exists; sign in')
raise HTTPException(409, 'Já existe uma conta com este e-mail. Entre com a sua senha.')
audit('account_registered', account=str(identity))
return {'customer': profile}
@router.post('/api/account/register/verify')
def register_verify(body: SignupCode, request: Request, response: Response):
rate_limit('code-verify', client_ip(request), 30)
with db.connect() as c:
signup, refusal = checked_code(c, 'account_signups', (body.signup,), body.code, request)
# Raised outside the block, so a wrong attempt is counted, not rolled back.
if refusal:
raise refusal
return create_account(profile=signup['profile'], password=signup['password_hash'],
previous=current(request), response=response, verified=True)
@router.get('/api/account/register/dev-code')
def register_dev_code(signup: UUID):
"""The local stack's last code for a signup, for the browser test, which
cannot read the database. Only where e-mail stays in the log; elsewhere
the code exists only in the customer's inbox."""
if ENVIRONMENT != 'local' or mail.ADAPTER != 'log':
raise HTTPException(404, 'Not found')
with db.connect() as c:
row = c.execute('''SELECT m.body FROM dtf_local.account_signups s JOIN dtf_local.mail_queue m
ON m.to_addr=s.email AND m.kind='code' WHERE s.id=%s ORDER BY m.id DESC LIMIT 1''', (signup,)).fetchone()
if not row:
raise HTTPException(404, 'Not found')
return {'code': next(word for word in row['body'].split() if word.isdigit() and len(word) == 6)}
@router.post('/api/account/register/resend')
def register_resend(body: SignupResend, request: Request):
rate_limit('code-verify', client_ip(request), 30)
with db.connect() as c:
signup = c.execute('SELECT * FROM dtf_local.account_signups WHERE id=%s AND done_at IS NULL FOR UPDATE',
(body.signup,)).fetchone()
if not signup:
raise HTTPException(410, 'Este cadastro venceu. Preencha os dados de novo.')
if refusal := resend_wait(signup):
raise refusal
digest = signup_code(c, signup['id'], signup['email'], signup['profile'].get('name'))
c.execute('''UPDATE dtf_local.account_signups SET code_hash=%s, attempts=0, sends=sends+1, sent_at=now(),
expires_at=now() + %s * interval '1 minute' WHERE id=%s''', (digest, mail.CODE_MINUTES, signup['id']))
audit('account_signup_code_resent', ip=client_ip(request))
return {'ok': True, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
@router.post('/api/account/login')
def login(body: Login, request: Request, response: Response):
email = body.email.strip().lower()
@@ -57,7 +231,7 @@ def login(body: Login, request: Request, response: Response):
if not account or not matches:
login_failed(email)
audit('customer_login_failed', ip=client_ip(request))
raise HTTPException(401, 'Invalid email or password')
raise HTTPException(401, 'E-mail ou senha inválidos.')
previous = current(request)
with db.connect() as c:
if not stored.startswith('scrypt-v2$'):
@@ -65,6 +239,9 @@ def login(body: Login, request: Request, response: Response):
if previous:
transfer_guest(c, previous, account['id'])
c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['id'],))
# Orders bought without the account since, on any device.
if account['email_verified']:
claim_orders(c, account['id'], account['profile'])
new_session(c, response, account['id'])
audit('customer_login_success', account=str(account['id']))
return {'customer': account['profile']}
@@ -86,21 +263,256 @@ def me(identity=Depends(owner)):
row = c.execute('SELECT profile FROM dtf_local.accounts WHERE id=%s', (identity,)).fetchone()
return {'customer': row['profile'] if row else None}
@router.get('/api/customer/orders')
def orders(identity=Depends(owner)):
def account_row(c, identity, lock=False):
row = c.execute('SELECT * FROM dtf_local.accounts WHERE id=%s' + (' FOR UPDATE' if lock else ''), (identity,)).fetchone()
if not row:
raise HTTPException(401, 'Entre na sua conta.')
return row
@router.post('/api/account/profile')
def update_profile(body: ProfileUpdate, identity=Depends(owner)):
"""Name, WhatsApp and the saved delivery address. The CPF or CNPJ is the account's and
does not change; the e-mail is the login and changes on its own route."""
with db.connect() as c:
rows = c.execute('SELECT id,number,state,version,snapshot,created_at,updated_at FROM dtf_local.orders WHERE owner=%s ORDER BY created_at DESC', (identity,)).fetchall()
quotes = c.execute('''SELECT q.id,q.approved,q.approved_at,q.created_at FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id WHERE q.owner=%s AND o.id IS NULL ORDER BY q.created_at DESC''', (identity,)).fetchall()
return {'orders': rows, 'quotes': quotes, 'states': STATES}
row = account_row(c, identity, lock=True)
profile = {**row['profile'], 'zap': body.zap,
'address': body.address.model_dump() if body.address else None}
if body.name is not None:
profile['name'] = body.name
c.execute('UPDATE dtf_local.accounts SET profile=%s WHERE id=%s', (Jsonb(profile), identity))
audit('account_profile_updated', account=str(identity))
return {'customer': profile}
@router.post('/api/account/email')
def change_email(body: EmailChange, request: Request, identity=Depends(owner)):
with db.connect() as c:
row = account_row(c, identity)
throttle(row['email'], request)
if not password_matches(body.password, row['password_hash']):
login_failed(row['email'])
raise HTTPException(401, 'Senha incorreta.')
if body.email == row['email']:
raise HTTPException(422, 'Este já é o e-mail da sua conta.')
if not mail.configured():
return apply_email(identity, row, body.email)
# With e-mail on, the change waits for the code sent to the new address.
rate_limit('email-change', str(identity), CODE_SENDS, 3600)
change = uuid4()
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (body.email,)).fetchone():
raise HTTPException(409, 'Este e-mail já é de outra conta.')
digest = send_code(c, change, body.email, 'email', row['profile'].get('name'))
c.execute('''INSERT INTO dtf_local.email_changes(id,account_id,new_email,code_hash,expires_at)
VALUES(%s,%s,%s,%s,now() + %s * interval '1 minute')''', (change, identity, body.email, digest, mail.CODE_MINUTES))
audit('account_email_change_started', account=str(identity))
return {'verify': str(change), 'email': body.email, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
def apply_email(identity, row, email):
"""Switch the account to the new e-mail and tell the old address."""
profile = {**row['profile'], 'mail': email}
try:
with db.connect() as c:
c.execute('UPDATE dtf_local.accounts SET email=%s, profile=%s, email_verified=true WHERE id=%s',
(email, Jsonb(profile), identity))
claim_orders(c, identity, profile)
name = row['profile'].get('name')
mail.queue(c, 'notice', row['email'], 'O e-mail da sua conta foi trocado · DTF Dropstar',
f'{mail_html.greeting(name)}\n\nO e-mail da sua conta no DTF Dropstar foi trocado para {email}. '
'A partir de agora, entre com ele.\n\n'
'Se não foi você, fale com a Dropstar pelo WhatsApp 16 99428-0056.',
mail_html.email_changed(name, row['email'], email))
except UniqueViolation:
raise HTTPException(409, 'Este e-mail já é de outra conta.')
audit('account_email_changed', account=str(identity))
return {'customer': profile}
@router.post('/api/account/email/verify')
def change_email_verify(body: EmailCode, request: Request, identity=Depends(owner)):
rate_limit('code-verify', client_ip(request), 30)
with db.connect() as c:
change, refusal = checked_code(c, 'email_changes', (body.change, identity), body.code, request,
extra='AND account_id=%s')
row = account_row(c, identity) if change else None
if refusal:
raise refusal
return apply_email(identity, row, change['new_email'])
@router.post('/api/account/email/resend')
def change_email_resend(body: EmailResend, request: Request, identity=Depends(owner)):
rate_limit('code-verify', client_ip(request), 30)
with db.connect() as c:
change = c.execute('''SELECT * FROM dtf_local.email_changes WHERE id=%s AND account_id=%s AND done_at IS NULL
FOR UPDATE''', (body.change, identity)).fetchone()
if not change:
raise HTTPException(410, 'Esta troca venceu. Comece de novo.')
if refusal := resend_wait(change):
raise refusal
name = c.execute('SELECT profile FROM dtf_local.accounts WHERE id=%s', (identity,)).fetchone()['profile'].get('name')
digest = send_code(c, change['id'], change['new_email'], 'email', name)
c.execute('''UPDATE dtf_local.email_changes SET code_hash=%s, attempts=0, sends=sends+1, sent_at=now(),
expires_at=now() + %s * interval '1 minute' WHERE id=%s''', (digest, mail.CODE_MINUTES, change['id']))
return {'ok': True, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
@router.post('/api/account/password')
def change_password(body: PasswordChange, request: Request, identity=Depends(owner)):
with db.connect() as c:
row = account_row(c, identity)
throttle(row['email'], request)
if not password_matches(body.current, row['password_hash']):
login_failed(row['email'])
raise HTTPException(401, 'Senha atual incorreta.')
session = current(request)
with db.connect() as c:
c.execute('UPDATE dtf_local.accounts SET password_hash=%s WHERE id=%s', (password_hash(body.new), identity))
# Other devices signed in with the old password are signed out.
c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s AND id<>%s', (identity, session['id']))
audit('account_password_changed', account=str(identity))
return {'ok': True}
# Password recovery: a link by e-mail that works once, for an hour. The answer
# never says whether the e-mail has an account.
RESET_SENT = 'Se houver uma conta com este e-mail, enviamos um link para criar uma nova senha. Ele vale por 1 hora.'
@router.post('/api/account/forgot')
def forgot_password(body: ForgotPassword, request: Request):
if not mail.configured():
raise HTTPException(503, 'A recuperação por e-mail ainda não está disponível. Fale com a Dropstar pelo WhatsApp.')
email = body.email.strip().lower()
rate_limit('reset-source', client_ip(request), 10)
# Per address: a few links an hour, so nobody fills someone's inbox.
rate_limit('reset-account', email, 3, 3600)
token = secrets.token_urlsafe(32)
with db.connect() as c:
account = c.execute('SELECT id,profile FROM dtf_local.accounts WHERE email=%s', (email,)).fetchone()
if account:
c.execute('''INSERT INTO dtf_local.password_resets(token_hash,account_id,expires_at)
VALUES(%s,%s,now() + %s * interval '1 minute')''',
(hashlib.sha256(token.encode()).hexdigest(), account['id'], mail.RESET_MINUTES))
# In the fragment, not the query: it is never sent to a server,
# nor in the Referer of the fonts and the logo the page loads.
link = f'{PUBLIC_ORIGIN}/conta/redefinir#{token}'
name = account['profile'].get('name')
mail.queue(c, 'reset', email, 'Crie uma nova senha · DTF Dropstar',
f'{mail_html.greeting(name)}\n\nAlguém pediu para criar uma nova senha na sua conta do DTF Dropstar. '
f'Para criar, abra o link abaixo. Ele vale por 1 hora e funciona uma vez só.\n\n{link}\n\n'
'Se não foi você, ignore este e-mail: a sua senha continua a mesma.',
mail_html.reset(name, link, mail.RESET_MINUTES))
audit('password_reset_requested', account=str(account['id']) if account else None, ip=client_ip(request))
return {'ok': True, 'message': RESET_SENT}
@router.post('/api/account/reset')
def reset_password(body: PasswordReset, request: Request, response: Response):
rate_limit('reset-source', client_ip(request), 10)
digest = hashlib.sha256(body.token.encode()).hexdigest()
previous = current(request)
with db.connect() as c:
reset = c.execute('''SELECT * FROM dtf_local.password_resets WHERE token_hash=%s
AND used_at IS NULL AND expires_at>now() FOR UPDATE''', (digest,)).fetchone()
if not reset:
audit('password_reset_refused', ip=client_ip(request))
raise HTTPException(400, 'Este link venceu ou já foi usado. Peça outro em “Esqueci minha senha”.')
identity = reset['account_id']
account = account_row(c, identity, lock=True)
# The link came by e-mail, so the address is confirmed too.
c.execute('UPDATE dtf_local.accounts SET password_hash=%s, email_verified=true WHERE id=%s',
(password_hash(body.password), identity))
c.execute('UPDATE dtf_local.password_resets SET used_at=now() WHERE token_hash=%s', (digest,))
# Every other link to this account stops working, and so does every
# session signed in with the old password.
c.execute('DELETE FROM dtf_local.password_resets WHERE account_id=%s AND used_at IS NULL', (identity,))
if previous:
transfer_guest(c, previous, identity)
claim_orders(c, identity, account['profile'])
c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s', (identity,))
if previous:
c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['id'],))
new_session(c, response, identity)
audit('password_reset', account=str(identity))
return {'customer': account['profile']}
# The order list's groups, as the customer filters them.
GROUPS = {'pay': 'Aguardando pagamento', 'prod': 'Em produção', 'cor': 'Correção', 'fin': 'Finalizados'}
ENTRIES = '''WITH live_quote AS (
-- The cart waiting for payment: the newest unpaid quote whose files still
-- exist. An older one was replaced when the cart changed, and one whose
-- files are gone can no longer be paid.
SELECT q.id, q.created_at, q.approved FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE q.owner=%(me)s AND o.id IS NULL AND q.discarded_at IS NULL
AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i
CROSS JOIN LATERAL jsonb_array_elements_text(i->'uploads') u(uid)
JOIN dtf_local.uploads up ON up.id=u.uid::uuid
WHERE up.purged_at IS NOT NULL OR up.expires_at<=now())
ORDER BY q.created_at DESC LIMIT 1
), entries AS (
SELECT 'order' AS kind, o.id, o.number, CASE WHEN o.cancelled_at IS NOT NULL THEN 'cancelled' ELSE o.state END,
CASE WHEN o.cancelled_at IS NOT NULL OR o.state='fin' THEN 'fin' WHEN o.state='cor' THEN 'cor' ELSE 'prod' END AS grp,
(o.snapshot->>'total_cents')::bigint AS total_cents, o.created_at, o.snapshot->'items' AS items
FROM dtf_local.orders o WHERE o.owner=%(me)s
UNION ALL
SELECT 'quote', q.id, NULL, CASE WHEN q.approved IS NULL THEN 'review' ELSE 'pay' END, 'pay',
(q.approved->>'total_cents')::bigint, q.created_at, COALESCE(q.approved->'items','[]'::jsonb)
FROM live_quote q
)'''
@router.get('/api/customer/orders')
def orders(identity=Depends(owner), status: Literal['all','pay','prod','cor','fin'] = 'all',
number: int | None = Query(None, ge=1), code: str | None = Query(None, max_length=12, pattern=r'^[0-9A-Fa-f]+$'),
days: int = Query(0, ge=0, le=3650),
page: int = Query(1, ge=1, le=10000), size: int = Query(10, ge=1, le=50)):
"""The customer's orders and the cart waiting for payment, newest first,
filtered and a page at a time, with how many there are in each group."""
params = {'me': identity, 'grp': None if status == 'all' else status, 'number': number,
'code': code.lower() + '%' if code else None,
'since': datetime.now(timezone.utc) - timedelta(days=days) if days else None,
'size': size, 'offset': (page - 1) * size}
where = '''WHERE (%(grp)s::text IS NULL OR grp=%(grp)s) AND (%(number)s::int IS NULL OR number=%(number)s)
AND (%(code)s::text IS NULL OR (kind='order' AND replace(id::text,'-','') LIKE %(code)s))
AND (%(since)s::timestamptz IS NULL OR created_at>=%(since)s)'''
with db.connect() as c:
counts = {r['grp']: r['n'] for r in c.execute(ENTRIES + ' SELECT grp, count(*) AS n FROM entries GROUP BY grp', params).fetchall()}
total = c.execute(ENTRIES + ' SELECT count(*) AS n FROM entries ' + where, params).fetchone()['n']
rows = c.execute(ENTRIES + ' SELECT * FROM entries ' + where +
' ORDER BY created_at DESC LIMIT %(size)s OFFSET %(offset)s', params).fetchall()
items = []
for r in rows:
entry = {'kind': r['kind'], 'id': r['id'], 'number': r['number'], 'state': r['state'],
'code': order_code(r['id']) if r['kind'] == 'order' else None,
'group': r['grp'], 'total_cents': r['total_cents'], 'created_at': r['created_at'],
'items': [{'mode': i['mode'], 'billed_metres': i.get('billed_metres')} for i in r['items']]}
if r['kind'] == 'quote':
# A PIX code still open is paid on its own page.
pix = c.execute('''SELECT 1 FROM dtf_local.payment_intents WHERE quote_id=%s AND method='pix'
AND status='pending' AND COALESCE((response->>'expires_at')::timestamptz > now(), false)''',
(r['id'],)).fetchone()
entry['pay_with'] = 'pix' if pix else 'page'
items.append(entry)
return {'items': items, 'total': total, 'page': page, 'size': size,
'counts': {g: counts.get(g, 0) for g in GROUPS}, 'groups': GROUPS, 'states': STATES}
@router.get('/api/customer/orders/{oid}')
def detail(oid: UUID, identity=Depends(owner)):
with db.connect() as c:
row = owned_order(c, oid, identity)
history = c.execute('SELECT from_state,to_state,reason,created_at FROM dtf_local.movements WHERE order_id=%s ORDER BY id', (oid,)).fetchall()
return {'id': row['id'], 'number': row['number'], 'state': row['state'], 'version': row['version'],
'snapshot': row['snapshot'], 'history': history, 'files': file_rows(c,oid)}
# A move back undoes an operator's mistake and its reason is internal;
# only a correction's reason is written for the customer.
history = c.execute('''SELECT from_state,to_state,CASE WHEN to_state='cor' THEN reason ELSE '' END AS reason,
created_at FROM dtf_local.movements WHERE order_id=%s AND NOT back ORDER BY id''', (oid,)).fetchall()
# The review photos only once the order is Finalizado; a video stays
# on the Kanban card (app/reviews.py).
photos = c.execute('''SELECT r.id,u.name,r.created_at FROM dtf_local.order_reviews r
JOIN dtf_local.uploads u ON u.id=r.upload_id
WHERE r.order_id=%s AND r.kind='photo' ORDER BY r.seq''', (oid,)).fetchall() \
if row['state'] == 'fin' else []
return {'id': row['id'], 'number': row['number'], 'code': order_code(row['id']),
'state': row['state'], 'version': row['version'],
'created_at': row['created_at'], 'snapshot': row['snapshot'], 'history': history,
'files': file_rows(c,oid),
'reviews': [{'id': photo['id'], 'name': photo['name'], 'created_at': photo['created_at']}
for photo in photos]}
@router.post('/api/customer/orders/{oid}/corrections')
def correction(oid: UUID, body: ArtworkSubmission, identity=Depends(owner)):
@@ -113,7 +525,7 @@ def customer_download(oid: UUID, fid: UUID, identity=Depends(owner)):
with db.connect() as c:
owned_order(c,oid,identity)
row = c.execute('SELECT u.* FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.id=%s AND f.order_id=%s AND f.active', (fid,oid)).fetchone()
if not row: raise HTTPException(404, 'Active file not found')
if row['expires_at'] <= datetime.now(timezone.utc): raise HTTPException(410, 'File expired')
if not row: raise HTTPException(404, 'Arquivo não encontrado.')
if row['expires_at'] <= datetime.now(timezone.utc): raise HTTPException(410, 'Este arquivo não está mais disponível: os arquivos ficam guardados por 30 dias.')
require_clean(row)
return {'url':storage.download(row['object_key'],row['name']), 'name':row['name']}

View File

@@ -1,27 +1,70 @@
"""Health, session bootstrap and freight quoting."""
"""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, grade_rules, mail, observability
from ..core.auth import client_ip, owner, new_session, rate_limit
from ..core.limits import upload_limit_bytes
from ..core.models import Freight
from ..runtime import ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, freight, payment, storage
from ..core.pricing import manual_extra_cents
from ..core.models import FreightAsk, FreightEstimate
from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, delivery_services, freight, payment,
require_delivery_available, storage)
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):
@@ -33,14 +76,81 @@ def session(request: Request, response: Response):
rate_limit('guest-sessions', client_ip(request), GUEST_SESSION_LIMIT, 900)
with db.connect() as c:
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 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],
'bands': [{'from_metres': float(band['from_metres']),
'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 ''}
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
# The delivery options the cart quotes, or none: pickup only.
'freight_services': delivery_services()}
@router.post('/api/freight')
def quote_freight(body: Freight):
def quote_freight(body: FreightEstimate):
require_delivery_available(body.service)
try:
return freight.quote(body.service, body.postal_code)
return freight.quote(body.service, body.postal_code, body.metres, body.declared_cents)
except ValueError as exc:
raise HTTPException(422, str(exc))
@router.post('/api/freight/options')
def freight_options(body: FreightAsk, request: Request):
"""Every delivery option for the cart, cheapest first. Each asks a carrier,
so a source asking too often is held back."""
rate_limit('freight-options', client_ip(request), 120, 900)
if not delivery_services():
raise HTTPException(503, 'A entrega ainda não está disponível. Escolha a retirada em Franca.')
found = freight.options(body.postal_code, body.metres, body.declared_cents)
if not found['options']:
reasons = '; '.join(item['error'] for item in found['unavailable'])
raise HTTPException(422, 'Não foi possível cotar a entrega para este CEP agora.' + (f' ({reasons})' if reasons else ''))
return found
# The address of a CEP, so the cart fills it in. Looked up here rather than in
# the browser, which keeps the Site's CSP to its own origin.
VIACEP = 'https://viacep.com.br/ws/{}/json/'
CEP_LIMIT = 120
@router.get('/api/cep/{cep}')
def cep_address(cep: str, request: Request):
if not re.fullmatch(r'[0-9]{8}', cep):
raise HTTPException(422, 'CEP must have eight digits')
rate_limit('cep-lookup', client_ip(request), CEP_LIMIT, 900)
try:
response = httpx.get(VIACEP.format(cep), timeout=5)
data = response.json() if response.status_code == 200 else {}
except (httpx.HTTPError, ValueError):
raise HTTPException(503, 'Consulta de CEP indisponível')
if not data or data.get('erro'):
raise HTTPException(404, 'CEP não encontrado')
return {'street': data.get('logradouro') or '', 'district': data.get('bairro') or '',
'city': data.get('localidade') or '', 'state': data.get('uf') or ''}

139
app/api/machine_log.py Normal file
View File

@@ -0,0 +1,139 @@
"""Routes of the machine sheet (Fase 2, front 1a, app/machine_log.py)."""
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Request
from .. import machine_log, machine_stats
from ..core import db
from ..core.auth import audit, can, operator, operator_only, roles_of
from ..core.models import MachineEntry, MachineSheet
router = APIRouter()
# Números is read by management and by the seller and finance, who consult it.
STATS_ROLES = ('superadmin', 'admin', 'gestao', 'vendedor', 'financeiro')
def machine_row(c, mid):
row = c.execute('SELECT id,name,price_cents,installed_on FROM dtf_local.machines WHERE id=%s',
(mid,)).fetchone()
if not row:
raise HTTPException(404, 'Máquina não encontrada.')
return row
def own_machine(request, mid):
"""An operator enters only on the machine of their session; management, anywhere."""
account = request.state.operator
if not operator_only(account, 'print'):
return
session_machine = account['machine']
if not session_machine or str(session_machine['id']) != str(mid):
raise HTTPException(403, 'Você só lança na máquina em que está.')
def entry_label(row):
if row['kind'] == 'supply':
return machine_log.SUPPLIES.get(row['item'], (row['item'],))[0]
if row['kind'] == 'part':
return machine_log.PARTS.get(row['item'], row['item'])
return machine_log.EVENTS.get(row['item'], row['item'])
@router.get('/api/operator/machines/{mid}/sheet')
def sheet(mid: UUID, user=Depends(can('view'))):
with db.connect() as c:
machine = machine_row(c, mid)
entries = c.execute('''SELECT * FROM dtf_local.machine_entries
WHERE machine_id=%s ORDER BY created_at DESC, id DESC LIMIT 50''', (mid,)).fetchall()
minimums = {row['item']: row['minimum'] for row in c.execute(
'SELECT item,minimum FROM dtf_local.machine_minimums WHERE machine_id=%s', (mid,)).fetchall()}
return {'machine': {'id': str(machine['id']), 'name': machine['name'],
'price_cents': machine['price_cents'], 'installed_on': machine['installed_on']},
'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,
'events': machine_log.EVENTS}}
@router.post('/api/operator/machines/{mid}/entries')
def add_entry(mid: UUID, body: MachineEntry, request: Request, user=Depends(can('print'))):
own_machine(request, mid)
catalog = {'supply': machine_log.SUPPLIES, 'part': machine_log.PARTS,
'event': machine_log.EVENTS}[body.kind]
if body.item not in catalog:
raise HTTPException(422, 'Escolha um item da lista.')
if body.kind == 'supply':
if body.quantity is None:
raise HTTPException(422, 'Informe a quantidade que entrou.')
elif body.kind == 'part':
if body.cost_cents is None:
raise HTTPException(422, 'Informe o custo da peça.')
if body.item == 'other' and not (body.note or '').strip():
raise HTTPException(422, 'Descreva a outra peça.')
elif body.item == 'stop':
if not (body.note or '').strip() or body.stop_minutes is None:
raise HTTPException(422, 'Informe o motivo e os minutos da parada.')
elif body.quantity is not None or body.cost_cents is not None:
raise HTTPException(422, 'Limpeza e alinhamento não levam quantidade nem custo.')
with db.connect() as c:
machine_row(c, mid)
row = machine_log.add_entry(c, mid, body, user, from_alert=body.from_alert)
audit('machine_entry', operator=user, machine=str(mid), kind=body.kind, item=body.item,
from_alert=body.from_alert)
return row
@router.post('/api/operator/machines/{mid}/sheet')
def save_sheet(mid: UUID, body: MachineSheet, user=Depends(can('manage'))):
unknown = set(body.minimums) - set(machine_log.SUPPLIES)
if unknown:
raise HTTPException(422, 'Só os insumos têm mínimo.')
for value in body.minimums.values():
if value is not None and value < 0:
raise HTTPException(422, 'O mínimo não pode ser negativo.')
with db.connect() as c:
machine_row(c, mid)
c.execute('UPDATE dtf_local.machines SET price_cents=%s, installed_on=%s WHERE id=%s',
(body.price_cents, body.installed_on, mid))
for item, value in body.minimums.items():
if value is None:
c.execute('DELETE FROM dtf_local.machine_minimums WHERE machine_id=%s AND item=%s',
(mid, item))
else:
c.execute('''INSERT INTO dtf_local.machine_minimums(machine_id,item,minimum)
VALUES(%s,%s,%s) ON CONFLICT (machine_id,item) DO UPDATE SET minimum=EXCLUDED.minimum''',
(mid, item, value))
audit('machine_sheet', operator=user, machine=str(mid), price_cents=body.price_cents,
installed_on=str(body.installed_on) if body.installed_on else None)
return {'ok': True}
@router.post('/api/operator/machines/{mid}/alerts/{key}/snooze')
def snooze_alert(mid: UUID, key: str, request: Request, user=Depends(can('print'))):
own_machine(request, mid)
with db.connect() as c:
machine_row(c, mid)
machine_log.snooze(c, mid, key, user)
audit('machine_alert_snoozed', operator=user, machine=str(mid), alert=key)
return {'ok': True}
@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 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)
except ValueError:
raise HTTPException(422, 'Informe o mês como AAAA-MM.')
if start > machine_stats.month_bounds(None)[0]:
raise HTTPException(422, 'Esse mês ainda não começou.')
with db.connect() as c:
return machine_stats.report(c, month=month)

View File

@@ -1,255 +0,0 @@
"""Kanban: sign-in, the board, commercial review and card movement."""
import hashlib
import os
import secrets
from datetime import datetime, timedelta, timezone
from typing import Literal
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from fastapi.responses import RedirectResponse
from psycopg.types.json import Jsonb
from ..core import db
from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, client_ip, operator,
login_failed, password_matches, throttle)
from ..core.models import Move, OperatorLogin, Resolution, Review
from ..core.pricing import price
from ..printjobs import queue as queue_print_files
from .. import tiny
from ..runtime import (BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, STATES, TRANSITIONS,
enqueue, freight, quote_view, storage, upload_row)
from ..scanning import require_clean
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, 'No Kanban operator account is configured')
# 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, 'Invalid operator login')
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}
@router.get('/api/operator/board')
def board(user=Depends(operator)):
with db.connect() as c:
# 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()
finished = c.execute("SELECT * FROM dtf_local.orders WHERE state='fin' ORDER BY created_at DESC LIMIT %s",
(BOARD_FINISHED_LIMIT,)).fetchall()
finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin'").fetchone()['n']
pending = c.execute('''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
ORDER BY q.created_at DESC,q.id DESC LIMIT %s''', (BOARD_QUOTE_LIMIT,)).fetchall()
approved = c.execute('''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
ORDER BY q.created_at DESC,q.id DESC LIMIT 20''').fetchall()
pending_total = c.execute('''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''').fetchone()['n']
approved_total = c.execute('''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''').fetchone()['n']
orders = active + list(reversed(finished))
generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,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''', ([o['id'] for o in orders],)).fetchall()
for order in orders:
order['print_files'] = [row for row in generated if row['order_id'] == order['id']]
# A paid notification that did not become an order is money received
# for nothing the factory will make. It stays on the board until a
# person records what was done about it.
refused = c.execute('''SELECT id,provider,event_id,reference,status,amount_cents,received_at,outcome
FROM dtf_local.payment_events WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') AND resolved_at IS NULL
ORDER BY received_at LIMIT 100''').fetchall()
return {'states': STATES, 'transitions': TRANSITIONS,
'orders': orders, 'payment_issues': refused, 'tiny': tiny_status(),
'finished_shown': len(finished), 'finished_total': finished_total,
'quotes': [quote_view(c, q) for q in pending + approved],
'pending_total': pending_total, 'approved_total': approved_total,
'events': c.execute('SELECT * FROM dtf_local.outbox ORDER BY id DESC LIMIT 100').fetchall()}
@router.get('/api/operator/quotes')
def quote_page(kind: Literal['pending','approved'], before_created_at: datetime | None = None,
before_id: UUID | None = None, limit: int = Query(default=50, ge=1, le=100),
user=Depends(operator)):
if (before_created_at is None) != (before_id is None):
raise HTTPException(422, 'Both quote cursor fields are required')
approved_filter = 'q.approved IS NULL' if kind == 'pending' else 'q.approved IS NOT NULL'
cursor = 'AND (q.created_at,q.id)<(%s,%s)' if before_created_at else ''
params = ((before_created_at,before_id) if before_created_at else ()) + (limit+1,)
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 o.id IS NULL AND {approved_filter} {cursor}
ORDER BY q.created_at DESC,q.id DESC LIMIT %s''', params).fetchall()
return {'quotes':[quote_view(c,row) for row in rows[:limit]],
'has_more':len(rows)>limit}
@router.post('/api/operator/quotes/{uid}/approve')
def approve(uid: UUID, body: Review, user=Depends(operator)):
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')
if row['approved']:
raise HTTPException(409, 'Approved quotes are immutable; request a new quote')
draft = row['draft']
if any(item.get('production', {}).get('version') != 2 for item in draft['items']):
raise HTTPException(409, 'Quote uses an obsolete production layout; customer must request a new quote')
if len(body.items) != len(draft['items']):
raise HTTPException(422, 'Review must cover every item')
items = []
for item, original in zip(body.items, draft['items']):
if item.mode != original['mode'] or list(map(str,item.uploads)) != original['uploads']:
raise HTTPException(422, 'Product mode and attached files cannot change during review')
if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged']:
raise HTTPException(422, 'Production instructions and customer acknowledgement cannot change during commercial review')
for upload_id in item.uploads:
require_clean(upload_row(c, upload_id, row['owner']))
items.append({**price(item.mode, str(item.metres), item.grade),
'uploads': original['uploads'], 'production': original['production'],
'quality_status': original['quality_status'],
'quality_acknowledged': original['quality_acknowledged']})
quoted_freight = freight.quote(**draft['freight'])
approved = {'customer': draft['customer'], 'items': items, 'freight': quoted_freight,
'destination': draft.get('destination'),
'total_cents': sum(i['total_cents'] for i in items)+quoted_freight['total_cents']}
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s', (Jsonb(approved),user,uid))
return approved
@router.post('/api/operator/orders/{uid}/move')
def move(uid: UUID, body: Move, user=Depends(operator)):
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, 'Order changed; refresh the board')
if body.state == row['state']:
return row
if body.state not in TRANSITIONS[row['state']]:
raise HTTPException(409, 'Move is not allowed from this state')
if body.state == 'cor' and not body.reason.strip():
raise HTTPException(422, 'Correction requires a reason')
if body.state in ('fil','imp'):
coverage = c.execute('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 f.kind=\'final\' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state=\'clean\'', (uid,)).fetchall()
if {r['item_index'] for r in coverage} != set(range(len(row['snapshot']['items']))):
raise HTTPException(409, 'Approve a complete final-file set for every item before queueing')
if body.state == 'cor':
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,))
c.execute('INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) VALUES(%s,%s,%s,%s,%s)',
(uid,row['state'],body.state,user,body.reason))
changed = c.execute('UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now() WHERE id=%s RETURNING *', (body.state,uid)).fetchone()
events = {'imp':'production_started','cor':'correction_needed','fin':'ready'}
if body.state in events:
for provider in ('tiny','whatsapp'):
enqueue(c, f'{uid}:{changed["version"]}:{provider}', provider,
{'order_id':str(uid), 'number':row['number'], 'event':events[body.state], 'reason':body.reason,
'customer_path': f'/portal.html?order={uid}'})
return changed
@router.post('/api/operator/orders/{uid}/print-files')
def regenerate(uid: UUID, user=Depends(operator)):
"""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,snapshot,state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Order not found')
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')
queue_print_files(c, uid, len(row['snapshot']['items']), only_missing=True)
audit('print_file_requeued', order=str(uid), operator=user)
return c.execute('SELECT * FROM dtf_local.print_files WHERE order_id=%s ORDER BY item_index', (uid,)).fetchall()
@router.post('/api/operator/payment-events/{uid}/resolve')
def resolve_payment(uid: UUID, body: Resolution, user=Depends(operator)):
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():
if not tiny.configured():
return {'configured': False}
return {'configured': True, 'orders_enabled': os.environ.get('TINY_ADAPTER') == 'tiny',
**tiny.TinyAuth().status()}
@router.post('/api/operator/tiny/connect')
def tiny_connect(user=Depends(operator)):
"""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.get('/api/operator/tiny/callback')
def tiny_callback(code: str = Query(max_length=4096), state: 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."""
if not tiny.configured():
raise HTTPException(503, 'Tiny application is not configured')
try:
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)
@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}/download')
def download(uid: UUID, 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)
return {'name':row['name'], 'url':storage.download(row['object_key'],row['name']), 'expires_in':300}

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

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

@@ -0,0 +1,252 @@
"""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()
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)})
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'])} 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}

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

@@ -0,0 +1,648 @@
"""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,))
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)
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,))
# Pulled to Imprimindo, its files go to its machine's hot folder; out
# of it, what Flexi did not take leaves (item 10).
if row['state'] == 'imp':
hotfolder.stop(c, uid)
if body.state == 'imp':
hotfolder.start(c, uid)
# 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).
events = {'tra':'production_started','cor':'correction_needed','fin':'ready'}
if body.state in events and not back and payments.in_tiny(row):
# "Production started" and "ready" reach the customer once per order,
# even if a mistaken move is undone and made again. Each correction
# is a new request, so it keeps one message per movement.
once = body.state in ('tra','fin')
event = {'order_id':str(uid), 'number':row['number'], 'event':events[body.state], 'reason':body.reason,
'customer_path': f'/portal.html?order={uid}'}
# Tiny needs the order (customer, pickup or delivery) and, once the
# sale reached it, its id, to set the situação without a search.
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
(f'{uid}:paid:tiny',)).fetchone()
tiny = {**event, 'order': row['snapshot'], 'tiny_id': ((sale or {}).get('receipt') or {}).get('tiny_id')}
key = f'{uid}:{events[body.state]}:tiny' if once else f'{uid}:{changed["version"]}:tiny'
enqueue(c, key, 'tiny', tiny)
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.')
chosen = None if len(items) == count else 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

@@ -34,5 +34,5 @@ def dev_paid(body: Pay, session_id=Depends(owner)):
# The charge happens inside the transaction that persists the order, so a
# failure to record it cannot leave a customer charged without an order.
receipt = payment.pay(str(body.quote_id), quote['approved']['total_cents'])
order, _ = payments.create_order(c, quote, receipt)
order, _ = payments.create_order(c, quote, receipt, 'site')
return order

View File

@@ -7,10 +7,11 @@ and an unverified delivery is recorded and refused rather than retried.
"""
from uuid import uuid4
import httpx
from fastapi import APIRouter, Depends, HTTPException, Request
from psycopg.types.json import Jsonb
from .. import payments
from .. import payment_messages as messages, payments
from ..core import db
from ..core.auth import audit, client_ip, owner, rate_limit
from ..core.models import PaymentIntent
@@ -21,6 +22,8 @@ router = APIRouter()
# Generous: a provider legitimately retries, and a signature check is cheap.
# This exists so an unsigned flood cannot keep the database busy.
WEBHOOK_LIMIT = 600
# How long a card waiting for the bank's confirmation holds off a new attempt.
CHALLENGE_MINUTES = 10
@router.post('/api/payments/webhook')
@@ -30,9 +33,20 @@ async def webhook(request: Request):
query = dict(request.query_params)
if not payment.verify(request.headers, body, query):
audit('payment_webhook_rejected', ip=client_ip(request), reason='signature')
# What arrived, never what it carried: which query parameters (Mercado
# Pago's current webhook sends data.id/type, its old IPN topic/id and
# often no signature), whether the signature and request id headers came,
# and how old the signature's timestamp is.
audit('payment_webhook_rejected', ip=client_ip(request), reason='signature',
params=','.join(sorted(query))[:200], source=query.get('source_news', '')[:20],
signed='x-signature' in request.headers, request_id='x-request-id' in request.headers,
age=signature_age(request.headers.get('x-signature', '')))
raise HTTPException(403, 'Invalid signature')
if getattr(payment, 'last_signature', 'documentado') not in (None, 'documentado') or getattr(payment, 'secret_was_trimmed', False):
# Genuine, but not quite as documented: say how, so it can be settled.
audit('payment_webhook_signature', variant=payment.last_signature,
secret_trimmed=getattr(payment, 'secret_was_trimmed', False))
event = payment.parse(body, query)
if event is None:
# Verified, so genuinely from the provider, but not about a payment.
@@ -58,6 +72,25 @@ def event_provider():
return payment.name
def signature_age(signature):
"""Seconds since the signature's ts (ts=<unix>,v1=<hex>), or '' without one."""
import time
parts = dict(part.strip().split('=', 1) for part in signature.split(',') if '=' in part)
ts = parts.get('ts', '')
return int(time.time() - int(ts[:10])) if ts[:10].isdigit() else ''
def provider_reason(response):
"""A short, loggable reason from a refused provider call."""
try:
data = response.json()
except ValueError:
return f'HTTP {response.status_code}'
causes = '; '.join(f"{c.get('code')}: {c.get('description')}" for c in data.get('cause') or []
if isinstance(c, dict))
return (causes or data.get('message') or data.get('error') or f'HTTP {response.status_code}')[:300]
@router.post('/api/payments/intent')
def intent(body: PaymentIntent, session_id=Depends(owner)):
"""Start paying an approved quote: a PIX code, or a card token from the
@@ -68,27 +101,71 @@ def intent(body: PaymentIntent, session_id=Depends(owner)):
try:
quote = payments.approved_quote(c, body.quote_id, session_id)
except payments.PaymentRefused as refusal:
raise HTTPException(404 if 'not found' in str(refusal) else 409, str(refusal))
raise HTTPException(404 if 'not found' in str(refusal) else 409, messages.quote_refusal(refusal))
if c.execute('SELECT 1 FROM dtf_local.orders WHERE quote_id=%s', (body.quote_id,)).fetchone():
raise HTTPException(409, 'Quote is already paid')
raise HTTPException(409, 'Este pedido já foi pago.')
# 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.
uploads = payments.quote_uploads(quote['approved'])
live = c.execute('''SELECT count(*) AS n FROM dtf_local.uploads WHERE id=ANY(%s)
AND purged_at IS NULL AND expires_at>now()''', (uploads,)).fetchone()['n']
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')
# 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
# for CHALLENGE_MINUTES: a customer who gave up on it must still be able
# to pay, and an unanswered challenge is not charged.
if c.execute('''SELECT 1 FROM dtf_local.payment_intents WHERE quote_id=%s
AND (status='approved' OR (method='card' AND status='pending'))''', (body.quote_id,)).fetchone():
raise HTTPException(409, 'A payment for this quote is already approved or in review')
AND (status='approved' OR (method='card' AND status='pending'
AND NOT (jsonb_typeof(response->'challenge')='object'
AND created_at < now() - make_interval(mins => %s))))''',
(body.quote_id, CHALLENGE_MINUTES)).fetchone():
raise HTTPException(409, 'Já existe um pagamento aprovado ou em análise para este pedido. '
'Aguarde a confirmação nesta página.')
method = body.method.model_dump()
if body.method.type == 'pix':
existing = c.execute('''SELECT * FROM dtf_local.payment_intents WHERE quote_id=%s AND method='pix'
# One open PIX per quote: the same code until it expires, and a new
# one only after that, when the old code can no longer be paid.
# Serialised per quote, so two clicks never open two codes.
c.execute('SELECT pg_advisory_xact_lock(hashtext(%s))', ('pix:'+str(body.quote_id),))
existing = c.execute('''SELECT *, COALESCE((response->>'expires_at')::timestamptz <= now(), false) AS expired
FROM dtf_local.payment_intents WHERE quote_id=%s AND method='pix'
AND status='pending' ORDER BY created_at DESC LIMIT 1''', (body.quote_id,)).fetchone()
if existing:
if existing and not existing['expired']:
return existing['response']
if existing:
c.execute("UPDATE dtf_local.payment_intents SET status='expired', updated_at=now() WHERE id=%s",
(existing['id'],))
method['attempt'] = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_intents
WHERE quote_id=%s AND method='pix' ''', (body.quote_id,)).fetchone()['n'] + 1
try:
created = payment.create(str(body.quote_id), quote['approved']['total_cents'],
quote['approved']['customer'], body.method.model_dump())
except ValueError as exc:
raise HTTPException(422, str(exc))
except Exception:
audit('payment_intent_failed', quote=str(body.quote_id))
raise HTTPException(502, 'Payment provider unavailable; try again')
quote['approved']['customer'], method)
except ValueError:
raise HTTPException(422, 'Esta forma de pagamento não é aceita. Pague com cartão de crédito ou PIX.')
except httpx.HTTPStatusError as exc:
# Mercado Pago's own reason (status, message and cause codes) goes to
# the log; it never contains card data, only what was refused.
reason = provider_reason(exc.response)
audit('payment_intent_refused', quote=str(body.quote_id), method=body.method.type,
status=exc.response.status_code, reason=reason)
if exc.response.status_code < 500:
try:
data = exc.response.json()
except ValueError:
data = {}
raise HTTPException(422, messages.refusal(data))
raise HTTPException(502, messages.UNAVAILABLE)
except Exception as exc:
audit('payment_intent_failed', quote=str(body.quote_id), error=type(exc).__name__)
raise HTTPException(502, messages.UNAVAILABLE)
if created.get('status') == 'rejected':
# What to tell the customer; the code stays in status_detail for the team.
created['message'] = messages.rejection(created.get('status_detail'))
c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,
status,amount_cents,response) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)
ON CONFLICT(provider,provider_payment_id) DO NOTHING''',

View File

@@ -1,16 +1,20 @@
"""Quotes: the customer's cart, and the operator-reviewed version of it."""
"""Quotes: the customer's cart, approved at once when it can be (app/quote_review.py)."""
import hashlib
import json
from datetime import datetime, timezone
from decimal import Decimal
from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException
from psycopg.types.json import Jsonb
from .. import cart_pricing, payments
from ..core import db
from ..core.auth import owner
from ..core.models import QuoteRequest
from ..runtime import freight, quote_view, upload_row
from .. import quote_review
from ..grade_check import Files, mismatch, resolution_issue, source_dpi
from ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
from ..scanning import require_clean
router = APIRouter()
@@ -19,32 +23,93 @@ router = APIRouter()
def create_quote(body: QuoteRequest, session_id=Depends(owner)):
for item in body.items:
if abs(item.metres*100-item.production.height_cm) > Decimal('0.02'):
raise HTTPException(422, 'Quoted metres do not match the submitted layout height')
raise HTTPException(422, 'A metragem não confere com a montagem enviada. Monte o pedido de novo.')
require_delivery_available(body.freight.service)
# The coupon code is stored normalized, so a quote waiting for review keeps
# the code the operator will see (front 8.3).
code = (body.coupon or '').strip().upper() or None
draft = body.model_dump(mode='json', exclude={'request_key'})
draft['coupon'] = code
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
try:
freight.quote(body.freight.service, body.freight.postal_code)
except ValueError as exc:
raise HTTPException(422, str(exc))
accepted_at = datetime.now(timezone.utc).isoformat()
for item in draft['items']:
if item.get('residue_accepted'):
item['residue_accepted_at'] = accepted_at
if item.get('stroke_choice'):
item['stroke_choice_at'] = accepted_at
reason = quote_review.review_reason(draft)
with db.connect() as c:
rows = {}
for item in body.items:
for uid in item.uploads:
row = upload_row(c, uid, session_id)
if not row['complete']:
raise HTTPException(409, 'Complete every upload before requesting a quote')
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar antes de continuar.')
# No transparency: the background prints, and loose art packs as a box (2026-10-23).
if row['name'].lower().endswith(('.jpg', '.jpeg')):
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.
files = Files(storage)
# Record the lowest source resolution for the Prumo report (front 6).
for draft_item, item in zip(draft['items'], body.items):
dpis = []
for source in item.production.sources:
row = rows.get(str(source.upload_id))
dpi = source_dpi(files, row, source.model_dump(mode='json')) if row else None
if dpi:
dpis.append(dpi)
if dpis:
draft_item['source_dpi'] = round(min(dpis))
issue = resolution_issue(files, draft['items'], rows)
if issue:
raise HTTPException(422, issue)
note = mismatch(files, draft['items'], rows) if reason is None else None
reason = reason or note
uid = uuid4()
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',
(uid, session_id, body.request_key, digest, Jsonb(draft)))
row = c.execute('SELECT * FROM dtf_local.quotes WHERE owner=%s AND request_key=%s', (session_id, body.request_key)).fetchone()
c.execute('INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,review_note) VALUES(%s,%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING',
(uid, session_id, body.request_key, digest, Jsonb(draft), note))
row = c.execute('SELECT * FROM dtf_local.quotes WHERE owner=%s AND request_key=%s FOR UPDATE', (session_id, body.request_key)).fetchone()
if row['request_hash'] != digest:
raise HTTPException(409, 'Request key already used for a different cart')
return {'id': row['id'], 'status': 'pending_review'}
raise HTTPException(409, 'O carrinho mudou durante o envio. Tente de novo.')
if row['id'] == uid and reason is None:
quote_review.approve(c, row, body.items, quote_review.AUTO)
return {'id': row['id'], 'status': 'approved'}
if row['id'] == uid:
# An operator reviews it first; the files wait for that review.
payments.hold_uploads(c, payments.quote_uploads(draft), payments.REVIEW_HOLD)
return {'id': row['id'], 'status': 'approved' if row['approved'] else 'pending_review'}
@router.get('/api/quotes/{uid}')
def get_quote(uid: UUID, session_id=Depends(owner)):
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s AND owner=%s', (uid,session_id)).fetchone()
if not row:
raise HTTPException(404, 'Quote not found')
return quote_view(c, row)
raise HTTPException(404, 'Pedido não encontrado.')
view = quote_view(c, row)
# The payment page asks every few seconds while it waits for the order. An
# approved card with no order yet is checked with the provider now, rather
# than waiting for its notification.
if view['status'] == 'approved' and (view['payment'] or {}).get('status') == 'approved':
if payments.reconcile(db.connect, payment, quote_id=uid, limit=3):
with db.connect() as c:
view = quote_view(c, c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (uid,)).fetchone())
return view

98
app/api/reviews.py Normal file
View File

@@ -0,0 +1,98 @@
"""Routes of the review photo or video (Fase 2, front 2, app/reviews.py)."""
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException
from pydantic import Field
from .. import reviews
from ..core import db
from ..core.auth import audit, can, operator, owner
from ..core.models import StrictModel
from ..runtime import operator_identity, owned_order, storage, upload_row
from ..scanning import require_clean
from .uploads import begin_upload
router = APIRouter()
class ReviewUploadStart(StrictModel):
"""The same shape as UploadStart, without its artwork-extension rule: a
review carries a photo or a video, not an artwork."""
name: str = Field(min_length=1, max_length=200, pattern=r'^[^/\\\x00-\x1f]+$')
size: int = Field(gt=0, strict=True)
class ReviewAdd(StrictModel):
upload_id: UUID
@router.post('/api/operator/orders/{uid}/reviews/uploads')
def start_review_upload(uid: UUID, body: ReviewUploadStart, user=Depends(can('inspect'))):
reviews.kind_of(body.name, body.size)
return begin_upload(body, session_id=operator_identity(user))
@router.post('/api/operator/orders/{uid}/reviews')
def add_review(uid: UUID, body: ReviewAdd, user=Depends(can('inspect'))):
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 order.get('cancelled_at'):
raise HTTPException(409, 'Pedido cancelado.')
if order['state'] != 'rev':
raise HTTPException(409, 'A revisão só entra com o pedido em Revisão.')
upload = upload_row(c, body.upload_id, operator_identity(user), lock=True)
if not upload['complete']:
raise HTTPException(409, 'Espere o envio terminar.')
require_clean(upload)
kind, ext, width, height = reviews.check(storage, upload)
row = reviews.attach(c, order, upload, kind, ext, width, height, user)
audit('order_review_added', order=str(uid), review=row['id'], kind=kind, operator=user)
return row
@router.post('/api/operator/orders/{uid}/reviews/{rid}/remove')
def remove_review(uid: UUID, rid: int, user=Depends(can('inspect'))):
with db.connect() as c:
order = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
if order['state'] != 'rev':
raise HTTPException(409, 'A revisão só sai com o pedido ainda em Revisão.')
row = c.execute('DELETE FROM dtf_local.order_reviews WHERE id=%s AND order_id=%s RETURNING upload_id',
(rid, uid)).fetchone()
if not row:
raise HTTPException(404, 'Revisão não encontrada.')
c.execute('UPDATE dtf_local.uploads SET expires_at=now() WHERE id=%s', (row['upload_id'],))
audit('order_review_removed', order=str(uid), review=rid, operator=user)
return {'ok': True}
def _mime(name):
return reviews.FORMATS[name.rsplit('.', 1)[-1].lower()][1]
@router.get('/api/operator/orders/{uid}/reviews/{rid}/view')
def view_review(uid: UUID, rid: int, user=Depends(operator)):
with db.connect() as c:
row = c.execute('''SELECT r.kind,u.object_key,u.name FROM dtf_local.order_reviews r
JOIN dtf_local.uploads u ON u.id=r.upload_id WHERE r.id=%s AND r.order_id=%s''',
(rid, uid)).fetchone()
if not row:
raise HTTPException(404, 'Revisão não encontrada.')
return {'url': storage.view(row['object_key'], _mime(row['name'])), 'name': row['name'], 'kind': row['kind']}
@router.get('/api/customer/orders/{oid}/reviews/{rid}/view')
def customer_view_review(oid: UUID, rid: int, identity=Depends(owner)):
with db.connect() as c:
owned_order(c, oid, identity)
row = c.execute('''SELECT u.object_key,u.name FROM dtf_local.order_reviews r
JOIN dtf_local.uploads u ON u.id=r.upload_id
JOIN dtf_local.orders o ON o.id=r.order_id
WHERE r.id=%s AND r.order_id=%s AND o.state='fin' AND r.kind='photo' ''',
(rid, oid)).fetchone()
if not row:
raise HTTPException(404, 'Foto não encontrada.')
return {'url': storage.view(row['object_key'], _mime(row['name'])), 'name': row['name'], 'kind': 'photo'}

264
app/api/site_admin.py Normal file
View File

@@ -0,0 +1,264 @@
"""The Site tab: what the Site sells and at what price, edited by Gestão.
A product is switched on or off here. Prices carry a start date and become
history: a row that has started is never changed or deleted, so only a
scheduled (future) price may be cancelled. Approved quotes keep the price they
were approved with (app/quote_review.py); a switched-off product refuses new
quotes and approvals with 422.
"""
import re
from datetime import datetime, timedelta, timezone
from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException
from psycopg.errors import UniqueViolation
from psycopg.types.json import Jsonb
from .. import catalog, grade_rules
from ..core import db
from ..core.auth import audit, can
from ..core.models import CouponNew, CouponUpdate, GradeRules, SitePriceNew, SiteProductToggle
router = APIRouter()
def price_row(row):
return {'id': row['id'], 'unit_cents': row['unit_cents'], 'bands': row['bands'] or [],
'starts_at': row['starts_at'].isoformat(), 'created_by': row['created_by'],
'created_at': row['created_at'].isoformat()}
def checked_bands(product, bands):
"""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, '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.')
last = band.from_metres
checked.append({'from_metres': str(band.from_metres), 'unit_cents': band.unit_cents})
return checked
@router.get('/api/operator/site/products')
def site_products(user=Depends(can('manage'))):
with db.connect() as c:
state = catalog.current(c)
now = c.execute('SELECT now() AS now').fetchone()['now']
started = {row['product']: row['unit_cents'] for row in c.execute('''
SELECT DISTINCT ON (product) product, unit_cents
FROM dtf_local.product_prices
WHERE starts_at <= now()
ORDER BY product, starts_at DESC, id DESC''').fetchall()}
rows = c.execute('''SELECT id, product, unit_cents, bands, starts_at, created_by, created_at
FROM dtf_local.product_prices ORDER BY product, created_at DESC, id DESC''').fetchall()
products = []
for product in catalog.PRODUCTS:
prices = [row for row in rows if row['product'] == product]
future = sorted((row for row in prices if row['starts_at'] > now),
key=lambda row: (row['starts_at'], row['id']))
products.append({
'id': product, 'title': catalog.TITLES[product], 'unit': catalog.UNITS[product],
'enabled': state[product]['enabled'],
'unit_cents': state[product]['unit_cents'],
'bands': state[product]['bands'],
'fallback': product not in started,
'scheduled': [price_row(row) for row in future],
'history': [price_row(row) for row in prices[:20]],
})
return {'products': products}
@router.post('/api/operator/site/products/{product}')
def toggle_product(product: str, body: SiteProductToggle, user=Depends(can('manage'))):
if product not in catalog.PRODUCTS:
raise HTTPException(404, 'Produto não encontrado.')
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.products(id, enabled, updated_by, updated_at)
VALUES(%s,%s,%s,now())
ON CONFLICT (id) DO UPDATE SET enabled=EXCLUDED.enabled,
updated_by=EXCLUDED.updated_by, updated_at=now()''',
(product, body.enabled, user))
audit('site_product_changed', product=product, enabled=body.enabled, operator=user)
return {'ok': True}
@router.post('/api/operator/site/products/{product}/prices')
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 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
if starts_at.tzinfo is None:
starts_at = starts_at.replace(tzinfo=timezone.utc)
if starts_at < now - timedelta(minutes=1):
raise HTTPException(422, 'A data de início não pode estar no passado.')
with db.connect() as c:
row = c.execute('''INSERT INTO dtf_local.product_prices(product, unit_cents, starts_at, created_by, bands)
VALUES(%s,%s,%s,%s,%s) RETURNING id''',
(product, body.unit_cents, starts_at, user, Jsonb(bands))).fetchone()
audit('site_price_changed', product=product, unit_cents=body.unit_cents, bands=bands,
starts_at=starts_at.isoformat(), operator=user)
return {'id': row['id']}
@router.post('/api/operator/site/prices/{price_id}/cancel')
def cancel_price(price_id: int, user=Depends(can('manage'))):
with db.connect() as c:
row = c.execute('''SELECT id, product, unit_cents, starts_at
FROM dtf_local.product_prices WHERE id=%s FOR UPDATE''', (price_id,)).fetchone()
if not row:
raise HTTPException(404, 'Preço não encontrado.')
if row['starts_at'] <= datetime.now(timezone.utc):
raise HTTPException(409, 'Este preço já começou: o histórico não pode ser apagado.')
c.execute('DELETE FROM dtf_local.product_prices WHERE id=%s', (price_id,))
audit('site_price_cancelled', price=price_id, product=row['product'], operator=user)
return {'ok': True}
def as_utc(value):
if value is None:
return None
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
def coupon_code(value):
code = (value or '').strip().upper()
if not re.fullmatch(r'[A-Z0-9-]{3,30}', code):
raise HTTPException(422, 'O código precisa ter de 3 a 30 letras, números ou hífens.')
return code
def check_coupon(kind, value, valid_from, valid_until):
if kind == 'percent' and not 1 <= value <= 90:
raise HTTPException(422, 'A porcentagem do cupom precisa ser de 1 a 90.')
if valid_until is not None and valid_until <= valid_from:
raise HTTPException(422, 'A validade final precisa ser depois do início.')
@router.get('/api/operator/site/coupons')
def site_coupons(user=Depends(can('manage'))):
with db.connect() as c:
rows = c.execute('''SELECT c.*, (SELECT count(*) FROM dtf_local.orders o
WHERE o.snapshot->'coupon'->>'id'=c.id::text
AND o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste'
AND o.parent_id IS NULL) AS uses
FROM dtf_local.coupons c WHERE c.deleted_at IS NULL
ORDER BY c.paused, c.created_at DESC''').fetchall()
return {'coupons': [{'id': str(row['id']), 'code': row['code'], 'kind': row['kind'],
'value': row['value'], 'valid_from': row['valid_from'].isoformat(),
'valid_until': row['valid_until'].isoformat() if row['valid_until'] else None,
'min_metres': float(row['min_metres']) if row['min_metres'] is not None else None,
'max_uses': row['max_uses'], 'max_uses_per_customer': row['max_uses_per_customer'],
'product': row['product'], 'note': row['note'], 'paused': row['paused'],
'created_by': row['created_by'], 'created_at': row['created_at'].isoformat(),
'uses': row['uses']} for row in rows]}
@router.post('/api/operator/site/coupons')
def create_coupon(body: CouponNew, user=Depends(can('manage'))):
code = coupon_code(body.code)
valid_from = as_utc(body.valid_from) or datetime.now(timezone.utc)
valid_until = as_utc(body.valid_until)
check_coupon(body.kind, body.value, valid_from, valid_until)
coupon_id = uuid4()
try:
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.coupons WHERE code=%s AND deleted_at IS NULL',
(code,)).fetchone():
raise HTTPException(409, 'Já existe um cupom com este código.')
c.execute('''INSERT INTO dtf_local.coupons(id,code,kind,value,valid_from,valid_until,
min_metres,max_uses,max_uses_per_customer,product,note,created_by)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)''',
(coupon_id, code, body.kind, body.value, valid_from, valid_until, body.min_metres,
body.max_uses, body.max_uses_per_customer, body.product, body.note.strip(), user))
except UniqueViolation:
# Two requests with the same new code at once: the partial index decides.
raise HTTPException(409, 'Já existe um cupom com este código.')
audit('site_coupon_created', coupon=str(coupon_id), code=code, operator=user)
return {'id': str(coupon_id)}
@router.post('/api/operator/site/coupons/{coupon_id}')
def update_coupon(coupon_id: UUID, body: CouponUpdate, user=Depends(can('manage'))):
fields = body.model_dump(exclude_unset=True)
# The form never sends null for these; a null would try to write NULL into
# a NOT NULL column, so an explicit null means "keep what is there".
for name in ('kind', 'value', 'paused'):
if name in fields and fields[name] is None:
fields.pop(name)
with db.connect() as c:
row = c.execute('''SELECT * FROM dtf_local.coupons
WHERE id=%s AND deleted_at IS NULL FOR UPDATE''', (coupon_id,)).fetchone()
if not row:
raise HTTPException(404, 'Cupom não encontrado.')
kind = fields.get('kind', row['kind'])
value = fields.get('value', row['value'])
valid_from = as_utc(fields['valid_from']) if 'valid_from' in fields else row['valid_from']
valid_from = valid_from or row['valid_from']
valid_until = as_utc(fields['valid_until']) if 'valid_until' in fields else row['valid_until']
check_coupon(kind, value, valid_from, valid_until)
if 'valid_from' in fields:
fields['valid_from'] = valid_from
if 'valid_until' in fields:
fields['valid_until'] = valid_until
if 'note' in fields:
fields['note'] = (fields['note'] or '').strip()
if fields:
names = list(fields)
c.execute(f'''UPDATE dtf_local.coupons SET {', '.join(f'{name}=%s' for name in names)}
WHERE id=%s''', (*[fields[name] for name in names], coupon_id))
audit('site_coupon_updated', coupon=str(coupon_id), operator=user)
return {'ok': True}
@router.post('/api/operator/site/coupons/{coupon_id}/delete')
def delete_coupon(coupon_id: UUID, user=Depends(can('manage'))):
with db.connect() as c:
row = c.execute('''UPDATE dtf_local.coupons SET deleted_at=now()
WHERE id=%s AND deleted_at IS NULL RETURNING code''', (coupon_id,)).fetchone()
if not row:
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}

164
app/api/site_videos.py Normal file
View File

@@ -0,0 +1,164 @@
"""Six DTF videos, managed by Gestão and published only after virus scanning."""
from typing import Literal
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Response
from pydantic import Field
from ..core import db
from ..core.auth import audit, can, operator
from ..core.models import StrictModel
from ..runtime import operator_identity, storage, upload_row
from ..scanning import require_clean
from .uploads import begin_upload
router = APIRouter()
CATALOG = {
'subindo': 'Subindo a arte pelo celular',
'nota': 'O que é a nota da arte — e o que ela não é',
'png': 'Por que PNG com fundo transparente',
'avulsas': 'Montando artes avulsas e vendo a folha ao vivo',
'retirada': 'Retirada em Franca em 24 h',
'sala': 'A sala às 3 da manhã',
}
VIDEO_MAX = 500 * 1024 * 1024
CAPTIONS_MAX = 1024 * 1024
class VideoUpdate(StrictModel):
upload_id: UUID | None = None
captions_id: UUID | None = None
product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None
enabled: bool = False
class VideoUploadStart(StrictModel):
name: str = Field(min_length=1, max_length=200, pattern=r'^[^/\\\x00-\x1f]+$')
size: int = Field(gt=0, strict=True)
def _kind(upload):
name = upload['name'].lower()
if name.endswith('.mp4') and upload['size'] <= VIDEO_MAX:
return 'video/mp4', b'ftyp', 4
if name.endswith('.webm') and upload['size'] <= VIDEO_MAX:
return 'video/webm', b'\x1a\x45\xdf\xa3', 0
if name.endswith('.vtt') and upload['size'] <= CAPTIONS_MAX:
return 'text/vtt', b'WEBVTT', 0
raise HTTPException(422, 'Use MP4/WebM de até 500 MB ou legenda VTT de até 1 MB.')
def _checked_upload(c, uid, identity, expected):
upload = upload_row(c, uid, identity, lock=True)
if not upload['complete']:
raise HTTPException(409, 'Espere o envio terminar.')
require_clean(upload)
mime, signature, offset = _kind(upload)
if mime not in expected:
raise HTTPException(422, 'Escolha um vídeo MP4/WebM e uma legenda VTT.')
response = storage.client.get_object(Bucket=storage.bucket, Key=upload['object_key'], Range='bytes=0-31')
head = response['Body'].read()
if not head[offset:].startswith(signature) and not (mime == 'text/vtt' and head.startswith(b'\xef\xbb\xbfWEBVTT')):
raise HTTPException(422, 'O conteúdo do arquivo não corresponde à extensão.')
return upload, mime
@router.post('/api/operator/site-videos/uploads')
def start_video_upload(body: VideoUploadStart, user=Depends(can('manage'))):
_kind({'name': body.name, 'size': body.size})
return begin_upload(body, session_id=operator_identity(user))
@router.get('/api/operator/site-videos')
def manage_videos(user=Depends(operator)):
with db.connect() as c:
rows = {row['id']: row for row in c.execute('''SELECT v.*,
u.name AS video_name, t.name AS captions_name
FROM dtf_local.site_videos v
LEFT JOIN dtf_local.uploads u ON u.id=v.upload_id
LEFT JOIN dtf_local.uploads t ON t.id=v.captions_id''').fetchall()}
return {'videos': [dict(id=id, title=title,
product=rows[id]['product'] if id in rows else None,
upload_id=rows[id]['upload_id'] if id in rows else None,
captions_id=rows[id]['captions_id'] if id in rows else None,
video_name=rows[id]['video_name'] if id in rows else None,
captions_name=rows[id]['captions_name'] if id in rows else None,
enabled=rows[id]['enabled'] if id in rows else False)
for id, title in CATALOG.items()]}
@router.post('/api/operator/site-videos/{video_id}')
def update_video(video_id: str, body: VideoUpdate, user=Depends(can('manage'))):
if video_id not in CATALOG:
raise HTTPException(404, 'Vídeo não encontrado.')
if body.enabled and not body.upload_id:
raise HTTPException(422, 'Envie o vídeo antes de publicar.')
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 (
(body.upload_id, ('video/mp4','video/webm'), previous.get('upload_id'), previous.get('video_key')),
(body.captions_id, ('text/vtt',), previous.get('captions_id'), previous.get('captions_key'))):
if not uid:
keys.append(None)
elif uid == previous_id and previous_key:
keys.append(previous_key)
else:
upload, mime = _checked_upload(c, uid, identity, expected)
key = f'videos/{video_id}/{uid}{".vtt" if mime == "text/vtt" else ".webm" if mime == "video/webm" else ".mp4"}'
storage.client.copy_object(Bucket=storage.bucket,
CopySource={'Bucket': storage.bucket, 'Key': upload['object_key']},
Key=key, ContentType=mime, MetadataDirective='REPLACE')
keys.append(key)
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,
video_key=EXCLUDED.video_key,captions_key=EXCLUDED.captions_key,
product=EXCLUDED.product,enabled=EXCLUDED.enabled,updated_by=EXCLUDED.updated_by,updated_at=now()''',
(video_id, body.upload_id, body.captions_id, keys[0], keys[1], body.product, body.enabled, user))
ids = [uid for uid in (body.upload_id, body.captions_id) if uid]
if ids:
c.execute("UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at,now()+interval '30 days') WHERE id=ANY(%s)", (ids,))
audit('site_video_changed', video=video_id, operator=user, enabled=body.enabled)
return {'ok': True}
@router.get('/api/site/videos')
def published_videos():
with db.connect() as c:
rows = c.execute('''SELECT v.id,v.product,v.video_key,v.captions_key,u.name AS video_name
FROM dtf_local.site_videos v
JOIN dtf_local.uploads u ON u.id=v.upload_id
WHERE v.enabled AND v.video_key IS NOT NULL''').fetchall()
return {'videos': [dict(id=row['id'], product=row['product'],
src=storage.view(row['video_key'], _kind({'name':row['video_name'],'size':0})[0]),
captions=f"/api/site/videos/{row['id']}/captions" if row['captions_key'] else None)
for row in rows]}
@router.get('/api/site/videos/{video_id}/captions')
def published_captions(video_id: str):
if video_id not in CATALOG:
raise HTTPException(404, 'Legenda não encontrada.')
with db.connect() as c:
row = c.execute('''SELECT captions_key FROM dtf_local.site_videos
WHERE id=%s AND enabled AND video_key IS NOT NULL AND captions_key IS NOT NULL''',
(video_id,)).fetchone()
if not row:
raise HTTPException(404, 'Legenda não encontrada.')
obj = storage.client.get_object(Bucket=storage.bucket, Key=row['captions_key'])
body = obj['Body'].read(CAPTIONS_MAX + 1)
if len(body) > CAPTIONS_MAX:
raise HTTPException(500, 'Legenda inválida.')
return Response(body, media_type='text/vtt', headers={'Cache-Control': 'public, max-age=300'})

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

@@ -8,40 +8,65 @@ import os
from uuid import UUID, uuid4
from botocore.exceptions import ClientError
from fastapi import APIRouter, Depends, HTTPException
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
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, 'File exceeds the malware scan limit; select a smaller file')
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')
raise HTTPException(429, 'Local storage quota or pending upload limit reached')
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,size,object_key,multipart_id,expires_at)
VALUES(%s,%s,%s,%s,%s,%s,now()+interval '1 hour')''',
(uid, session_id, body.name, body.size, key, multipart))
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,original_name,size,object_key,multipart_id,expires_at)
VALUES(%s,%s,%s,%s,%s,%s,%s,now()+interval '1 hour')''',
(uid, session_id, body.name, body.name, body.size, key, multipart))
return {'id': uid, 'part_bytes': PART_BYTES}
@router.get('/api/uploads/{uid}')
@@ -57,8 +82,11 @@ def upload_status(uid: UUID, session_id=Depends(owner)):
def part_url(uid: UUID, part: int, session_id=Depends(owner)):
with db.connect() as c:
row = upload_row(c, uid, session_id)
if row['complete'] or not 1 <= part <= math.ceil(row['size'] / PART_BYTES):
raise HTTPException(409, 'Invalid part or completed upload')
if row['complete'] or not 1 <= part <= math.ceil(row['size'] / PART_BYTES):
raise HTTPException(409, 'O envio deste arquivo já terminou ou foi interrompido. Escolha o arquivo de novo.')
# The reservation lease is an hour; a multi-GB upload on a slow line
# takes longer, so each part it asks for keeps it alive.
c.execute("UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at,now()+interval '1 hour') WHERE id=%s", (uid,))
size = min(PART_BYTES, row['size']-(part-1)*PART_BYTES)
return {'url': storage.part_url(row['object_key'], row['multipart_id'], part, size)}
@@ -79,21 +107,59 @@ def complete_upload(uid: UUID, session_id=Depends(owner)):
expected = math.ceil(row['size'] / PART_BYTES)
if [p['PartNumber'] for p in parts] != list(range(1, expected+1)) or any(
p['Size'] != min(PART_BYTES, row['size'] - i*PART_BYTES) for i,p in enumerate(parts)):
raise HTTPException(409, 'Parts are missing or their sizes do not match')
raise HTTPException(409, 'O envio do arquivo não chegou inteiro. Escolha o arquivo de novo.')
storage.complete(row['object_key'], row['multipart_id'], parts)
existing_size = storage.size(row['object_key'])
if existing_size != row['size']:
raise HTTPException(409, 'Stored size differs from declared size')
c.execute("UPDATE dtf_local.uploads SET complete=true,expires_at=now()+interval '30 days' WHERE id=%s", (uid,))
raise HTTPException(409, 'O envio do arquivo não chegou inteiro. Escolha o arquivo de novo.')
# Held while the cart is unpaid: an abandoned cart's files go after
# UNPAID_HOLD; a paid order keeps them for its 30 days (app/payments.py).
c.execute('UPDATE dtf_local.uploads SET complete=true,expires_at=now()+%s::interval WHERE id=%s',
(UNPAID_HOLD, uid))
return {'id': uid, 'complete': True}
# The browser's small picture of the artwork, for the Kanban. Only an image, and
# only a small one: the type is read from the bytes, never from the header.
THUMBNAIL_BYTES = 300_000
def thumbnail_type(data):
if data[:4] == b'RIFF' and data[8:12] == b'WEBP':
return 'image/webp'
if data[:3] == b'\xff\xd8\xff':
return 'image/jpeg'
if data[:8] == b'\x89PNG\r\n\x1a\n':
return 'image/png'
return None
def store_thumbnail(uid, session_id, mime, data):
rate_limit('upload-thumbnail', str(session_id), 120, 900)
with db.connect() as c:
upload_row(c, uid, session_id)
c.execute('''INSERT INTO dtf_local.upload_thumbnails(upload_id,mime,data) VALUES(%s,%s,%s)
ON CONFLICT(upload_id) DO UPDATE SET mime=EXCLUDED.mime, data=EXCLUDED.data, created_at=now()''',
(uid, mime, data))
@router.put('/api/uploads/{uid}/thumbnail')
async def put_thumbnail(uid: UUID, request: Request, session_id=Depends(owner)):
if int(request.headers.get('content-length') or 0) > THUMBNAIL_BYTES:
raise HTTPException(413, 'Thumbnail too large')
data = await request.body()
if len(data) > THUMBNAIL_BYTES:
raise HTTPException(413, 'Thumbnail too large')
mime = thumbnail_type(data)
if not mime:
raise HTTPException(415, 'Thumbnail must be a WebP, JPEG or PNG image')
await run_in_threadpool(store_thumbnail, uid, session_id, mime, data)
return {'id': uid}
@router.delete('/api/uploads/{uid}')
def cancel_upload(uid: UUID, session_id=Depends(owner)):
with db.connect() as c:
row=upload_row(c,uid,session_id,lock=True)
if row['complete']:
raise HTTPException(409, 'Completed upload cannot be cancelled')
raise HTTPException(409, 'Este arquivo já foi enviado e não pode ser cancelado.')
storage.discard(row['object_key'],row['multipart_id'],False)
c.execute('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s',(uid,))
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s',(uid,))
audit('upload_cancelled', upload=str(uid))
return {'id':uid,'cancelled':True}

336
app/api/users.py Normal file
View File

@@ -0,0 +1,336 @@
"""Kanban users and print machines, managed by the administrators.
An administrator creates each account with a first password and the person
changes it in "Minha senha". The superadmin is the system's own account, set from the console (python -m app.operators);
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
from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import Field, field_validator
from .. import machines, mail, observability
from ..core import db
from ..core.auth import (CAPABILITIES, audit, can, has, machine_bound, machine_question, may_move, may_reorder,
password_hash, password_matches, roles_of, signed_in)
from ..core.models import StrictModel
from ..runtime import BACK, ENVIRONMENT, STATES, TRANSITIONS
router = APIRouter()
class TinySeller(StrictModel):
id: int = Field(gt=0)
name: str = Field(min_length=1, max_length=120)
ASSIGNABLE = Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao']
class UserIn(StrictModel):
# The profiles an administrator may give; superadmin only comes from the console.
name: str = Field(min_length=1, max_length=80)
email: str = Field(min_length=3, max_length=254)
# 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
def email_valid(cls, value):
value = value.strip().lower()
if not re.fullmatch(r'[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}', value):
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)
products: list[Literal['textil', 'uv']] = Field(default_factory=list, max_length=2)
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)
@router.get('/api/operator/me')
def me(request: Request):
"""Who is signed in, and what the Kanban should offer them: the moves
their profile makes (forward, and the step back) and the columns whose
order they set."""
account = signed_in(request)
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(account),
'machine_answered': account['machine_answered'],
'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):
# None: "Não estou em máquina", for the profiles that may say so.
machine_id: UUID | None = None
# Taken while someone else is on it: a shift change, not a mistake.
confirm: bool = False
@router.post('/api/operator/me/machine')
def choose_session_machine(body: MachineAnswer, request: Request):
"""The machine this session works on (Dropstar's third round, item 12):
the operator's pulls go to it, and the history names it. Per session, so a
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(account)
if not question:
raise HTTPException(403, 'Seu perfil não trabalha em máquina.')
with db.connect() as c:
name = None
if body.machine_id is None:
if question == 'required':
raise HTTPException(422, 'Escolha a máquina em que você está.')
else:
row = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s AND active', (body.machine_id,)).fetchone()
if not row:
raise HTTPException(404, 'Máquina não encontrada ou desligada.')
name = row['name']
others = [r['who'] for r in c.execute('''SELECT DISTINCT COALESCE(NULLIF(o.name,''), o.email) AS who
FROM dtf_local.operator_sessions s JOIN dtf_local.operators o ON o.email=s.username AND o.active
WHERE s.machine_id=%s AND s.expires_at>now() AND s.username<>%s ORDER BY 1''',
(body.machine_id, account['email'])).fetchall()]
if others and not body.confirm:
raise HTTPException(409, f"{name} já tem {' e '.join(others)} ligado.")
c.execute('''UPDATE dtf_local.operator_sessions SET machine_id=%s, machine_at=CASE WHEN %s THEN now() END,
machine_answered=true WHERE token_hash=%s''', (body.machine_id, name is not None, account['session']))
audit('operator_machine_chosen', operator=account['email'], machine=name or '')
return {'machine': {'id': str(body.machine_id), 'name': name} if name else None}
@router.post('/api/operator/me/password')
def change_password(body: PasswordChange, request: Request):
account = signed_in(request)
with db.connect() as c:
row = c.execute('SELECT password_hash FROM dtf_local.operators WHERE id=%s', (account['id'],)).fetchone()
if not password_matches(body.current, row['password_hash']):
raise HTTPException(403, 'A senha atual não confere.')
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.new), account['id']))
audit('operator_password_changed', operator=account['email'])
return {'ok': True}
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.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
WHERE x.username=o.email AND x.expires_at>now()) AS seen_at
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_sessions s
ON s.username=o.email AND s.expires_at>now() AND s.machine_id IS NOT NULL
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
@router.get('/api/operator/users')
def list_users(user=Depends(can('users'))):
with db.connect() as c:
return {'users': user_rows(c), 'machines': machines.rows(c, with_operators=True)}
def target(c, uid, request):
"""The account to change, refusing a superadmin unless one is asking."""
row = c.execute('SELECT * FROM dtf_local.operators WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row:
raise HTTPException(404, 'Usuário não encontrado.')
if row['role'] == 'superadmin' and request.state.operator['role'] != 'superadmin':
raise HTTPException(403, 'Só o superadmin altera esta conta.')
return row
@router.post('/api/operator/users')
def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
if not body.password:
raise HTTPException(422, 'Defina uma senha inicial com 8 caracteres ou mais.')
uid = uuid4()
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.')
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)}
@router.post('/api/operator/users/{uid}')
def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('users'))):
me_ = request.state.operator
with db.connect() as c:
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
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.')
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']:
c.execute('UPDATE dtf_local.operator_sessions SET username=%s WHERE username=%s', (body.email, row['email']))
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='/'.join(roles), active=body.active,
password_reset=bool(body.password))
return {'ok': True}
@router.post('/api/operator/users/{uid}/delete')
def delete_user(uid: UUID, request: Request, user=Depends(can('users'))):
with db.connect() as c:
row = target(c, uid, request)
if str(row['id']) == str(request.state.operator['id']):
raise HTTPException(409, 'Você não pode excluir a sua própria conta.')
c.execute('DELETE FROM dtf_local.operator_sessions WHERE username=%s', (row['email'],))
c.execute('DELETE FROM dtf_local.operators WHERE id=%s', (uid,))
# The movement history keeps the e-mail of whoever moved each card.
audit('operator_deleted', operator=user, account=row['email'])
return {'ok': True}
def release_sessions(c, mid):
"""Whoever was on a machine switched off or deleted is asked again."""
c.execute('''UPDATE dtf_local.operator_sessions SET machine_id=NULL, machine_at=NULL, machine_answered=false
WHERE machine_id=%s''', (mid,))
@router.get('/api/operator/machines')
def list_machines(user=Depends(can('view'))):
with db.connect() as c:
return {'machines': machines.rows(c, with_operators=True)}
@router.post('/api/operator/machines')
def create_machine(body: MachineIn, user=Depends(can('users'))):
mid = uuid4()
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone():
raise HTTPException(409, 'Já existe uma máquina com este nome.')
c.execute('''INSERT INTO dtf_local.machines(id,name,products,active,limit_metres,places)
VALUES(%s,%s,%s,%s,%s,%s)''', (mid, body.name.strip(), sorted(set(body.products)), body.active,
body.limit_metres, body.places or machines.DEFAULT_PLACES))
audit('machine_created', operator=user, machine=body.name)
return {'id': str(mid)}
@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,
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)
audit('machine_updated', operator=user, machine=body.name)
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."""
with db.connect() as c:
if c.execute("SELECT 1 FROM dtf_local.orders WHERE machine_id=%s AND state='imp' AND cancelled_at IS NULL LIMIT 1",
(mid,)).fetchone():
raise HTTPException(409, 'Há pedido imprimindo nesta máquina. Termine ou mova o pedido antes de excluí-la.')
release_sessions(c, mid)
row = c.execute('DELETE FROM dtf_local.machines WHERE id=%s RETURNING name', (mid,)).fetchone()
if not row:
raise HTTPException(404, 'Máquina não encontrada.')
audit('machine_deleted', operator=user, machine=row['name'])
return {'ok': True}
@router.post('/api/operator/mail/test')
def test_mail(request: Request, user=Depends(can('integrations'))):
"""A message to whoever asked, to prove the mail server works."""
with db.connect() as c:
if not mail.queue(c, 'test', user, 'Teste de e-mail · Kanban DTF',
'Este é um teste do Kanban DTF. Se chegou, o envio de e-mails está funcionando: '
'os e-mails dos clientes.'):
raise HTTPException(409, 'O envio de e-mails não está configurado no servidor.')
audit('mail_test_queued', operator=user)
return {'ok': True, 'to': user}

View File

@@ -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, operator, orders, payments, quotes, uploads
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'):
@@ -37,12 +74,13 @@ async def safe_headers(request, call_next):
response = await call_next(request)
if response.status_code in (401,403,429) or response.status_code>=500:
audit('http_security_event', method=request.method, status=response.status_code, ip=client_ip(request))
response.headers['Cache-Control'] = 'no-store'
# Nothing is cached unless a route says so (the Kanban's artwork pictures).
response.headers.setdefault('Cache-Control', 'no-store')
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['Referrer-Policy'] = 'no-referrer'
return response
# Order is not significant: no two routers declare the same path.
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork):
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

@@ -9,8 +9,8 @@ from uuid import UUID, uuid4
from fastapi import HTTPException
from .printjobs import generated_identity
from .runtime import upload_row
from .runtime import upload_row, storage
from .printpng_validate import require_final_png
from .scanning import require_clean
@@ -21,55 +21,108 @@ def generated_owner(c, order, ref, kind):
from, and only while that item still has its original artwork: after a
customer correction it reproduces a layout nobody wants printed.
"""
generated = c.execute('''SELECT item_index FROM dtf_local.print_files
WHERE order_id=%s AND upload_id=%s AND status='ready' ''', (order['id'], ref.upload_id)).fetchone()
generated = c.execute('''SELECT p.item_index FROM dtf_local.print_parts p JOIN dtf_local.print_files f
ON f.order_id=p.order_id AND f.item_index=p.item_index
WHERE p.order_id=%s AND p.upload_id=%s AND f.status='ready' ''', (order['id'], ref.upload_id)).fetchone()
if not generated:
return None
if kind != 'final' or generated['item_index'] != ref.item_index:
raise HTTPException(422, 'A generated print file can only be the final file of its own item')
raise HTTPException(422, 'O arquivo gerado só pode ser o final do próprio item.')
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1",
(order['id'],)).fetchone():
raise HTTPException(409, 'A customer correction replaced the artwork this file was generated from')
return generated_identity(order['id'])
raise HTTPException(409, 'O cliente enviou uma correção depois que este arquivo foi gerado. Use a correção ou envie outro arquivo.')
return c.execute('SELECT owner FROM dtf_local.uploads WHERE id=%s', (ref.upload_id,)).fetchone()['owner']
def correction_owner(c, order, ref, kind):
"""The owner of a customer correction approved as it is, or None if it is not one.
A corrected file is often ready to print: the operator approves it as the
final of the item it corrects, without downloading and sending it back.
"""
if kind != 'final':
return None
row = c.execute('''SELECT u.owner FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id
WHERE f.order_id=%s AND f.upload_id=%s AND f.kind='correction' AND f.active AND f.item_index=%s''',
(order['id'], ref.upload_id, ref.item_index)).fetchone()
return row and row['owner']
def submit_files(c, order, body, identity, kind, actor):
if order['version'] != body.version:
raise HTTPException(409, 'Order changed. Refresh before submitting files.')
if kind == 'final' and order['state'] not in ('rec','tra','cor'):
raise HTTPException(409, 'Final files can only change during artwork review')
raise HTTPException(409, 'O pedido mudou. Atualize a página e envie de novo.')
# Arte conferida is the print queue (2026-10-23): what is in it keeps its finals.
if kind == 'final' and order['state'] not in ('rec','cor'):
raise HTTPException(409, 'O arquivo final só muda antes de Arte conferida, a fila. Volte o pedido para Arte recebida para trocar.')
if kind == 'correction' and order['state'] != 'cor':
raise HTTPException(409, 'This order is not awaiting artwork correction')
raise HTTPException(409, 'Este pedido não está esperando correção.')
if len({f.upload_id for f in body.files}) != len(body.files):
raise HTTPException(422, 'Each uploaded file must appear once')
raise HTTPException(422, 'O mesmo arquivo foi enviado duas vezes.')
count = len(order['snapshot']['items'])
if any(f.item_index >= count for f in body.files):
raise HTTPException(422, 'Invalid order item')
raise HTTPException(422, 'Item do pedido inválido.')
if kind == 'final' and {f.item_index for f in body.files} != set(range(count)):
raise HTTPException(422, 'Final-file set must cover every order item')
raise HTTPException(422, 'Envie um arquivo final para cada item do pedido.')
original_ids = [UUID(uid) for item in order['snapshot']['items'] for uid in item['uploads']]
first = c.execute('SELECT min(created_at) AS first FROM dtf_local.uploads WHERE id=ANY(%s)', (original_ids,)).fetchone()['first']
expiry = first + timedelta(days=30)
if expiry <= datetime.now(timezone.utc):
raise HTTPException(410, 'Order artwork retention has expired')
raise HTTPException(410, 'Os arquivos deste pedido expiraram (30 dias).')
# A final already approved for its item may stay as it is beside a new
# one for another item: "Tratar a arte" replaces only the item treated
# (Dropstar, 2026-10-29). Something has to change, though.
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()
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:
upload = upload_row(c, ref.upload_id, generated_owner(c, order, ref, kind) or identity, lock=True)
if ref.upload_id in kept:
continue
corrected = correction_owner(c, order, ref, kind)
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, 'Complete all uploads first')
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar.')
require_clean(upload)
if c.execute('SELECT id FROM dtf_local.order_files WHERE upload_id=%s', (ref.upload_id,)).fetchone():
raise HTTPException(409, 'File is already attached. Upload a new revision.')
if kind == 'final':
require_final_png(storage, upload)
# 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.
if kind == 'correction':
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 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
c.execute('INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by) VALUES(%s,%s,%s,%s,%s,%s,%s)',
(uuid4(),order['id'],ref.upload_id,ref.item_index,kind,body.note,actor))
c.execute('UPDATE dtf_local.uploads SET expires_at=LEAST(expires_at,%s) WHERE id=%s', (expiry,ref.upload_id))
# The order's window, whatever the upload's own hold was.
c.execute('UPDATE dtf_local.uploads SET expires_at=%s WHERE id=%s', (expiry,ref.upload_id))
c.execute('UPDATE dtf_local.orders SET version=version+1,updated_at=now() WHERE id=%s', (order['id'],))
if kind == 'final':
# Artwork approval, not commercial quote approval, starts original cleanup.
c.execute("UPDATE dtf_local.uploads SET expires_at=LEAST(expires_at,now()+interval '7 days') WHERE id=ANY(%s)", (original_ids,))
# An original approved as its own print file is kept as the final.
finals = [ref.upload_id for ref in body.files]
c.execute("UPDATE dtf_local.uploads SET expires_at=LEAST(expires_at,now()+interval '7 days') WHERE id=ANY(%s) AND NOT id=ANY(%s)",
(original_ids, finals))
return {'ok': True, 'version': order['version']+1, 'expires_at': expiry}

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

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,17 +42,22 @@ 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)))
c.execute(sql.SQL('GRANT SELECT,INSERT,UPDATE,DELETE ON ALL TABLES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
c.execute(sql.SQL('GRANT USAGE,SELECT ON ALL SEQUENCES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
# The order identity sequence is never reset: DTF-1…DTF-15 already
# exist as Tiny order numbers (Dropstar, 2026-11-05).
# Turn the configured credential into a real account so an existing
# deployment keeps logging in exactly as before. Inserts only when that
# email is absent, so a password changed with local.operators is never
# 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}

113
app/catalog.py Normal file
View File

@@ -0,0 +1,113 @@
"""What the Site sells and at what price, edited in the Kanban's Site tab.
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 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 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 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 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',
'premium': 'Têxtil Premium · 8 passadas',
'tratamento': 'Ajuste Fino',
'redesenho': 'Ajuste Fino Redesenho',
}
UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro',
'premium': 'metro', 'tratamento': 'arte', 'redesenho': 'arte'}
def fallback_cents(product: str) -> int:
"""The price in the code, used until a row in the database takes over.
Redesenho has no price in the code: it starts disabled and unpriced, and
Gestão sets both in the Site tab."""
if product == 'tratamento':
return pricing.treatment_cents()
if product == 'redesenho':
return 0
return pricing.PRICES[product]
def band_price(base_cents: int, bands: list, quantity: Decimal) -> int:
"""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 quantity >= start and (best is None or start >= best):
best = start
price = band['unit_cents']
return price
def current(c) -> dict:
"""{'file': {'enabled': bool, 'unit_cents': int, 'bands': [...]}, ...}."""
enabled = {row['id']: row['enabled'] for row in
c.execute('SELECT id, enabled FROM dtf_local.products').fetchall()}
prices = {row['product']: row for row in c.execute('''
SELECT DISTINCT ON (product) product, unit_cents, bands
FROM dtf_local.product_prices
WHERE starts_at <= now()
ORDER BY product, starts_at DESC, id DESC''').fetchall()}
return {product: {'enabled': bool(enabled.get(product, True)),
'unit_cents': prices[product]['unit_cents'] if product in prices else fallback_cents(product),
'bands': prices[product]['bands'] if product in prices else []}
for product in PRODUCTS}
def unit_cents(c, product: str) -> int:
"""The current base price of one product, or the fallback."""
row = c.execute('''SELECT unit_cents FROM dtf_local.product_prices
WHERE product=%s AND starts_at <= now()
ORDER BY starts_at DESC, id DESC LIMIT 1''', (product,)).fetchone()
return row['unit_cents'] if row else fallback_cents(product)
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'], 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:
"""Refuse a product someone switched off in the Kanban's Site tab."""
# Imported here so the pure helpers above load without the web framework
# (tests/test_pricing.py runs on the host, where FastAPI is not installed).
from fastapi import HTTPException
row = c.execute('SELECT enabled FROM dtf_local.products WHERE id=%s', (product,)).fetchone()
if row and not row['enabled']:
raise HTTPException(422, 'Este produto não está à venda agora.')

102
app/cnpj.py Normal file
View File

@@ -0,0 +1,102 @@
"""The company name behind a customer's CNPJ, from the public registry.
The Site asks for e-mail, CNPJ and WhatsApp only, so the Kanban showed an
e-mail where a name belongs, and a new Tiny contact was named after it. The
Receita's CNPJ registry is public, and BrasilAPI serves it without a key.
Names are looked up by the worker, never while a customer waits, and kept in
dtf_local.cnpj_names; a lookup that fails is tried again a day later.
"""
import os
import httpx
API = os.environ.get('CNPJ_LOOKUP_URL', 'https://brasilapi.com.br/api/cnpj/v1/')
# A few per minute of the worker's time is plenty: customers repeat.
PER_RUN = 5
def digits(value):
return ''.join(ch for ch in str(value or '') if ch.isdigit())
def fetch(cnpj, transport=None):
"""The registry's names for one CNPJ. An unknown CNPJ has none, and is not asked again."""
with httpx.Client(timeout=8, transport=transport) as http:
response = http.get(API + cnpj, headers={'Accept': 'application/json', 'User-Agent': 'dtf-sistema'})
if response.status_code == 404:
return {'legal_name': None, 'trade_name': None}
response.raise_for_status()
data = response.json()
clean = lambda value: ' '.join(str(value).split()) or None if value else None
return {'legal_name': clean(data.get('razao_social')), 'trade_name': clean(data.get('nome_fantasia'))}
def pending(c, limit):
"""CNPJs of orders and recent quotes never looked up, or whose lookup failed a day ago."""
return [row['cnpj'] for row in c.execute('''WITH seen AS (
SELECT regexp_replace(snapshot->'customer'->>'cnpj', '\\D', '', 'g') AS cnpj, created_at FROM dtf_local.orders
UNION ALL
SELECT regexp_replace(draft->'customer'->>'cnpj', '\\D', '', 'g'), created_at FROM dtf_local.quotes
WHERE created_at > now() - interval '3 days')
SELECT s.cnpj FROM seen s LEFT JOIN dtf_local.cnpj_names n ON n.cnpj=s.cnpj
WHERE length(s.cnpj)=14 AND (n.cnpj IS NULL OR (n.fetched_at IS NULL AND n.failed_at < now() - interval '1 day'))
GROUP BY s.cnpj ORDER BY max(s.created_at) DESC LIMIT %s''', (limit,)).fetchall()]
def store(c, cnpj, found):
c.execute('''INSERT INTO dtf_local.cnpj_names(cnpj,legal_name,trade_name,fetched_at) VALUES(%s,%s,%s,now())
ON CONFLICT (cnpj) DO UPDATE SET legal_name=EXCLUDED.legal_name, trade_name=EXCLUDED.trade_name,
fetched_at=now(), failed_at=NULL''', (cnpj, found['legal_name'], found['trade_name']))
def failed(c, cnpj):
c.execute('''INSERT INTO dtf_local.cnpj_names(cnpj,failed_at) VALUES(%s,now())
ON CONFLICT (cnpj) DO UPDATE SET failed_at=now()''', (cnpj,))
def resolve(connect, limit=PER_RUN, transport=None):
"""Look up the next few CNPJs; returns how many were found."""
with connect() as c:
cnpjs = pending(c, limit)
found = 0
for cnpj in cnpjs:
try:
names = fetch(cnpj, transport)
except (httpx.HTTPError, ValueError):
with connect() as c:
failed(c, cnpj)
continue
with connect() as c:
store(c, cnpj, names)
found += 1
return found
def names(c, cnpjs):
"""{cnpj: {'legal': ..., 'trade': ...}} for the CNPJs already found."""
wanted = sorted({digits(value) for value in cnpjs} - {''})
if not wanted:
return {}
rows = c.execute('''SELECT cnpj,legal_name,trade_name FROM dtf_local.cnpj_names
WHERE cnpj=ANY(%s) AND (legal_name IS NOT NULL OR trade_name IS NOT NULL)''', (wanted,)).fetchall()
return {row['cnpj']: {'legal': row['legal_name'], 'trade': row['trade_name']} for row in rows}
def company(cnpj, connect=None, transport=None):
"""One CNPJ's names for a Tiny contact: stored, or looked up now. None if unavailable."""
if connect is None:
from .core.db import connect
cnpj = digits(cnpj)
if len(cnpj) != 14: # a CPF: a person, not in the company registry
return None
with connect() as c:
known = names(c, [cnpj]).get(cnpj)
if known:
return known
try:
found = fetch(cnpj, transport)
except (httpx.HTTPError, ValueError):
return None
with connect() as c:
store(c, cnpj, found)
return {'legal': found['legal_name'], 'trade': found['trade_name']} if any(found.values()) else 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
@@ -45,7 +48,7 @@ def session_row(request):
try:
sid = UUID(request.cookies.get('dtf_session', ''))
except ValueError:
raise HTTPException(401, 'Start a local session first')
raise HTTPException(401, 'Sessão não iniciada. Recarregue a página.')
with connect() as c:
row = c.execute('SELECT * FROM dtf_local.sessions WHERE id=%s AND expires_at>now()', (sid,)).fetchone()
if not row:
@@ -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()
@@ -92,7 +111,7 @@ def rate_limit(scope, identity, limit, seconds=900):
RETURNING attempts""", (key,seconds,seconds)).fetchone()
if row['attempts'] > limit:
audit('rate_limit', scope=scope)
raise HTTPException(429, 'Too many requests. Try again later.', headers={'Retry-After':str(seconds)})
raise HTTPException(429, 'Muitas tentativas. Tente de novo mais tarde.', headers={'Retry-After':str(seconds)})
ACCOUNT_FAILURES = 10
@@ -108,19 +127,199 @@ def throttle(email, request):
WHERE key=%s AND started_at >= now()-interval '900 seconds'""", (key,)).fetchone()
if row and row['attempts'] >= ACCOUNT_FAILURES:
audit('rate_limit', scope='auth-account')
raise HTTPException(429, 'Too many requests. Try again later.', headers={'Retry-After': '900'})
raise HTTPException(429, 'Muitas tentativas. Tente de novo mais tarde.', headers={'Retry-After': '900'})
def login_failed(email):
"""Count a failed sign-in (or registration attempt) against the account."""
rate_limit('auth-account', email, 1_000_000)
def operator(request: Request):
# What each Kanban profile may do. "view" is reading; "produce" handles the
# artwork: approving the final files, the contraction, "Tratar a arte", the
# contact wait. "The designer approves every file" (Dropstar's rule D-16), so
# the operator does not: they pull and print. "print" is the print room's side
# of it (the machine, the
# queue's order, its files and folder); "manage" covers quotes, cancellations
# and payments; "users" is the Usuários page; "integrations" is everything in
# Integrações but the print room's folder (connecting Tiny, the checks, the
# 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', 'expedicao')
CAPABILITIES = {
'view': set(ROLES),
'produce': {'superadmin', 'admin', 'gestao', 'designer'},
'print': {'superadmin', 'admin', 'gestao', 'operador'},
'manage': {'superadmin', 'admin', 'gestao'},
# Registering an order paid outside the system, from its Site quote (D-35).
# Not the seller: Vendedor only views the board (D-30).
'enter': {'superadmin', 'admin', 'gestao'},
# Rework (D-02): coordination opens it with its cause, an Administrador
# (Thales or Alexandre) authorizes it.
'rework': {'superadmin', 'gestao'},
'authorize': {'superadmin', 'admin'},
'users': {'superadmin', 'admin'},
'integrations': {'superadmin'},
# Financeiro (Dropstar, 2026-10-30): sees the board, Pagamentos, Números and
# Cotações, and cancels an order with its reason; moves no card, touches no
# file. Resolving a payment stays with "manage".
'payments': {'superadmin', 'admin', 'gestao', 'financeiro'},
'cancel': {'superadmin', 'admin', 'gestao', 'financeiro'},
# Prova OK or reprovada, on the proof card only (Dropstar, 2026-11-03): the
# seller, who otherwise only views, Gestão and the administrators.
'proof': {'superadmin', 'admin', 'gestao', 'vendedor'},
# "Retirado" at the counter (Dropstar's third round, item 14): everyone
# but the seller, who only views (D-30). It includes everyone who produces,
# and the operator, so an operator upload (artwork.py) takes it for its parts.
'deliver': {'superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor'},
# 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
# 2026-10-26): the designer the artwork, the operator the printing, and the
# Revisor to Finalizado, so nobody in the room releases their own print (D-29);
# Admin, Dropstar's own login, may release too (the user, 2026-10-28), and we,
# the superadmin, for support. Gestão, the coordination, pulls back and
# never forward, always with a reason (D-20): a step back, or Correção. Admin,
# Dropstar's own login, makes every other move. A step back undoes a mistaken
# move: open to whoever may make the move it undoes.
MOVES = {
'designer': {('rec', 'tra'), ('rec', 'cor'), ('tra', 'cor'), ('cor', 'rec'), ('cor', 'tra')},
'operador': {('tra', 'imp'), ('imp', 'rev')},
'revisor': {('rev', 'fin')},
}
ADMINS = ('superadmin', 'admin')
COORDINATION = ('gestao',)
MANAGERS = ADMINS + COORDINATION
RELEASERS = ('revisor', 'admin', 'superadmin')
# Who is asked "Em qual máquina você está?" after signing in (Dropstar, 2026-10-30):
# the operator must answer; Gestão and the administrators may say they are on
# none. The other profiles are never asked.
MACHINE_QUESTION = {'operador': 'required', 'gestao': 'optional', 'admin': 'optional'}
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 (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':
return role in RELEASERS
if to_state == 'cor' and role in COORDINATION:
return True
return role in ADMINS or (from_state, to_state) in MOVES.get(role, ())
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 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):
"""The operator behind this session, active, with the profile read now: a
role changed or an account disabled takes effect on the next request."""
token = request.cookies.get('dtf_operator', '')
if not token or len(token)>128:
raise HTTPException(401, 'Sign in to the local Kanban')
raise HTTPException(401, 'Entre no Kanban.')
digest = hashlib.sha256(token.encode()).hexdigest()
with connect() as c:
row = c.execute('SELECT username FROM dtf_local.operator_sessions WHERE token_hash=%s AND expires_at>now()', (digest,)).fetchone()
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
WHERE s.token_hash=%s AND s.expires_at>now()''', (digest,)).fetchone()
if row:
# When the session was last used, for "Ativo agora" in Usuários:
# written at most once a minute, not on every request.
c.execute('''UPDATE dtf_local.operator_sessions SET seen_at=now()
WHERE token_hash=%s AND (seen_at IS NULL OR seen_at<now()-interval '1 minute')''', (digest,))
if not row:
raise HTTPException(401, 'Operator session expired')
return row['username']
raise HTTPException(401, 'Sua sessão expirou. Entre de novo.')
# The machine this session works on (item 12), or None.
machine_id, machine_name = row.pop('machine_id'), row.pop('machine_name')
row['machine'] = {'id': str(machine_id), 'name': machine_name} if machine_id else None
row['session'] = digest
request.state.operator = row
return row
def can(capability):
"""A dependency that lets through the profiles allowed to do this, and
returns the operator's e-mail, as the routes record it."""
def check(request: Request):
account = signed_in(request)
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
operator = can('view')

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

@@ -1,13 +1,13 @@
"""Limits shared by upload admission and the malware scanner."""
import os
CLAMAV_STREAM_MAX_BYTES = 128 * 1024 * 1024 # infra/clamd.conf
CLAMAV_STREAM_MAX_BYTES = 2000 * 1024 * 1024 # infra/clamd.conf StreamMaxLength
def scan_limit_bytes():
return min(CLAMAV_STREAM_MAX_BYTES, int(os.environ.get('SCAN_MAX_BYTES', '134217728')))
"""The largest file ClamAV scans; above it the format check releases it."""
return min(CLAMAV_STREAM_MAX_BYTES, int(os.environ.get('SCAN_MAX_BYTES', str(CLAMAV_STREAM_MAX_BYTES))))
def upload_limit_bytes():
transport = int(os.environ.get('MAX_UPLOAD_BYTES', '5368709120'))
return min(transport, scan_limit_bytes())
return int(os.environ.get('MAX_UPLOAD_BYTES', str(4 * 1024 ** 3)))

View File

@@ -1,4 +1,5 @@
import re
from datetime import date, datetime
from decimal import Decimal
from typing import Literal
from uuid import UUID
@@ -7,22 +8,48 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
class StrictModel(BaseModel):
model_config = ConfigDict(extra='forbid', allow_inf_nan=False)
def check_digit(base, weights):
rem = sum(int(n) * w for n, w in zip(base, weights)) % 11
return 0 if rem < 2 else 11 - rem
def cpf_ok(digits):
return (len(digits) == 11 and len(set(digits)) > 1
and check_digit(digits[:9], range(10, 1, -1)) == int(digits[9])
and check_digit(digits[:10], range(11, 1, -1)) == int(digits[10]))
def cnpj_ok(digits):
return (len(digits) == 14 and len(set(digits)) > 1
and check_digit(digits[:12], [5,4,3,2,9,8,7,6,5,4,3,2]) == int(digits[12])
and check_digit(digits[:13], [6,5,4,3,2,9,8,7,6,5,4,3,2]) == int(digits[13]))
def person_name(value):
"""A name as typed, with its spaces tidied; at least two letters when given."""
name = ' '.join(str(value or '').split())
if name and sum(ch.isalpha() for ch in name) < 2:
raise ValueError('Invalid name')
return name
class Customer(StrictModel):
# The customer's CPF or CNPJ, digits only. The key keeps the name it had
# when only companies bought, as stored orders, quotes and accounts use it.
cnpj: str
zap: str
mail: str = Field(max_length=254)
# Who to greet: the Tiny contact and the WhatsApp notices use it. Empty in
# orders placed before the Site asked for it.
name: str = Field(default='', max_length=80)
@field_validator('name')
@classmethod
def name_valid(cls, value):
return person_name(value)
@field_validator('cnpj')
@classmethod
def cnpj_valid(cls, value):
def document_valid(cls, value):
digits = re.sub(r'\D', '', value)
if len(digits) != 14 or len(set(digits)) == 1 or not digits.isascii():
raise ValueError('Invalid CNPJ')
def check(base, weights):
rem = sum(int(n) * w for n,w in zip(base, weights)) % 11
return 0 if rem < 2 else 11-rem
if check(digits[:12], [5,4,3,2,9,8,7,6,5,4,3,2]) != int(digits[12]) or check(digits[:13], [6,5,4,3,2,9,8,7,6,5,4,3,2]) != int(digits[13]):
raise ValueError('Invalid CNPJ')
if not digits.isascii() or not (cpf_ok(digits) or cnpj_ok(digits)):
raise ValueError('Invalid CPF or CNPJ')
return digits
@field_validator('zap')
@@ -41,9 +68,21 @@ class Customer(StrictModel):
return value.strip()
class Freight(StrictModel):
service: Literal['pickup','mock-standard'] = 'pickup'
service: Literal['pickup','mock-standard','jadlog','pac','sedex'] = 'pickup'
postal_code: str = Field(default='', max_length=8)
class FreightEstimate(Freight):
"""The cart's estimate. The charged freight is quoted again by the server
from the approved items, never from these numbers."""
metres: Decimal | None = Field(default=None, gt=0, le=12000)
declared_cents: int = Field(default=0, ge=0, le=100_000_000, strict=True)
class FreightAsk(StrictModel):
"""Every delivery option for the cart's package to a CEP."""
postal_code: str = Field(pattern=r'^[0-9]{8}$')
metres: Decimal = Field(gt=0, le=12000)
declared_cents: int = Field(default=0, ge=0, le=100_000_000, strict=True)
UF = Literal['AC','AL','AP','AM','BA','CE','DF','ES','GO','MA','MT','MS','MG','PA','PB',
'PR','PE','PI','RJ','RN','RS','RO','RR','SC','SP','SE','TO']
@@ -88,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)
@@ -99,28 +143,120 @@ class ProductionPlacement(StrictModel):
rotation_degrees: Literal[0, 90, 180, 270]
mirrored: bool
# The layout rule an order was packed with. 2: pieces 5 mm apart on a 5 mm grid,
# no margins. 3 (Dropstar, 2026-10-21): 5 mm margins top and bottom and between
# rows, and across the width 5 mm or the space left shared out equally.
PRODUCTION_VERSIONS = (2, 3)
class ProductionSpec(StrictModel):
version: Literal[2]
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):
"""One sheet of loose art the Site split by contraction class (item 17,
Dropstar 2026-10-30): fine lines (C1, C2) on one sheet, thick (C3) on
another, each its own item and print file, billed together."""
group: str = Field(pattern=r'^[a-z0-9]{1,16}$')
part: int = Field(ge=1, le=10, strict=True)
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 = {}
for item in items:
if item.split:
groups.setdefault(item.split.group, []).append(item)
for parts in groups.values():
of = parts[0].split.of
if sorted(item.split.part for item in parts) != list(range(1, of + 1)) or \
any(item.split.of != of or item.mode != parts[0].mode for item in parts):
raise ValueError('Split sheets must list each part once, of one product')
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)
stroke_class: Literal['C1', 'C2', 'C3'] | None = None
# A sheet with fine lines and solid areas (item 16): the customer kept the
# measure (protect the fine lines) or chose to protect the solid areas (C3).
stroke_choice: Literal['measured', 'client_c3'] | None = None
# Where the thinnest stroke sits in the assembled film, from 0 (top) to 1
# (bottom): the proof card crops a 15 cm window around it (Dropstar, 05/11).
proof_y_fraction: Decimal | None = Field(default=None, ge=0, le=1)
# The lowest source resolution the server measured, for the Prumo report
# (Dropstar, 05/11). None when the format cannot be measured.
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')
film_width = Decimal('28.5') if self.mode in ('uvfile', 'uv') else Decimal('57')
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:
raise ValueError('Production film width does not match the product')
for source in self.production.sources:
@@ -128,6 +264,11 @@ 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')
expected={(index,copy) for index,source in enumerate(self.production.sources)
for copy in range(source.copies)}
placed=set()
@@ -154,12 +295,89 @@ class Item(StrictModel):
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: a value out of range
(a cart left open for hours, DTF-WEB-9) is dropped, never refused.
"""
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):
request_key: UUID
customer: Customer
items: list[Item] = Field(min_length=1, max_length=30)
freight: Freight
destination: Destination | None = None
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
proof: 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).
timings: ClientTimings | None = None
@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')
def destination_matches_freight(self):
@@ -172,9 +390,55 @@ 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):
quote_id: UUID
@@ -184,13 +448,23 @@ class PaymentMethod(StrictModel):
# in the browser; the number never reaches this server.
token: str | None = Field(default=None, max_length=200)
payment_method_id: str | None = Field(default=None, max_length=40, pattern=r'^[a-z_]+$')
installments: int = Field(default=1, ge=1, le=12, strict=True)
# 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 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}$')
@model_validator(mode='after')
def card_needs_token(self):
if self.type == 'card' and not (self.token and self.payment_method_id):
raise ValueError('Card payment requires the provider token and method')
# The store takes credit cards and PIX only. Mercado Pago's debit
# methods are debvisa, debmaster, debelo...; the adapter still knows
# how to pay one, should debit be offered again.
if self.type == 'card' and self.payment_method_id.startswith('deb'):
raise ValueError('Só aceitamos cartão de crédito ou PIX.')
return self
class PaymentIntent(StrictModel):
@@ -198,16 +472,151 @@ class PaymentIntent(StrictModel):
method: PaymentMethod
class Move(StrictModel):
state: Literal['rec','tra','fil','imp','cor','fin']
state: Literal['rec','tra','imp','cor','rev','fin']
version: int = Field(ge=0)
reason: str = Field(default='', max_length=1000)
# Pulled into Imprimindo onto a machine's lane: the machine it prints on.
machine_id: UUID | None = None
class MachineEntry(StrictModel):
"""One thing entered into a machine (Fase 2, front 1a, app/machine_log.py)."""
kind: Literal['supply', 'part', 'event']
item: str = Field(min_length=1, max_length=40)
quantity: Decimal | None = Field(default=None, gt=0, le=999999, decimal_places=3)
cost_cents: int | None = Field(default=None, ge=0, le=10**12, strict=True)
serial: str | None = Field(default=None, max_length=200)
note: str | None = Field(default=None, max_length=1000)
stop_minutes: int | None = Field(default=None, gt=0, le=100000, strict=True)
from_alert: bool = False
class MachineSheet(StrictModel):
"""The machine's own data, typed by Gestão: cost, start and supply minimums."""
price_cents: int | None = Field(default=None, ge=0, le=10**12, strict=True)
installed_on: date | None = None
minimums: dict[str, Decimal | None] = Field(default_factory=dict)
class SiteProductToggle(StrictModel):
"""Ligar ou desligar um produto na aba Site (Fase 2, front 8)."""
enabled: bool
class PriceBand(StrictModel):
"""Uma faixa por metragem: a partir de X m, o metro passa a custar Y."""
from_metres: Decimal
unit_cents: int = Field(strict=True)
class SitePriceNew(StrictModel):
"""Um novo preço e a data em que começa; sem data, começa agora."""
unit_cents: int = Field(ge=0, le=10000000, strict=True)
starts_at: datetime | None = None
# As faixas viajam com o preço (front 8.2); vazio é o preço único.
bands: list[PriceBand] = Field(default_factory=list)
class CouponNew(StrictModel):
"""Um cupom novo, criado na aba Site (front 8.3)."""
code: str = Field(min_length=1, max_length=30)
kind: Literal['percent', 'per_metre']
value: int = Field(gt=0, le=10000000, strict=True)
valid_from: datetime | None = None
valid_until: datetime | None = None
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', 'premium'] | None = None
note: str = Field(default='', max_length=1000)
class CouponUpdate(StrictModel):
"""Os campos de um cupom que podem mudar; o código fica como foi criado."""
kind: Literal['percent', 'per_metre'] | None = None
value: int | None = Field(default=None, gt=0, le=10000000, strict=True)
valid_from: datetime | None = None
valid_until: datetime | None = None
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', '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.
value: Literal['C1', 'C2', 'C3'] | None = None
class Resolution(StrictModel):
note: str = Field(min_length=3, max_length=1000)
class Register(StrictModel):
customer: Customer
password: str = Field(min_length=12, max_length=128)
password: str = Field(min_length=8, max_length=128)
class ProfileUpdate(StrictModel):
"""What a customer may change about their account; the CPF/CNPJ is not among it."""
zap: str
address: Destination | None = None
name: str | None = Field(default=None, max_length=80)
@field_validator('name')
@classmethod
def name_valid(cls, value):
return None if value is None else person_name(value)
@field_validator('zap')
@classmethod
def phone_valid(cls, value):
digits = re.sub(r'\D', '', value)
if len(digits) not in (10,11) or not digits.isascii():
raise ValueError('Invalid phone')
return digits
class EmailChange(StrictModel):
email: str = Field(max_length=254)
password: str = Field(min_length=1, max_length=128)
@field_validator('email')
@classmethod
def email_valid(cls, value):
value = value.strip().lower()
if not re.fullmatch(r'[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}', value):
raise ValueError('Invalid email')
return value
class PasswordChange(StrictModel):
current: str = Field(min_length=1, max_length=128)
new: str = Field(min_length=8, max_length=128)
class SignupCode(StrictModel):
signup: UUID
code: str = Field(pattern=r'^[0-9]{6}$')
class SignupResend(StrictModel):
signup: UUID
class EmailCode(StrictModel):
change: UUID
code: str = Field(pattern=r'^[0-9]{6}$')
class EmailResend(StrictModel):
change: UUID
class ForgotPassword(StrictModel):
email: str = Field(min_length=3, max_length=254)
class PasswordReset(StrictModel):
token: str = Field(min_length=20, max_length=100, pattern=r'^[A-Za-z0-9_-]+$')
password: str = Field(min_length=8, max_length=128)
class Login(StrictModel):
email: str = Field(min_length=3, max_length=254)
@@ -233,3 +642,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

@@ -1,27 +1,98 @@
"""Exact approved Site DTF price ladders; integer BRL cents at the boundary.
"""Dropstar's single price per metre for each product; integer BRL cents at the boundary.
Quantity/grade must be supplied by an authenticated commercial reviewer.
This module does not inspect artwork or perform pre-flight.
One price per product (Dropstar, 2026-10-23). The grade is still recorded with
each item, for the customer and the print room, but it no longer changes the
price. This module does not inspect artwork or perform pre-flight.
"""
import os
import re
from decimal import Decimal, ROUND_CEILING
TIERS = {
'file': [(90,1490),(75,1620),(60,1750),(40,1870),(0,1990)],
'avulsa': [(90,2490),(75,2620),(60,2750),(40,2870),(0,2990)],
'uvfile': [(90,6990),(75,7390),(60,7790),(40,8190),(0,8590)],
'uv': [(90,8390),(75,8790),(60,9190),(40,9590),(0,9990)],
}
PRICES = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990, 'premium': 3990}
def price(mode: str, metres: str, grade: int) -> dict:
# 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
# when the business sets it, to make the formats the robot reads the cheaper
# path. Zero adds nothing.
MANUAL_FORMATS = re.compile(r'\.(cdr|ai|psd|psb|tiff?)$', re.I)
def manual_extra_cents() -> int:
value = int(os.environ.get('MANUAL_FILE_EXTRA_CENTS', '0') or 0)
if not 0 <= value <= 100000:
raise ValueError('MANUAL_FILE_EXTRA_CENTS must be between 0 and 100000')
return value
def treatment_cents() -> int:
"""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`.
"""
value = int(os.environ.get('TREATMENT_CENTS', '0') or 0)
if not 0 <= value <= 1000000:
raise ValueError('TREATMENT_CENTS must be between 0 and 1000000')
return value
def is_manual(item, names) -> bool:
"""Whether a finished-sheet item has a file someone must open by hand: one
the customer measured, or one in a format the Site cannot read."""
return any(source['kind'] == 'sheet' and (source['measurement'] == 'customer' or
MANUAL_FORMATS.search(names.get(str(source['upload_id']), '')))
for source in item['production']['sources'])
def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Decimal = Decimal('1'),
unit_cents: int | None = None) -> dict:
"""The item's charge. The grade is validated and kept with the item; the
price does not depend on it. A split sheet has no minimum of its own: its
group has one (bill_splits). `unit_cents` is the current price from the
database (app/catalog.py); without it, the table above."""
length = Decimal(str(metres))
if mode not in TIERS or not length.is_finite() or not 0 < length <= 12000:
if mode not in PRICES or not length.is_finite() or not 0 < length <= 12000:
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(Decimal('1'), (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10)
unit = next(cents for minimum, cents in TIERS[mode] if grade >= minimum)
return {'mode': mode, 'metres': str(length), 'grade': grade,
'billed_metres': str(billed), 'unit_cents': unit,
'total_cents': int(billed * unit),
'discount_cents': int(billed * (TIERS[mode][-1][1] - unit))}
billed = max(minimum, (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10)
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
priced = {'mode': mode, 'metres': str(length), 'grade': grade,
'billed_metres': str(billed), 'unit_cents': unit,
'total_cents': int(billed * unit)}
if extra_cents:
priced['manual_extra_cents'] = extra_cents
return priced
def bill_splits(priced: list) -> list:
"""The order minimum of 1 m once per split group, on its first sheet: the
customer did not choose the split (item 17), so it never costs a metre more."""
for group in dict.fromkeys(i['split']['group'] for i in priced if i.get('split')):
parts = [i for i in priced if (i.get('split') or {}).get('group') == group]
short = Decimal('1') - sum(Decimal(i['billed_metres']) for i in parts)
if short > 0:
first = min(parts, key=lambda i: i['split']['part'])
billed = Decimal(first['billed_metres']) + short
first.update(billed_metres=str(billed), total_cents=int(billed * first['unit_cents']))
return priced
def apply_bands(priced: list, unit_by_mode: dict) -> list:
"""Rewrite the items of each mode to the band price for the order's total
metres of that product (front 8.2). The manual-file extra stays on top of
each item; a mode absent from `unit_by_mode` is untouched."""
for item in priced:
if item['mode'] in unit_by_mode:
unit = unit_by_mode[item['mode']] + item.get('manual_extra_cents', 0)
item['unit_cents'] = unit
item['total_cents'] = int(Decimal(str(item['billed_metres'])) * unit)
return priced
def sheet_label(item: dict) -> str:
"""' · folha 1 de 2' on a split sheet (item 17), for the customer's lists."""
split = item.get('split')
return f" · folha {split['part']} de {split['of']}" if split else ''

View File

@@ -27,7 +27,8 @@ SECRET_FILE_SETTINGS = (
'PAYMENT_TOKEN',
'PAYMENT_WEBHOOK_SECRET',
'TINY_TOKEN',
'WHATSAPP_TOKEN',
'SMTP_PASSWORD',
'CORREIOS_CODIGO_ACESSO',
)
SUFFIX = '_FILE'

184
app/correios.py Normal file
View File

@@ -0,0 +1,184 @@
"""Correios freight quotes (CWS API: Token, Preço and Prazo), PAC and SEDEX.
Written from the Correios manuals (API Preço, API Prazo) and exercised against
a fake HTTP transport until app.correios_probe has run on Dropstar's contract.
A quote is read-only: it creates no shipment and costs nothing.
The token comes from the posting card (cartão de postagem) with the CWS user
and its access code, lasts about a day and is reused until shortly before it
expires. It also says the contract and its regional office (DR), which price
the contract's own rates. Each box of the order (app/package.py) is one
object: Correios price the larger of its real and cubic weight themselves,
from the box's sides, so only the real weight is sent.
"""
import base64
import os
import threading
from datetime import datetime, timedelta, timezone
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal, InvalidOperation
import httpx
from .package import Package
API = 'https://api.correios.com.br'
ORIGIN = '14402310'
# The contract's service codes ("contrato agência"); a setting overrides each.
SERVICES = {'pac': ('CORREIOS_COD_PAC', '03298', 'Correios PAC'),
'sedex': ('CORREIOS_COD_SEDEX', '03220', 'Correios SEDEX')}
PACKAGE = '2'
MAX_KG = Decimal(30)
BRASILIA = timezone(timedelta(hours=-3))
class CorreiosError(Exception):
pass
def digits(value):
return ''.join(ch for ch in str(value or '') if ch.isdigit())
def required_settings():
return ('CORREIOS_USUARIO', 'CORREIOS_CODIGO_ACESSO', 'CORREIOS_CARTAO')
def configured():
return bool(os.environ.get('CORREIOS_CODIGO_ACESSO', '').strip())
def problem(response):
"""The Correios' own words for a refusal: txErro, or the gateway's msgs."""
try:
data = response.json()
except ValueError:
return f'HTTP {response.status_code}'
if isinstance(data, list):
data = data[0] if data else {}
if isinstance(data, dict):
if data.get('txErro'):
return data['txErro']
if data.get('msgs'):
return '; '.join(map(str, data['msgs']))
return f'HTTP {response.status_code}'
def cents(text):
"""'11,64' (or 11.64) in centavos."""
try:
value = Decimal(str(text).replace('.', '').replace(',', '.')) if ',' in str(text) else Decimal(str(text))
except InvalidOperation:
raise CorreiosError(f'preço ilegível: {text!r}') from None
return int((value * 100).quantize(Decimal('1'), ROUND_HALF_UP))
class CorreiosQuotes:
def __init__(self, user=None, access_code=None, card=None, origin=None, transport=None, clock=None):
self.user = (user or os.environ.get('CORREIOS_USUARIO', '')).strip()
self.access_code = (access_code or os.environ.get('CORREIOS_CODIGO_ACESSO', '')).strip()
self.card = digits(card or os.environ.get('CORREIOS_CARTAO'))
self.origin = digits(origin or os.environ.get('CORREIOS_ORIGEM_CEP') or ORIGIN)
if not (self.user and self.access_code and self.card):
raise RuntimeError('Correios needs ' + ', '.join(required_settings()))
self.http = httpx.Client(base_url=API, timeout=15, transport=transport)
self.clock = clock or (lambda: datetime.now(timezone.utc))
self.lock = threading.Lock()
self.token = None
self.expires = None
self.contract = None
self.dr = None
def authenticate(self):
basic = base64.b64encode(f'{self.user}:{self.access_code}'.encode()).decode()
response = self.http.post('/token/v1/autentica/cartaopostagem', json={'numero': self.card},
headers={'Authorization': f'Basic {basic}'})
if response.status_code >= 400:
raise CorreiosError(f'token recusado: {problem(response)}')
data = response.json()
card = data.get('cartaoPostagem') or {}
self.token = data['token']
self.contract = card.get('contrato') or os.environ.get('CORREIOS_CONTRATO') or None
self.dr = card.get('dr') or os.environ.get('CORREIOS_DR') or None
try:
# "2026-10-16T10:00:00", Brasília time unless it says otherwise.
expires = datetime.fromisoformat(data['expiraEm'])
self.expires = expires if expires.tzinfo else expires.replace(tzinfo=BRASILIA)
except (KeyError, TypeError, ValueError):
self.expires = self.clock() + timedelta(hours=23)
def bearer(self, fresh=False):
with self.lock:
if fresh or not self.token or self.clock() >= self.expires - timedelta(minutes=10):
self.authenticate()
return self.token
def get(self, path, params):
"""A GET with the token, renewed once if the Correios refuse it."""
for fresh in (False, True):
response = self.http.get(path, params=params, headers={'Authorization': f'Bearer {self.bearer(fresh)}',
'Accept': 'application/json'})
if response.status_code != 401:
break
if response.status_code >= 400:
raise CorreiosError(problem(response))
return response.json()
def price(self, code, postal_code, grams, sides):
"""The contract's price in centavos for one package."""
length, width, height = (int(side.to_integral_value(ROUND_CEILING)) for side in sides)
params = {'cepOrigem': self.origin, 'cepDestino': postal_code, 'psObjeto': str(grams),
'tpObjeto': PACKAGE, 'comprimento': str(length), 'largura': str(width), 'altura': str(height)}
self.bearer()
if self.contract and self.dr:
params.update(nuContrato=str(self.contract), nuDR=str(self.dr))
data = self.get(f'/preco/v1/nacional/{code}', params)
if data.get('txErro'):
raise CorreiosError(data['txErro'])
if data.get('pcFinal') in (None, ''):
raise CorreiosError('sem preço na resposta')
return cents(data['pcFinal'])
def days(self, code, postal_code):
"""Delivery time in working days from posting, or None."""
data = self.get(f'/prazo/v1/nacional/{code}', {'cepOrigem': self.origin, 'cepDestino': postal_code})
if data.get('txErro'):
raise CorreiosError(data['txErro'])
return data.get('prazoEntrega')
class CorreiosFreight(Package):
"""The Site's PAC and SEDEX options for the order's package."""
name = 'correios'
def __init__(self, quotes=None):
super().__init__()
if not self.box_cm:
raise RuntimeError('Correios price by the box: set JADLOG_CAIXA_CM')
self.quotes = quotes or CorreiosQuotes()
self.codes = {service: (os.environ.get(setting) or code).strip()
for service, (setting, code, _) in SERVICES.items()}
self.services = {service: label for service, (_, _, label) in SERVICES.items()}
def quote(self, service, postal_code, metres=None, declared_cents=0):
if service == 'pickup':
return {'provider': self.name, 'service': 'pickup', 'total_cents': 0, 'postal_code': ''}
if service not in self.codes or len(postal_code) != 8 or not postal_code.isascii() or not postal_code.isdigit():
raise ValueError('Select pickup or Correios delivery with an eight-digit CEP')
if metres is None or Decimal(str(metres)) <= 0:
raise ValueError('The order length is required to quote freight')
weights = self.box_weights_kg(metres)
if max(weights) > MAX_KG:
raise ValueError('Uma caixa passa de 30 kg, o limite dos Correios.')
code = self.codes[service]
try:
# Boxes of the same weight cost the same: one price per weight.
prices = {weight: self.quotes.price(code, postal_code, int(weight * 1000), self.box_cm)
for weight in set(weights)}
days = self.quotes.days(code, postal_code)
except (CorreiosError, httpx.HTTPError) as error:
raise ValueError(f'Não foi possível cotar o {self.services[service]} agora: {error}') from None
return {'provider': self.name, 'service': service, 'postal_code': postal_code,
'total_cents': sum(prices[weight] for weight in weights),
'real_kg': str(sum(weights)), 'boxes': len(weights),
'days': None if days is None else int(days) + self.production_days,
'description': self.services[service]}

70
app/correios_probe.py Normal file
View File

@@ -0,0 +1,70 @@
"""Read-only check against Dropstar's real Correios contract, run by hand.
A quote creates no shipment and costs nothing.
python -m app.correios_probe [--cep 01310100 ...] [--peso 0.5 ...]
It answers whether the user, access code and posting card are accepted (and
which contract and DR the token carries), whether the contract prices PAC and
SEDEX with the codes in use, and what they cost and take for one box (the
JADLOG_CAIXA_CM sides) to a few regions. The first failure stops the run: an
account problem would repeat on every line.
In production, from the worker's console (Portainer > Containers > worker >
Console), with CORREIOS_CODIGO_ACESSO in the stack:
python -m app.correios_probe
"""
import argparse
import os
import sys
from decimal import Decimal
from .core.secrets import load as load_secret_files
from .correios import SERVICES, CorreiosError, CorreiosQuotes
from .package import box_cm
DESTINATIONS = {'01310100': 'São Paulo', '20040002': 'Rio de Janeiro', '80010000': 'Curitiba',
'50030230': 'Recife', '69005010': 'Manaus'}
WEIGHTS = ['0.5', '2', '5']
def money(cents):
return f'R$ {cents / 100:.2f}'.replace('.', ',')
def run(quotes, sides, ceps, weights, out):
try:
quotes.bearer()
except CorreiosError as error:
out(f'ERRO no token: {error}')
return 1
out(f'Token ok · cartão {quotes.card} · contrato {quotes.contract or "-"} · DR {quotes.dr or "-"} '
f'· válido até {quotes.expires:%d/%m %H:%M}')
out(f"Origem {quotes.origin} · caixa {' × '.join(str(side) for side in sides)} cm")
for service, (setting, default, label) in SERVICES.items():
code = (os.environ.get(setting) or default).strip()
for cep in ceps:
try:
days = quotes.days(code, cep)
for weight in weights:
cents = quotes.price(code, cep, int(Decimal(weight) * 1000), sides)
out(f"{label} ({code})\t{weight} kg\t{cep}\t{DESTINATIONS.get(cep, '')}\t{money(cents)}\t"
f"{days if days is not None else '?'} dia(s)")
except CorreiosError as error:
out(f'ERRO {label} ({code}) para {cep}: {error}')
return 1
return 0
def main(argv=None):
parser = argparse.ArgumentParser(prog='python -m app.correios_probe')
parser.add_argument('--cep', action='append', help='destination CEP (repeatable)')
parser.add_argument('--peso', action='append', help='weight in kg (repeatable)')
args = parser.parse_args(argv)
load_secret_files()
sides = box_cm(os.environ.get('JADLOG_CAIXA_CM') or '63x15.5x15.5')
return run(CorreiosQuotes(), sides, args.cep or list(DESTINATIONS), args.peso or WEIGHTS, print)
if __name__ == '__main__':
sys.exit(main())

81
app/coupons.py Normal file
View File

@@ -0,0 +1,81 @@
"""Discount coupons typed by the customer at checkout (Fase 2, front 8.3).
One coupon per order. It is checked when the quote is created and again at
approval; only paid orders count against its limits, so a cart that waits or
expires never spends a use. The discount is computed on the server after the
bands of app/catalog.py, on the eligible items only, and never on freight or
the treatment. An approved quote keeps the coupon it was approved with.
"""
from decimal import Decimal, ROUND_FLOOR
from . import catalog
# A test order, a cancelled one and a proof card are not a sale (as the
# board's REAL_ORDER): they do not spend a coupon use.
PAID_ORDER = ("o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste' "
"AND o.parent_id IS NULL")
def eligible_items(items, product):
"""The items a coupon applies to: all of them, or one product's."""
return [item for item in items if product is None or item.get('mode') == product]
def discount_cents(kind, value, items):
"""The discount on the eligible items, in cents. Percent: floor of the
items' total. Per metre: the value times their billed metres, floored.
Never more than the items' total."""
total = sum(int(item.get('total_cents') or 0) for item in items)
if kind == 'percent':
discount = int((Decimal(total) * value / 100).to_integral_value(rounding=ROUND_FLOOR))
elif kind == 'per_metre':
metres = sum(Decimal(str(item.get('billed_metres') or 0)) for item in items)
discount = int((metres * value).to_integral_value(rounding=ROUND_FLOOR))
else:
raise ValueError('Invalid coupon kind')
return max(0, min(discount, total))
def metres_label(value):
"""5,5 m: how a minimum reads on the Site."""
return f'{Decimal(value).normalize():f}'.replace('.', ',')
def check(c, code, customer_document, priced_items):
"""The coupon for this cart and customer, or a 422 saying why not.
Returns {'id', 'code', 'discount_cents'}."""
# Imported here so the pure helpers above load without the web framework
# (tests/test_coupons.py runs on the host, where FastAPI is not installed).
from fastapi import HTTPException
code = (code or '').strip().upper()
row = c.execute('''SELECT *, now() AS now FROM dtf_local.coupons
WHERE code=%s AND deleted_at IS NULL''', (code,)).fetchone()
if not row:
raise HTTPException(422, 'Cupom não encontrado.')
if row['paused']:
raise HTTPException(422, 'Este cupom está pausado.')
if row['valid_from'] > row['now']:
raise HTTPException(422, 'Este cupom ainda não começou.')
if row['valid_until'] is not None and row['valid_until'] <= row['now']:
raise HTTPException(422, 'Este cupom expirou.')
eligible = eligible_items(priced_items, row['product'])
if row['product'] and not eligible:
raise HTTPException(422, f'Este cupom vale só para {catalog.TITLES[row["product"]]}.')
metres = sum(Decimal(str(item.get('billed_metres') or 0)) for item in eligible)
if row['min_metres'] is not None and metres < row['min_metres']:
raise HTTPException(422, f'Este cupom pede pelo menos {metres_label(row["min_metres"])} m.')
# Uses count only paid orders: the limit is spent at payment, not at the
# quote, and an order already paid is never refused afterwards.
used = c.execute(f'''SELECT count(*) AS n FROM dtf_local.orders o
WHERE o.snapshot->'coupon'->>'id'=%s AND {PAID_ORDER}''',
(str(row['id']),)).fetchone()['n']
if row['max_uses'] is not None and used >= row['max_uses']:
raise HTTPException(422, 'Este cupom já foi usado o máximo de vezes.')
if row['max_uses_per_customer'] is not None and customer_document:
mine = c.execute(f'''SELECT count(*) AS n FROM dtf_local.orders o
WHERE o.snapshot->'coupon'->>'id'=%s AND o.snapshot->'customer'->>'cnpj'=%s
AND {PAID_ORDER}''', (str(row['id']), str(customer_document))).fetchone()['n']
if mine >= row['max_uses_per_customer']:
raise HTTPException(422, 'Você já usou este cupom.')
return {'id': str(row['id']), 'code': row['code'],
'discount_cents': discount_cents(row['kind'], row['value'], eligible)}

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

46
app/freight.py Normal file
View File

@@ -0,0 +1,46 @@
"""Every delivery option the Site offers, from every carrier configured.
The cart asks for all options at once and shows them cheapest first; the
customer's choice is quoted again by the server when the cart is approved.
A carrier that does not answer leaves its options out instead of blocking the
others.
"""
from concurrent.futures import ThreadPoolExecutor
class FreightOptions:
name = 'carriers'
def __init__(self, carriers):
self.carriers = carriers
self.by_service = {service: carrier for carrier in carriers for service in carrier.services}
@property
def services(self):
return {service: carrier.services[service] for service, carrier in self.by_service.items()}
def carrier(self, name):
return next((c for c in self.carriers if c.name == name), None)
def quote(self, service, postal_code, metres=None, declared_cents=0):
if service == 'pickup':
return {'provider': self.name, 'service': 'pickup', 'total_cents': 0, 'postal_code': ''}
carrier = self.by_service.get(service)
if not carrier:
raise ValueError('Esta forma de entrega não está disponível. Escolha outra.')
return carrier.quote(service, postal_code, metres, declared_cents)
def options(self, postal_code, metres=None, declared_cents=0):
"""Each service's quote, cheapest first, and why any could not be quoted."""
services = list(self.by_service)
with ThreadPoolExecutor(max_workers=max(1, len(services))) as pool:
futures = {service: pool.submit(self.quote, service, postal_code, metres, declared_cents)
for service in services}
found, missing = [], []
for service, future in futures.items():
try:
found.append(future.result())
except ValueError as error:
missing.append({'service': service, 'description': self.services[service], 'error': str(error)})
found.sort(key=lambda option: (option['total_cents'], option.get('days') or 99))
return {'options': found, 'unavailable': missing}

240
app/grade_check.py Normal file
View File

@@ -0,0 +1,240 @@
"""The grade recomputed from the uploaded files.
The Site grades the art in the customer's browser and sends the grade with the
cart. The price no longer depends on it (one price per product, 2026-10-23),
but the grade is shown with the order on the Kanban and in Tiny. A customer
who edits the page could claim a better grade, so before a cart is approved at
checkout the server reads the files it already has and works the grade out
again, by the Site's own rules:
- a finished sheet: its pixel width over the sheet width is its DPI, and the
item's grade comes from the worst sheet (web/site-quality.js);
- artworks: each one's DPI along the width it is printed at, rotation
included; the item's grade is the average of the artworks' grades;
- a PDF: the area-weighted DPI of the images drawn on its page, 300 when it
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. 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
import struct
import tempfile
DPI_IDEAL = 200
DPI_REFUSE = 96
PDF_VECTOR_DPI = 300
# The Site analyses PDFs up to 150 MB (GRANDE_BYTES); above that it does not
# grade them, so neither does this.
PDF_MAX_BYTES = 150 * 1048576
HEAD_BYTES = 1048576
# Rounding in the browser and here can differ by a point on the same file.
TOLERANCE = 2
def js_round(value):
"""Math.round, which rounds halves up; Python's round() does not."""
return math.floor(value + 0.5)
def grade_of(dpi):
return max(6, min(100, js_round(dpi / DPI_IDEAL * 100)))
def image_size(head):
"""(width, height) in pixels from a PNG, JPEG or WebP's first bytes."""
if head[:8] == b'\x89PNG\r\n\x1a\n' and head[12:16] == b'IHDR':
return struct.unpack('>II', head[16:24])
if head[:2] == b'\xff\xd8':
i = 2
while i + 9 < len(head):
if head[i] != 0xFF:
i += 1
continue
marker = head[i + 1]
if marker in (0xD8, 0x01) or 0xD0 <= marker <= 0xD7 or marker == 0xFF:
i += 1 if marker == 0xFF else 2
continue
length = struct.unpack('>H', head[i + 2:i + 4])[0]
if 0xC0 <= marker <= 0xCF and marker not in (0xC4, 0xC8, 0xCC):
h, w = struct.unpack('>HH', head[i + 5:i + 9])
return w, h
i += 2 + length
return None
if head[:4] == b'RIFF' and head[8:12] == b'WEBP':
chunk = head[12:16]
if chunk == b'VP8X':
return (int.from_bytes(head[24:27], 'little') + 1, int.from_bytes(head[27:30], 'little') + 1)
if chunk == b'VP8L' and head[20] == 0x2F:
bits = int.from_bytes(head[21:25], 'little')
return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1
if chunk == b'VP8 ' and head[23:26] == b'\x9d\x01\x2a':
w, h = struct.unpack('<HH', head[26:30])
return w & 0x3FFF, h & 0x3FFF
return None
def _multiply(a, b):
return [a[0] * b[0] + a[2] * b[1], a[1] * b[0] + a[3] * b[1],
a[0] * b[2] + a[2] * b[3], a[1] * b[2] + a[3] * b[3],
a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]]
def pdf_dpi(path):
"""The page's area-weighted image DPI, 300 for vectors only, None if the
file is not a one-page PDF this can read."""
import pikepdf
try:
with pikepdf.open(path) as pdf:
if len(pdf.pages) != 1:
return None
page = pdf.pages[0]
unit = float(page.obj.get('/UserUnit', 1))
found = []
def walk(resources, instructions, ctm, depth):
stack = []
xobjects = resources.get('/XObject', {}) if resources is not None else {}
for operands, operator in instructions:
op = str(operator)
if op == 'q':
stack.append(ctm)
elif op == 'Q':
ctm = stack.pop() if stack else [1, 0, 0, 1, 0, 0]
elif op == 'cm':
ctm = _multiply(ctm, [float(v) for v in operands])
elif op == 'Do' and operands:
xobject = xobjects.get(str(operands[0]))
if xobject is None:
continue
subtype = xobject.get('/Subtype')
if subtype == '/Image':
width_pt = math.hypot(ctm[0], ctm[1])
if width_pt >= 1:
found.append((int(xobject.get('/Width', 0)) / (width_pt * unit / 72),
abs(ctm[0] * ctm[3] - ctm[1] * ctm[2])))
elif subtype == '/Form' and depth < 8:
matrix = [float(v) for v in xobject.get('/Matrix', [1, 0, 0, 1, 0, 0])]
walk(xobject.get('/Resources', resources),
pikepdf.parse_content_stream(xobject), _multiply(ctm, matrix), depth + 1)
walk(page.obj.get('/Resources'), pikepdf.parse_content_stream(page), [1, 0, 0, 1, 0, 0], 0)
except Exception:
return None
found = [(dpi, area) for dpi, area in found if dpi > 0]
if not found:
return PDF_VECTOR_DPI
total = sum(area for _, area in found) or 1
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."""
def __init__(self, storage):
self.storage = storage
# A PDF is read once per quote: source_dpi, resolution_issue and
# mismatch all ask for the same files.
self._heads = {}
self._dpis = {}
def head(self, row):
key = row['object_key']
if key not in self._heads:
self._heads[key] = self.storage.client.get_object(
Bucket=self.storage.bucket, Key=key, Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read()
return self._heads[key]
def pdf_dpi(self, row):
key = row['object_key']
if key not in self._dpis:
if row.get('pdf_checked'):
self._dpis[key] = row['pdf_dpi']
else:
self._dpis[key] = stored_pdf_dpi(self.storage, row)
return self._dpis[key]
def source_dpi(files, row, source):
"""One source's DPI across the width it is printed at, or None."""
name = row['name'].lower()
width_in = float(source['width_cm']) / 2.54
if name.endswith('.pdf'):
return files.pdf_dpi(row) if source['kind'] == 'sheet' else None
if not name.endswith(('.png', '.jpg', '.jpeg', '.webp')):
return None
size = image_size(files.head(row))
if not size or not all(size):
return None
across = size[1] if source['rotation_degrees'] in (90, 270) else size[0]
return across / width_in
def item_grade(files, item, rows):
"""The grade the Site gives this item, recomputed; None if it cannot be."""
sources = item['production']['sources']
dpis = []
for source in sources:
row = rows.get(str(source['upload_id']))
dpi = source_dpi(files, row, source) if row else None
if dpi is None:
return None
dpis.append(dpi)
if all(source['kind'] == 'sheet' for source in sources):
# A sheet's DPI is shown and compared as a whole number.
return grade_of(min(js_round(d) for d in dpis))
return js_round(sum(grade_of(d) for d in dpis) / len(dpis))
def resolution_issue(files, items, rows):
"""Refuse sub-96 DPI and require recorded consent for measurable 96–199 DPI.
Unknown formats remain for manual review; they cannot be treated as a
measured zero DPI or silently called high-resolution artwork.
"""
for index, item in enumerate(items, 1):
dpis = []
for source in item['production']['sources']:
row = rows.get(str(source['upload_id']))
dpi = source_dpi(files, row, source) if row else None
if dpi is None:
dpis = []
break
dpis.append(dpi)
if not dpis:
continue
# 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 mismatch(files, items, rows):
"""Why a cart's grades cannot be approved at checkout, or None."""
for item in items:
if item['grade'] == 0:
continue # no grade claimed: nothing to verify
verified = item_grade(files, item, rows)
if verified is None:
return 'Nota não conferida no servidor'
if item['grade'] > verified + TOLERANCE:
return f"Nota {item['grade']} maior que a do arquivo ({verified})"
return None

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

173
app/hotfolder.py Normal file
View File

@@ -0,0 +1,173 @@
"""Each machine's hot folders (Dropstar's third round, item 10, 2026-10-29/30).
FlexiPRINT watches 3. Imprimindo/<máquina>/<C1|C2|C3|PREMIUM>/ and takes a
file out of it when it rips. When the operator pulls a card to Imprimindo, its
files go, as a copy, into its machine's folder for the item's contraction
class; a premium item always goes to PREMIUM, whichever class it carries;
the order's own file stays in its stage folder. A film over 15 m is several
parts (item 13): all on the same machine, in order. A machine's folder holds
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
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.
Each part's life is one row of dtf_local.hot_parts:
queued -> claimed -> written -> consumed, or withdraw -> gone.
"""
from datetime import timedelta
# The machines' folders, inside the Kanban's main folder (Dropstar, 2026-10-30).
PRINTING_FOLDER = '3. Imprimindo'
# 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):
"""The item's class for the folder: the one chosen in the Kanban, or what
the Site measured (C3 when the customer protected the solid areas)."""
chosen = (order.get('contraction') or {}).get(str(index)) or {}
if chosen.get('class') in CLASSES:
return chosen['class']
item = order['snapshot']['items'][index]
if item.get('stroke_choice') == 'client_c3':
return 'C3'
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; 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 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):
c.execute('''INSERT INTO dtf_local.hot_parts(order_id,round,seq,item_index,upload_id,name)
VALUES(%s,%s,%s,%s,%s,%s)''', (order_id, round_, seq, row['item_index'], row['upload_id'], row['name']))
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."""
c.execute('''UPDATE dtf_local.hot_parts SET state=CASE WHEN state IN ('claimed','written') THEN 'withdraw' ELSE 'gone' END,
done_at=CASE WHEN state IN ('claimed','written') THEN NULL ELSE now() END
WHERE order_id=%s AND state IN ('queued','claimed','written')''', (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 its places' worth in its folder."""
c.execute('''UPDATE dtf_local.hot_parts SET state='queued', claimed_at=NULL, claimed_by=NULL
WHERE state='claimed' AND claimed_at < now() - %s''', (CLAIM_TIMEOUT,))
rows = c.execute('''SELECT h.*, o.machine_id, o.contraction, o.snapshot, m.name AS machine_name, m.places,
(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()
due, busy, blocked = [], {}, set()
for row in rows:
machine = row['machine_id']
if row['state'] != 'queued':
busy[machine] = busy.get(machine, 0) + 1
for row in rows:
machine, order = row['machine_id'], row['order_id']
if row['state'] != 'queued' or order in blocked:
continue
cls = folder_class(row, row['item_index'])
# A part without its class waits, and the parts after it with it.
if busy.get(machine, 0) >= row['places'] or not cls:
blocked.add(order)
continue
folder = f"{row['machine_name']}/{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
due.append({**row, 'folder': folder})
return due
def watched(c):
"""The parts written and not yet taken by Flexi, and those to delete."""
return c.execute('''SELECT id, order_id, name, folder, state FROM dtf_local.hot_parts
WHERE state IN ('written','withdraw') AND folder IS NOT NULL ORDER BY id''').fetchall()
# What a computer reports about a part, and from which states it may.
REPORTS = {'written': ('claimed',), 'released': ('claimed',), 'consumed': ('written',), 'gone': ('withdraw',)}
def report(c, part_id, what, user):
"""A computer wrote the part, could not, saw Flexi take it, or deleted a
withdrawn one. Returns whether the report applied."""
if what == 'written':
sql = '''UPDATE dtf_local.hot_parts SET state='written', written_at=now() WHERE id=%s AND state='claimed'
AND claimed_by=%s RETURNING id'''
return bool(c.execute(sql, (part_id, user)).fetchone())
if what == 'released':
sql = '''UPDATE dtf_local.hot_parts SET state='queued', claimed_at=NULL, claimed_by=NULL, folder=NULL
WHERE id=%s AND state='claimed' AND claimed_by=%s RETURNING id'''
return bool(c.execute(sql, (part_id, user)).fetchone())
new = {'consumed': 'consumed', 'gone': 'gone'}[what]
return bool(c.execute(f'''UPDATE dtf_local.hot_parts SET state='{new}', done_at=now() WHERE id=%s
AND state=ANY(%s) RETURNING id''', (part_id, list(REPORTS[what]))).fetchone())
def progress(c, order_ids):
"""For each order in parts, where its film is (Dropstar, 2026-10-30):
"parte 3/7 imprimindo · 4/7 ripando". Flexi rips the part it took last
while the one before it prints."""
rows = c.execute('''SELECT h.order_id, count(*) AS parts,
max(h.seq) FILTER (WHERE h.state='consumed') AS taken,
count(*) FILTER (WHERE h.state IN ('claimed','written')) AS waiting
FROM dtf_local.hot_parts h
WHERE h.order_id=ANY(%s) AND h.round=(SELECT max(round) FROM dtf_local.hot_parts x WHERE x.order_id=h.order_id)
GROUP BY h.order_id''', (order_ids,)).fetchall()
return {row['order_id']: {'parts': row['parts'], 'taken': row['taken'] or 0, 'waiting': row['waiting']}
for row in rows}

109
app/jadlog.py Normal file
View File

@@ -0,0 +1,109 @@
"""Jadlog freight quotes (Embarcador API, "Simulador de Frete").
Written from Jadlog's API manual v2.3 (August 2025) and exercised only
against a fake HTTP transport until app.jadlog_probe has run on the client's
account. A quote is read-only: it creates no shipment and costs nothing, so
unlike Tiny it can be tried on the real account as often as needed.
The client's contract: origin CEP 14402-310, service .PACKAGE (modalidade 3),
home delivery. Jadlog prices by weight in kg and expects the larger of the
real and the cubed weight, both from the order's package (app/package.py).
"""
import os
from decimal import ROUND_HALF_UP, Decimal
import httpx
from .package import WEIGHT_SETTINGS, Package
QUOTE_URL = 'https://www.jadlog.com.br/embarcador/api/frete/valor'
PACKAGE = 3
ORIGIN = '14402310'
SERVICE = 'jadlog'
class JadlogError(Exception):
pass
def digits(value):
return ''.join(ch for ch in str(value or '') if ch.isdigit())
class JadlogQuotes:
def __init__(self, token=None, cnpj=None, conta=None, contrato=None, origin=None,
modalidade=None, transport=None):
self.token = (token or os.environ.get('JADLOG_TOKEN', '')).strip()
self.cnpj = digits(cnpj or os.environ.get('JADLOG_CNPJ'))
# Sent as configured: Jadlog issues it as 000000-0 and documents six
# characters, so which form it accepts is only known on the account.
self.conta = (conta if conta is not None else os.environ.get('JADLOG_CONTA', '')).strip()
# Only when Jadlog issued one; the manual says to send null otherwise.
self.contrato = (contrato if contrato is not None else os.environ.get('JADLOG_CONTRATO', '')).strip() or None
self.origin = digits(origin or os.environ.get('JADLOG_ORIGEM_CEP') or ORIGIN)
self.modalidade = int(modalidade or os.environ.get('JADLOG_MODALIDADE') or PACKAGE)
if not self.token or len(self.cnpj) != 14:
raise RuntimeError('Jadlog needs JADLOG_TOKEN and a 14-digit JADLOG_CNPJ')
self.http = httpx.Client(timeout=20, transport=transport)
def item(self, postal_code, weight_kg, declared_cents):
return {'cepori': self.origin, 'cepdes': digits(postal_code), 'frap': 'N',
'peso': float(weight_kg), 'cnpj': self.cnpj, 'conta': self.conta,
'contrato': self.contrato, 'modalidade': self.modalidade,
'tpentrega': 'D', 'tpseguro': 'N',
'vldeclarado': declared_cents / 100, 'vlcoleta': 0}
def quote(self, postal_code, weight_kg, declared_cents):
"""Price in centavos and delivery days for one package to one CEP."""
response = self.http.post(QUOTE_URL, json={'frete': [self.item(postal_code, weight_kg, declared_cents)]},
headers={'Authorization': self.token})
if response.status_code == 401:
raise JadlogError('Jadlog refused the token (HTTP 401)')
try:
data = response.json()
except ValueError:
raise JadlogError(f'HTTP {response.status_code}: the response is not JSON') from None
items = data.get('frete') or []
# The manual names the group "erro" in its tables and "error" in its
# examples, at the top level and per item.
problem = data.get('error') or data.get('erro')
if not problem and items:
problem = items[0].get('erro') or items[0].get('error')
if problem:
raise JadlogError(problem.get('descricao') or str(problem) if isinstance(problem, dict) else str(problem))
if response.status_code >= 400 or not items or items[0].get('vltotal') is None:
raise JadlogError(f'HTTP {response.status_code}: no freight value in the response')
total = Decimal(str(items[0]['vltotal']))
return {'total_cents': int((total * 100).quantize(Decimal('1'), ROUND_HALF_UP)),
'days': items[0].get('prazo'), 'raw': items[0]}
def required_settings():
return ('JADLOG_TOKEN', 'JADLOG_CNPJ') + WEIGHT_SETTINGS
class JadlogFreight(Package):
"""The Site's Jadlog option: Jadlog's price for the order's package."""
name = 'jadlog'
services = {SERVICE: 'Jadlog'}
def __init__(self, quotes=None):
super().__init__()
self.quotes = quotes or JadlogQuotes()
def quote(self, service, postal_code, metres=None, declared_cents=0):
if service == 'pickup':
return {'provider': self.name, 'service': 'pickup', 'total_cents': 0, 'postal_code': ''}
if service != SERVICE or len(postal_code) != 8 or not postal_code.isascii() or not postal_code.isdigit():
raise ValueError('Select pickup or Jadlog delivery with an eight-digit CEP')
if metres is None or Decimal(str(metres)) <= 0:
raise ValueError('The order length is required to quote freight')
weight, real = self.weight_kg(metres), self.real_kg(metres)
try:
result = self.quotes.quote(postal_code, weight, int(declared_cents))
except (JadlogError, httpx.HTTPError) as error:
raise ValueError(f'Não foi possível cotar o frete na Jadlog agora: {error}') from None
days = result['days']
return {'provider': self.name, 'service': SERVICE, 'postal_code': postal_code,
'total_cents': result['total_cents'], 'weight_kg': str(weight), 'real_kg': str(real),
'boxes': self.boxes(metres),
'days': None if days is None else int(days) + self.production_days,
'description': self.services[SERVICE]}

80
app/jadlog_probe.py Normal file
View File

@@ -0,0 +1,80 @@
"""Read-only price check against the client's real Jadlog account, run by hand.
A quote creates no shipment and costs nothing.
python -m app.jadlog_probe [--cep 01310100 ...] [--peso 0.5 ...] [--valor 100]
Without --cep and --peso it prices a few test weights to a few regions. It
answers whether the token, CNPJ and account are accepted, whether a contract
number is required (Jadlog names it in the error), and what the contract
prices and delivery times are. The first failure stops the run: an account
problem would repeat on every line.
In production, from the worker's console (Portainer > Containers > worker >
Console), with JADLOG_TOKEN, JADLOG_CNPJ and JADLOG_CONTA in the stack:
python -m app.jadlog_probe
Locally, with the credentials in jadlog.env (ignored by git):
docker compose -f compose.local.yaml -f compose.providers.yaml run --rm --no-deps --build \\
--env-from-file jadlog.env worker python -m app.jadlog_probe
"""
import argparse
import sys
from decimal import Decimal
from .core.secrets import load as load_secret_files
from .jadlog import JadlogError, JadlogQuotes
DESTINATIONS = {'14402310': 'Franca (origem)', '01310100': 'São Paulo', '20040002': 'Rio de Janeiro',
'80010000': 'Curitiba', '50030230': 'Recife', '69005010': 'Manaus'}
WEIGHTS = ['0.3', '0.5', '1', '2', '5']
def money(cents):
return f'R$ {cents / 100:.2f}'.replace('.', ',')
def run(quotes, ceps, weights, declared_cents, out):
header = quotes.token
for weight in weights:
for cep in ceps:
try:
result = quotes.quote(cep, Decimal(weight), declared_cents)
except JadlogError as error:
# The manual shows the header as the bare token; some accounts
# are issued one that expects the Bearer scheme.
if '401' in str(error) and not header.lower().startswith('bearer '):
quotes.token = 'Bearer ' + header
header = quotes.token
try:
result = quotes.quote(cep, Decimal(weight), declared_cents)
except JadlogError as retry:
out(f'ERRO {cep} {weight} kg: {retry} (also with "Bearer ")')
return 1
out('Note: the token only works with the "Bearer " prefix.')
else:
out(f'ERRO {cep} {weight} kg: {error}')
return 1
days = result['days']
out(f"{weight} kg\t{cep}\t{DESTINATIONS.get(cep, '')}\t{money(result['total_cents'])}\t"
f"{days if days is not None else '?'} dia(s)")
return 0
def main(argv=None):
parser = argparse.ArgumentParser(prog='python -m app.jadlog_probe')
parser.add_argument('--cep', action='append', help='destination CEP (repeatable)')
parser.add_argument('--peso', action='append', help='weight in kg (repeatable)')
parser.add_argument('--valor', default='100', help='declared value in reais (default 100)')
args = parser.parse_args(argv)
load_secret_files()
quotes = JadlogQuotes()
declared = int(Decimal(args.valor) * 100)
print(f'Origem {quotes.origin}, modalidade {quotes.modalidade}, contrato {quotes.contrato or "-"}, '
f'valor declarado {money(declared)}')
return run(quotes, args.cep or list(DESTINATIONS), args.peso or WEIGHTS, declared, print)
if __name__ == '__main__':
sys.exit(main())

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

265
app/machine_log.py Normal file
View File

@@ -0,0 +1,265 @@
"""Each machine's sheet: supplies, parts, events, counters and alerts
(Fase 2, front 1, part a; the Números block per machine is part b).
The room enters what goes into a machine with one click on its card: a
supply (film roll, ink by colour, powder) with its quantity and lot cost,
a part (cap, damper, head, wiper, other) with its cost and serial, or an
event (cleaned, aligned the head, a stop with its reason and minutes). The
Kanban already knows what each machine printed; with what goes in, it knows
what it uses.
Alerts appear on the machine's computer between one file and the next,
never in the middle: when someone on that machine pulls the next card into
Imprimindo. They are marked done (which records the event) or postponed
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 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
that interval, averaged over the last SUPPLY_INTERVALS intervals; the stock is
the average refill minus that use times the metres printed since the last
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.
"""
from datetime import datetime, timezone
from decimal import Decimal
CLEAN_EVERY_METRES = Decimal('10')
ALIGN_AFTER_FILM_METRES = Decimal('20')
SUPPLY_INTERVALS = 3
# item -> (Portuguese label, unit shown). Supplies are counted in rolls,
# litres and kilograms; Números shows ink per 100 m and powder in grams.
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'}
# A cycle with no resetting event still needs a value the snooze row can key on.
_EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
def one_decimal(value):
"""One decimal place with the Brazilian comma, as the alert lines show it."""
return f'{Decimal(str(value)):.1f}'.replace('.', ',')
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, m.items FROM dtf_local.movements m
JOIN dtf_local.orders o ON o.id=m.order_id
WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back
AND (%s::timestamptz IS NULL OR m.created_at > %s::timestamptz)''',
(machine_id, since, since)).fetchall()
total = Decimal(0)
for row in rows:
snapshot = row['snapshot'] or {}
proof = bool(snapshot.get('proof_of'))
for index, item in enumerate(snapshot.get('items') or []):
# A reprint counts only the items that went again (#105).
if row.get('items') is not None and index not in row['items']:
continue
if proof:
total += PROOF_SHEET_CM
else:
value = item.get('metres')
if value is None:
value = item.get('billed_metres')
total += Decimal(str(value or 0))
return total
def _last_entry(c, machine_id, kind, item):
return c.execute('''SELECT * FROM dtf_local.machine_entries
WHERE machine_id=%s AND kind=%s AND item=%s
ORDER BY created_at DESC, id DESC LIMIT 1''', (machine_id, kind, item)).fetchone()
def counters(c, machine_id):
"""{'clean': {'metres': Decimal, 'since': datetime|None},
'film': {'metres': Decimal, 'since': datetime|None, 'aligned': bool}}"""
clean = _last_entry(c, machine_id, 'event', 'clean')
film = _last_entry(c, machine_id, 'supply', 'film')
clean_since = clean['created_at'] if clean else None
# No cleaning on record yet: count from when the sheet started, or every
# machine would ask for one on the day this went live.
start = c.execute('SELECT log_since FROM dtf_local.machines WHERE id=%s', (machine_id,)).fetchone()
film_since = film['created_at'] if film else None
aligned = False
if film:
aligned = c.execute('''SELECT 1 FROM dtf_local.machine_entries
WHERE machine_id=%s AND kind='event' AND item='align' AND created_at>=%s LIMIT 1''',
(machine_id, film_since)).fetchone() is not None
return {'clean': {'metres': printed_since(c, machine_id, clean_since or (start or {}).get('log_since')),
'since': clean_since},
'film': {'metres': printed_since(c, machine_id, film_since or (start or {}).get('log_since')),
'since': film_since,
'aligned': aligned}}
def estimate(entries, metres_between, metres_since_last, minimum=None):
"""The supply estimate from simple lists, so it is tested without a database.
`entries` are the quantities entered, oldest first; `metres_between[i]` is
the film printed between entry i and entry i+1; `metres_since_last` is the
film printed since the last entry. None with fewer than two entries or when
no interval had film printed (nothing to divide by).
"""
quantities = [Decimal(str(value)) for value in entries]
if len(quantities) < 2:
return None
uses, refills = [], []
for quantity, metres in list(zip(quantities[1:], metres_between))[-SUPPLY_INTERVALS:]:
metres = Decimal(str(metres))
if metres <= 0:
continue
uses.append(quantity / metres)
refills.append(quantity)
if not uses:
return None
per_metre = sum(uses, Decimal(0)) / len(uses)
refill = sum(refills, Decimal(0)) / len(refills)
stock = refill - per_metre * Decimal(str(metres_since_last))
return {'per_metre': per_metre, 'stock': stock, 'metres_left': stock / per_metre,
'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 (typed or default)."""
return bool(value) and value['minimum'] is not None and value['stock'] <= value['minimum']
def supply_estimates(c, machine_id):
"""{item: {'per_metre': Decimal, 'stock': Decimal, 'metres_left': Decimal,
'minimum': Decimal|None}} for the supplies with an estimate (see module doc)."""
minimums = {row['item']: row['minimum'] for row in c.execute(
'SELECT item,minimum FROM dtf_local.machine_minimums WHERE machine_id=%s', (machine_id,)).fetchall()}
result = {}
for item in SUPPLIES:
# Only the entries the estimate uses: the board asks for it on every refresh.
rows = c.execute('''SELECT quantity, created_at FROM (SELECT quantity, created_at, id
FROM dtf_local.machine_entries WHERE machine_id=%s AND kind='supply' AND item=%s
ORDER BY created_at DESC, id DESC LIMIT %s) last ORDER BY created_at, id''',
(machine_id, item, SUPPLY_INTERVALS + 1)).fetchall()
if len(rows) < 2:
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],
minimum_for(minimums, item))
if value is not None:
result[item] = value
return result
def alerts(c, machine_id):
"""The alerts due on this machine now, each {'key': 'clean' | 'align' |
'supply:<item>', 'text': Portuguese line, 'cycle_from': datetime|None,
'snoozable': bool, 'blocking': bool}. blocking is False when it was
postponed this cycle and no card was pulled on the machine since.
Texts, with metres in one decimal and a comma:
clean "<máquina>: 10,4 m desde a última limpeza — limpe antes do próximo arquivo"
align "<máquina>: 19,8 m desde a troca de filme — alinhe a cabeça antes do próximo"
supply "<label minúsculo> da <máquina> deve acabar em ~3 m" (e.g. "tinta branca da máquina2 deve acabar em ~3,0 m")
"""
machine = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s', (machine_id,)).fetchone()
if not machine:
return []
name = machine['name']
counts = counters(c, machine_id)
supplies = supply_estimates(c, machine_id)
result = []
def postponed(key, cycle):
return c.execute('''SELECT snoozed_at FROM dtf_local.machine_snoozes
WHERE machine_id=%s AND alert=%s AND cycle_from=%s''',
(machine_id, key, cycle or _EPOCH)).fetchone()
def pulled_since(moment):
return c.execute('''SELECT 1 FROM dtf_local.movements m
JOIN dtf_local.orders o ON o.id=m.order_id
WHERE o.machine_id=%s AND m.to_state='imp' AND NOT m.back AND m.created_at>%s LIMIT 1''',
(machine_id, moment)).fetchone() is not None
def due(key, text, cycle):
snooze = postponed(key, cycle)
blocking = not (snooze and not pulled_since(snooze['snoozed_at']))
result.append({'key': key, 'text': text, 'cycle_from': cycle,
'snoozable': snooze is None, 'blocking': blocking})
if counts['clean']['metres'] >= CLEAN_EVERY_METRES:
due('clean', f"{name}: {one_decimal(counts['clean']['metres'])} m desde a última limpeza "
'— limpe antes do próximo arquivo', counts['clean']['since'])
if (counts['film']['since'] is not None and not counts['film']['aligned']
and counts['film']['metres'] >= ALIGN_AFTER_FILM_METRES):
due('align', f"{name}: {one_decimal(counts['film']['metres'])} m desde a troca de filme "
'— alinhe a cabeça antes do próximo', counts['film']['since'])
for item, value in supplies.items():
if not supply_low(value):
continue
last = _last_entry(c, machine_id, 'supply', item)
due('supply:' + item, f"{SUPPLIES[item][0].lower()} da {name} deve acabar em "
f"~{one_decimal(value['metres_left'])} m", last['created_at'] if last else None)
return result
def _field(body, name, default=None):
return body.get(name, default) if isinstance(body, dict) else getattr(body, name, default)
def add_entry(c, machine_id, body, user, from_alert=False):
"""Record one entry. A supply without cost takes the cost of that item's
last entry on the machine. Returns the row."""
kind = _field(body, 'kind')
item = _field(body, 'item')
cost = _field(body, 'cost_cents')
if kind == 'supply' and cost is None:
last = c.execute('''SELECT cost_cents FROM dtf_local.machine_entries
WHERE machine_id=%s AND kind='supply' AND item=%s AND cost_cents IS NOT NULL
ORDER BY created_at DESC, id DESC LIMIT 1''', (machine_id, item)).fetchone()
if last:
cost = last['cost_cents']
quantity = _field(body, 'quantity') if kind == 'supply' else None
stop_minutes = _field(body, 'stop_minutes') if kind == 'event' and item == 'stop' else None
return c.execute('''INSERT INTO dtf_local.machine_entries
(machine_id,kind,item,quantity,cost_cents,serial,note,stop_minutes,from_alert,created_by)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
(machine_id, kind, item, quantity, cost if kind in ('supply', 'part') else None,
_field(body, 'serial') if kind == 'part' else None, _field(body, 'note'),
stop_minutes, from_alert, user)).fetchone()
def snooze(c, machine_id, key, user):
"""Postpone an alert once per cycle; a second time in the same cycle is 409."""
from fastapi import HTTPException
current = next((alert for alert in alerts(c, machine_id) if alert['key'] == key), None)
if current is None:
raise HTTPException(409, 'Este aviso não está pendente.')
if not current['snoozable']:
raise HTTPException(409, 'Este aviso já foi adiado neste ciclo.')
row = c.execute('''INSERT INTO dtf_local.machine_snoozes(machine_id,alert,cycle_from,snoozed_by)
VALUES(%s,%s,%s,%s) ON CONFLICT (machine_id,alert,cycle_from) DO NOTHING RETURNING *''',
(machine_id, key, current['cycle_from'] or _EPOCH, user)).fetchone()
if not row:
raise HTTPException(409, 'Este aviso já foi adiado neste ciclo.')
return row

294
app/machine_stats.py Normal file
View File

@@ -0,0 +1,294 @@
"""Números per machine, month by month (Fase 2, front 1, part b).
From what the room enters on each machine's sheet (app/machine_log.py) and
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
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
total and by reason (the note, as typed).
Consumo metres per film roll = printed / rolls entered in the month;
ink litres per 100 m, per colour = litres entered / printed * 100;
powder grams per 100 m = kg entered * 1000 / printed * 100.
Refills stand for what was used: an entry replaces what ran out.
Custo supplies per metre and parts per metre = their cost entered in
the month / printed; total per metre = the sum.
Resultado contribution = what the orders it printed in the month sold
(their items' total_cents, not freight or treatment; no proof
or test order) minus its supplies and parts of the month. Also
accumulated since installation (installed_on, else log_since).
ROI accumulated contribution / (price + parts since installation),
in %, and months to pay back = (price + parts since
installation - accumulated contribution) / the average monthly
contribution since installation (None when that average is not
positive or the price is unknown).
Every ratio is None when its divisor is zero or unknown: no number is
better than a made-up one.
"""
from datetime import datetime, time
from decimal import Decimal, ROUND_HALF_UP
from zoneinfo import ZoneInfo
from .machine_log import SUPPLIES
SAO_PAULO = ZoneInfo('America/Sao_Paulo')
# The five inks Números lists, in the order the sheet knows them.
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
the next month) as timezone-aware datetimes at 00:00 America/Sao_Paulo.
A malformed month is ValueError."""
now = datetime.now(SAO_PAULO)
if month is None:
year, number = now.year, now.month
else:
try:
parsed = datetime.strptime(month, '%Y-%m')
except (TypeError, ValueError):
raise ValueError('month must be YYYY-MM') from None
# strptime accepts a single digit; the board always sends two.
if month != f'{parsed.year:04d}-{parsed.month:02d}':
raise ValueError('month must be YYYY-MM')
year, number = parsed.year, parsed.month
start = datetime(year, number, 1, tzinfo=SAO_PAULO)
if number == 12:
end = datetime(year + 1, 1, 1, tzinfo=SAO_PAULO)
else:
end = datetime(year, number + 1, 1, tzinfo=SAO_PAULO)
return start, end
def ratios(printed, hours_running=None, supplies_cents=0, parts_cents=0, rolls=None,
inks=None, powder=None, price_cents=None, contribution_cents=0,
installed_parts_cents=0, months=None):
"""Every Números ratio from raw totals, so they are tested without a
database. A zero or unknown divisor gives None; cents are whole."""
printed = Decimal(str(printed or 0))
def per_metre(cents):
if printed == 0:
return None
return int((Decimal(cents) / printed).quantize(Decimal('1'), rounding=ROUND_HALF_UP))
result = {
'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
else round(float(Decimal(str(quantity)) / printed * 100), 1))
for item, quantity in (inks or {}).items()},
'powder_g_per_100m': (round(float(Decimal(str(powder)) * 1000 / printed * 100), 1)
if powder is not None and printed else None),
'supplies_per_metre_cents': per_metre(supplies_cents),
'parts_per_metre_cents': per_metre(parts_cents),
'total_per_metre_cents': per_metre(Decimal(supplies_cents) + Decimal(parts_cents)),
'roi_pct': None,
'payback_months': None,
}
# Without a price there is no investment to measure the return against.
invested = None if price_cents is None else Decimal(price_cents) + Decimal(installed_parts_cents)
if invested:
result['roi_pct'] = round(float(Decimal(contribution_cents) * 100 / invested), 1)
if price_cents is not None and months and months > 0:
average = Decimal(contribution_cents) / Decimal(str(months))
if average > 0:
result['payback_months'] = round(
float((invested - Decimal(contribution_cents)) / average), 1)
return result
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, m.items
FROM dtf_local.movements m JOIN dtf_local.orders o ON o.id=m.order_id
WHERE o.machine_id=%s AND m.from_state='imp' AND m.to_state='rev' AND NOT m.back
AND m.created_at>=%s AND m.created_at<%s''', (machine_id, start, end)).fetchall()
def _film(snapshot, items=None):
"""The film printed for one order (machine_log's rule), as Decimal; on a
reprint only the `items` that went again."""
from .proof import PROOF_SHEET_CM
snapshot = snapshot or {}
proof = bool(snapshot.get('proof_of'))
total = Decimal(0)
for index, item in enumerate(snapshot.get('items') or []):
if items is not None and index not in items:
continue
if proof:
total += PROOF_SHEET_CM
else:
value = item.get('metres')
if value is None:
value = item.get('billed_metres')
total += Decimal(str(value or 0))
return total
def _sold(row):
"""What the order's items sold; proof cards, tests and cancelled orders
are not sales (as REAL_ORDER in the board)."""
if (row['parent_id'] is not None or row['cancelled_at'] is not None
or (row['payment'] or {}).get('provider') == 'teste'):
return 0
return sum(int(item.get('total_cents') or 0)
for item in (row['snapshot'] or {}).get('items') or [])
def printed_between(c, machine_id, start, end):
"""Film metres the machine printed in [start, end), as Decimal."""
return sum((_film(row['snapshot'], row.get('items')) for row in _printed_orders(c, machine_id, start, end)),
Decimal(0))
def _union_hours(spans, start, end):
"""The hours the spans (start, end) cover inside [start, end); time shared
by several orders is counted once."""
clipped = []
for at, until in spans:
first, last = max(at, start), min(until, end)
if last > first:
clipped.append((first, last))
seconds, reached = 0.0, None
for at, until in sorted(clipped):
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 round(seconds / 3600, 1)
def machine_month(c, machine, start, end):
"""One machine's figures for [start, end): {'printed_metres', 'hours_running',
'metres_per_hour', 'stopped_hours', 'stops': [{'reason', 'hours'}],
'metres_per_roll', 'ink_per_100m': {item: litres}, 'powder_g_per_100m',
'supplies_cents', 'parts_cents', 'supplies_per_metre_cents',
'parts_per_metre_cents', 'total_per_metre_cents', 'sold_cents',
'contribution_cents'}. `machine` is its row from dtf_local.machines."""
mid = machine['id']
rows = _printed_orders(c, mid, start, end)
printed = sum((_film(row['snapshot'], row.get('items')) for row in rows), Decimal(0))
sold = sum((_sold(row) for row in rows), 0)
ids = [row['id'] for row in rows]
spans = 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 at, until FROM spans WHERE state='imp' AND until IS NOT NULL''',
(ids,)).fetchall() if ids else []
hours = _union_hours([(row['at'], row['until']) for row in spans], start, end)
supplies = c.execute('''SELECT item, COALESCE(sum(quantity),0) AS quantity,
COALESCE(sum(cost_cents),0) AS cents FROM dtf_local.machine_entries
WHERE machine_id=%s AND kind='supply' AND created_at>=%s AND created_at<%s
GROUP BY item''', (mid, start, end)).fetchall()
quantities = {row['item']: row['quantity'] for row in supplies}
supplies_cents = int(sum((row['cents'] for row in supplies), 0))
parts_cents = int(c.execute('''SELECT COALESCE(sum(cost_cents),0) AS cents
FROM dtf_local.machine_entries WHERE machine_id=%s AND kind='part'
AND created_at>=%s AND created_at<%s''', (mid, start, end)).fetchone()['cents'])
stops = c.execute('''SELECT note, COALESCE(sum(stop_minutes),0) AS minutes
FROM dtf_local.machine_entries WHERE machine_id=%s AND kind='event' AND item='stop'
AND created_at>=%s AND created_at<%s GROUP BY note ORDER BY minutes DESC, note''',
(mid, start, end)).fetchall()
stop_list = [{'reason': row['note'] or '', 'hours': round(float(row['minutes']) / 60, 1)}
for row in stops if row['minutes']]
stopped = round(sum(float(row['minutes']) for row in stops) / 60, 1)
values = ratios(printed, hours_running=hours, supplies_cents=supplies_cents,
parts_cents=parts_cents, rolls=quantities.get('film'),
inks={item: quantities.get(item) for item in INK_ITEMS},
powder=quantities.get('powder'))
return {
'printed_metres': round(float(printed), 2),
'hours_running': hours,
'metres_per_hour': values['metres_per_hour'],
'stopped_hours': stopped,
'stops': stop_list,
'metres_per_roll': values['metres_per_roll'],
'ink_per_100m': values['ink_per_100m'],
'powder_g_per_100m': values['powder_g_per_100m'],
'supplies_cents': supplies_cents,
'parts_cents': parts_cents,
'supplies_per_metre_cents': values['supplies_per_metre_cents'],
'parts_per_metre_cents': values['parts_per_metre_cents'],
'total_per_metre_cents': values['total_per_metre_cents'],
'sold_cents': sold,
'contribution_cents': sold - supplies_cents - parts_cents,
}
def since_installation(c, machine, until):
"""{'from': date, 'contribution_cents', 'parts_cents', 'months': float,
'roi_pct': float|None, 'payback_months': float|None} from installed_on
(else log_since) to `until`."""
mid = machine['id']
if machine['installed_on'] is not None:
from_date = machine['installed_on']
start = datetime.combine(from_date, time.min, tzinfo=SAO_PAULO)
else:
start = machine['log_since'] or datetime.now(SAO_PAULO)
from_date = start.astimezone(SAO_PAULO).date()
sold = sum((_sold(row) for row in _printed_orders(c, mid, start, until)), 0)
cents = lambda kind: int(c.execute('''SELECT COALESCE(sum(cost_cents),0) AS cents
FROM dtf_local.machine_entries WHERE machine_id=%s AND kind=%s
AND created_at>=%s AND created_at<%s''', (mid, kind, start, until)).fetchone()['cents'])
supplies_cents, parts_cents = cents('supply'), cents('part')
contribution = sold - supplies_cents - parts_cents
seconds = (until - start).total_seconds()
months = round(float(Decimal(str(seconds)) / _MONTH_SECONDS), 1) if seconds > 0 else 0.0
values = ratios(0, price_cents=machine['price_cents'], contribution_cents=contribution,
installed_parts_cents=parts_cents, months=months)
return {'from': from_date, 'contribution_cents': contribution, 'parts_cents': parts_cents,
'months': months, 'roi_pct': values['roi_pct'],
'payback_months': values['payback_months']}
def report(c, month=None):
"""{'month': '2026-11', 'machines': [{'id', 'name', 'price_cents',
'installed_on', 'month': machine_month(...), 'total': since_installation(...)}]}
for every machine (active or not) that has entries or printed in the month,
plus every active one."""
start, end = month_bounds(month)
until = min(datetime.now(SAO_PAULO), end)
machines = c.execute('''SELECT id, name, price_cents, installed_on, log_since, active
FROM dtf_local.machines ORDER BY created_at, name''').fetchall()
entered = {str(row['machine_id']) for row in c.execute(
'''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
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
AND m.created_at>=%s AND m.created_at<%s''', (start, end)).fetchall()}
result = []
for machine in machines:
key = str(machine['id'])
if not (machine['active'] or key in entered or key in printed):
continue
result.append({'id': key, 'name': machine['name'], 'price_cents': machine['price_cents'],
'installed_on': machine['installed_on'],
'month': machine_month(c, machine, start, end),
'total': since_installation(c, machine, until)})
return {'month': start.strftime('%Y-%m'), 'machines': result}

90
app/machines.py Normal file
View File

@@ -0,0 +1,90 @@
"""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')
# 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):
"""Têxtil or UV, by the order's first item: what a machine prints."""
items = (order.get('snapshot') or {}).get('items') or [{}]
return 'uv' if items[0].get('mode') in ('uvfile', 'uv') else 'textil'
def order_metres(order):
return sum((Decimal(str(i.get('billed_metres') or 0)) for i in (order.get('snapshot') or {}).get('items') or []),
Decimal(0))
def loads(c):
"""Per machine id: metres and orders still open, and orders per stage."""
result = {}
for row in c.execute('''SELECT machine_id, state, snapshot FROM dtf_local.orders
WHERE machine_id IS NOT NULL AND cancelled_at IS NULL AND state=ANY(%s)''', (list(OPEN),)).fetchall():
load = result.setdefault(str(row['machine_id']), {'metres': Decimal(0), 'orders': 0, 'states': {}})
load['metres'] += order_metres(row)
load['orders'] += 1
load['states'][row['state']] = load['states'].get(row['state'], 0) + 1
return result
def rows(c, with_operators=False):
"""Every machine with its load, for the Kanban."""
machines = c.execute('''SELECT id, name, products, active, limit_metres, places FROM dtf_local.machines
ORDER BY created_at, name''').fetchall()
load = loads(c)
operators = {}
if with_operators:
# Who is on it now: the open sessions that chose it (item 12).
for r in c.execute('''SELECT DISTINCT ON (s.machine_id, o.id) s.machine_id, o.id, o.name, o.email, s.machine_at
FROM dtf_local.operator_sessions s JOIN dtf_local.operators o ON o.email=s.username AND o.active
WHERE s.machine_id IS NOT NULL AND s.expires_at>now()
ORDER BY s.machine_id, o.id, s.machine_at''').fetchall():
operators.setdefault(str(r['machine_id']), []).append(
{'id': str(r['id']), 'name': r['name'] or r['email'], 'since': r['machine_at']})
result = []
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'],
'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:
row['operators'] = operators.get(key, [])
result.append(row)
return result
def full(c, machine_id, order_id):
"""(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, 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'], 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, '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
WHERE o.state='imp' AND o.cancelled_at IS NULL AND o.machine_id IS NOT NULL''').fetchall()}

215
app/mail.py Normal file
View File

@@ -0,0 +1,215 @@
"""E-mail: the customers' account messages and order confirmation.
Messages are queued in the database inside the transaction that caused them
(an order paid, a password to recover) and sent by the worker, so a slow
or unreachable mail server never holds up a request and a failed send is
retried. MAIL_ADAPTER chooses where they go:
off nothing is queued and recovery offers WhatsApp instead (the default,
until the client's SMTP details arrive);
log kept in the database and written to the worker's log, for the local
stack, where there is no mail server;
smtp sent through SMTP_HOST as MAIL_FROM.
A recovery link or a signup code lets someone in, so its text is erased once
it is sent (or once it expired unsent); only its subject stays as a record.
Customer messages carry an HTML version (app/mail_html.py) beside the plain
text.
"""
import logging
import os
import smtplib
import ssl
from email.message import EmailMessage
from email.utils import formataddr, formatdate, make_msgid, parseaddr
from .core.pricing import sheet_label
ADAPTER = os.environ.get('MAIL_ADAPTER', 'off')
RESET_MINUTES = 60
CODE_MINUTES = 15
# Messages that let someone in: their text is erased once sent, or once they
# expired unsent (minutes).
SECRET_KINDS = {'reset': RESET_MINUTES, 'code': CODE_MINUTES}
MAX_ATTEMPTS = 12
log = logging.getLogger('dtf.mail')
def configured():
return ADAPTER in ('log', 'smtp')
def required_settings():
return ('SMTP_HOST', 'MAIL_FROM')
def queue(c, kind, to, subject, body, html=None):
"""Queue one message in the caller's transaction. Returns False when e-mail
is off, so the caller can say so instead of promising a message."""
if not configured():
return False
c.execute('INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body,html) VALUES(%s,%s,%s,%s,%s)',
(kind, to, subject, body, html))
return True
def order_paid(c, order, origin):
"""The customer's confirmation of a paid order, with a link to it in the
account. Not for an operator's test order."""
snapshot = order['snapshot']
customer = snapshot.get('customer') or {}
if not customer.get('mail'):
return False
from . import mail_html
method = 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()
paid = {'pix': 'Pix', 'card': 'cartão'}.get((method or {}).get('method'), '')
freight = snapshot.get('freight') or {}
if freight.get('service') == 'pickup':
delivery = 'Retirada em Franca-SP'
else:
delivery = freight.get('description') or 'Entrega'
if freight.get('days'):
delivery += f" · até {freight['days']} dias úteis"
rows = [('Itens', '\n'.join(f"{PRODUCTS.get(i.get('mode'), i.get('mode'))}{sheet_label(i)} · "
f"{str(i.get('billed_metres') or i.get('metres')).replace('.', ',')} m"
for i in snapshot.get('items', []))),
('Entrega', delivery)]
coupon = snapshot.get('coupon') or {}
if coupon:
rows.append((f"Cupom {coupon.get('code', '')}",
f"− {money(coupon.get('discount_cents') or 0)}"))
rows.append(('Total', money(snapshot.get('total_cents') or 0) + (f' · {paid}' if paid else '')))
number, link = order['number'], f"{origin}/conta/pedidos?order={order['id']}"
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
f'Seu pagamento foi aprovado e o pedido #{number} já está com a nossa equipe. '
'Agora a gente confere a arte e coloca na fila de impressão.', '',
*(f'{key}: {value}' for key, value in rows), '',
f'Acompanhe cada etapa em Minha conta: {link}', '',
'Ainda não tem conta? Crie com este e-mail e o mesmo CPF/CNPJ do pedido: ele aparece lá na hora.'])
return queue(c, 'order', customer['mail'], f'Recebemos seu pedido #{number} · DTF Dropstar', text,
mail_html.order_paid(customer.get('name'), number, rows, link))
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · 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):
"""The customer's notice that an approved, unpaid order expired after 24 h
(Fase 2, front 9): its files were deleted and they can send it again on
the Site. Returns whether it was queued (False without an e-mail)."""
customer = (quote.get('draft') or {}).get('customer') or {}
if not customer.get('mail'):
return False
from . import mail_html
link = f'{origin}/'
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
'Seu pedido não foi pago em 24 horas e expirou. Os arquivos que você enviou foram apagados.', '',
f'Quando quiser, é só montar de novo no site: {link}'])
html = mail_html.layout('Seu pedido não foi pago em 24 horas e expirou.', 'Seu pedido', [
mail_html.pill('Pedido expirado', 'info'),
mail_html.title('Seu pedido expirou'),
mail_html.para(f'{mail_html.greeting(customer.get("name"))} Seu pedido não foi pago em 24 horas e '
'expirou. Os arquivos que você enviou foram apagados.'),
mail_html.button('Montar de novo', link),
mail_html.small(f'Quando quiser, é só montar de novo no site: {link}'),
])
return queue(c, 'notice', customer['mail'], 'Seu pedido expirou · DTF Dropstar', text, html)
def money(cents):
whole, cents = divmod(int(cents), 100)
return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}'
def message(to, subject, body, html=None):
sender = os.environ.get('MAIL_FROM', 'DTF Dropstar <nao-responda@localhost>')
name, address = parseaddr(sender)
msg = EmailMessage()
msg['From'] = formataddr((name or 'DTF Dropstar', address))
msg['To'] = to
msg['Subject'] = subject
# Neither EmailMessage nor smtplib adds it, and filters (Outlook's among them) count it missing.
msg['Date'] = formatdate(localtime=True)
msg['Message-ID'] = make_msgid(domain=address.split('@')[-1] or None)
reply = os.environ.get('MAIL_REPLY_TO', '')
if reply:
msg['Reply-To'] = reply
msg.set_content(body)
if html:
msg.add_alternative(html, subtype='html')
return msg
def send_smtp(msg):
host = os.environ['SMTP_HOST']
security = os.environ.get('SMTP_SECURITY', 'starttls')
port = int(os.environ.get('SMTP_PORT') or (465 if security == 'ssl' else 587))
user, password = os.environ.get('SMTP_USER', ''), os.environ.get('SMTP_PASSWORD', '')
context = ssl.create_default_context()
if security == 'ssl':
server = smtplib.SMTP_SSL(host, port, timeout=20, context=context)
else:
server = smtplib.SMTP(host, port, timeout=20)
with server:
if security == 'starttls':
server.starttls(context=context)
if user:
server.login(user, password)
server.send_message(msg)
def deliver(row):
msg = message(row['to_addr'], row['subject'], row['body'], row.get('html'))
if ADAPTER == 'smtp':
send_smtp(msg)
else:
log.warning('mail (%s) to %s: %s', ADAPTER, row['to_addr'], row['subject'])
def send_pending(connect, limit=5, ids=None):
"""Send what is due, a few at a time. Called by the worker every second;
`ids` sends just those messages, due or not (the tests use it)."""
if not configured():
return
with connect() as c:
# A link or a code that expired before it could be sent is useless.
for kind, minutes in SECRET_KINDS.items():
c.execute("""UPDATE dtf_local.mail_queue SET body='', html=NULL, last_error='expirou sem ser enviado', failed_at=now()
WHERE kind=%s AND sent_at IS NULL AND failed_at IS NULL
AND created_at < now() - %s * interval '1 minute'""", (kind, minutes))
rows = c.execute('''SELECT * FROM dtf_local.mail_queue WHERE sent_at IS NULL AND failed_at IS NULL
AND (id = ANY(%s) OR (%s::bigint[] IS NULL AND available_at <= now()))
ORDER BY id FOR UPDATE SKIP LOCKED LIMIT %s''', (ids or [], ids, limit)).fetchall()
for row in rows:
try:
deliver(row)
except Exception as exc:
attempts = row['attempts'] + 1
gave_up = attempts >= MAX_ATTEMPTS
c.execute('''UPDATE dtf_local.mail_queue SET attempts=%s, last_error=%s,
available_at=now() + %s * interval '1 second',
failed_at=CASE WHEN %s THEN now() END WHERE id=%s''',
(attempts, str(exc)[:500], min(3600, 2 ** min(attempts + 3, 12)), gave_up, row['id']))
log.warning('mail to %s failed (attempt %s): %s', row['to_addr'], attempts, exc)
continue
# The local log keeps the text so the link can be followed by hand.
erase = row['kind'] in SECRET_KINDS and ADAPTER != 'log'
c.execute('''UPDATE dtf_local.mail_queue SET sent_at=now(), attempts=attempts+1, last_error=NULL,
body=CASE WHEN %s THEN '' ELSE body END, html=CASE WHEN %s THEN NULL ELSE html END
WHERE id=%s''', (erase, erase, row['id']))
def status(c):
"""What the Kanban's Integrações shows about e-mail."""
last = c.execute('SELECT max(sent_at) AS at FROM dtf_local.mail_queue').fetchone()['at']
failing = c.execute('''SELECT to_addr, last_error, created_at FROM dtf_local.mail_queue
WHERE sent_at IS NULL AND last_error IS NOT NULL ORDER BY id DESC LIMIT 1''').fetchone()
pending = c.execute('SELECT count(*) AS n FROM dtf_local.mail_queue WHERE sent_at IS NULL AND failed_at IS NULL').fetchone()['n']
return {'adapter': ADAPTER, 'from': os.environ.get('MAIL_FROM', '') if configured() else '',
'host': os.environ.get('SMTP_HOST', '') if ADAPTER == 'smtp' else '',
'last_sent': last, 'pending': pending,
'error': {'to': failing['to_addr'], 'error': failing['last_error'], 'at': failing['created_at']} if failing else None}

203
app/mail_html.py Normal file
View File

@@ -0,0 +1,203 @@
"""The customer e-mails' HTML, next to the plain text every message keeps.
Built for mail clients, not browsers: tables for layout, every style inline,
no web fonts or images (Outlook ignores flex, many clients block images until
asked), so it reads the same in Gmail, Outlook and phone apps. The look is
the Site's: the DROPSTAR wordmark in orange on black, a white card, orange
buttons. Every value put in is escaped here; callers pass plain text.
"""
from html import escape
ORANGE, INK, DARK_ORANGE = '#FFA81A', '#03060B', '#C25E00'
TEXT, MUTED, LINE = '#3A3733', '#5E5A54', '#ECE8E2'
FONT = "Inter, 'Helvetica Neue', Helvetica, Arial, sans-serif"
WHATSAPP = 'https://wa.me/5516994280056'
def greeting(name):
first = (name or '').split()
return f'Olá, {first[0]}!' if first else 'Olá!'
def layout(preheader, label, blocks):
"""The whole message: the dark header, the card holding `blocks` (already
HTML), and the footer. The preheader is the line inboxes show after the
subject."""
rows = ''.join(f'<tr><td style="padding:0 0 20px 0">{block}</td></tr>' for block in blocks)
return f'''<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="color-scheme" content="light">
<title>DTF Dropstar</title>
</head>
<body style="margin:0;padding:0;background:#EEEBE6">
<div style="display:none;max-height:0;overflow:hidden;opacity:0">{escape(preheader)}</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#EEEBE6">
<tr><td align="center" style="padding:32px 12px">
<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;font-family:{FONT}">
<tr><td style="background:{INK};border-radius:16px 16px 0 0;padding:22px 32px">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr>
<td style="font-family:{FONT};font-size:24px;font-weight:800;font-style:italic;letter-spacing:-0.5px;color:{ORANGE}">DROPSTAR
<span style="font-size:12px;font-style:normal;letter-spacing:1px;color:{INK};background:{ORANGE};border-radius:6px;padding:3px 7px;vertical-align:middle">DTF</span></td>
<td align="right" style="font-family:{FONT};font-size:12px;font-weight:600;letter-spacing:0.7px;text-transform:uppercase;color:#B9B4AC">{escape(label)}</td>
</tr></table>
</td></tr>
<tr><td style="background:#FFFFFF;border-radius:0 0 16px 16px;padding:36px 36px 16px 36px">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">{rows}</table>
</td></tr>
<tr><td align="center" style="padding:22px 8px 0 8px;font-family:{FONT};font-size:12.5px;line-height:19px;color:{MUTED}">
DTF Dropstar · Franca-SP · WhatsApp <a href="{WHATSAPP}" style="color:{MUTED}">16 99428-0056</a><br>
E-mail automático, não precisa responder.
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>
'''
def title(text):
return (f'<h1 style="margin:0;font-family:{FONT};font-size:26px;line-height:32px;font-weight:800;'
f'color:{INK}">{escape(text)}</h1>')
def para(text):
return f'<p style="margin:0;font-family:{FONT};font-size:16px;line-height:25px;color:{TEXT}">{escape(text)}</p>'
def small(text, html=''):
return (f'<p style="margin:0;font-family:{FONT};font-size:13.5px;line-height:21px;color:{MUTED}">'
f'{escape(text)}{html}</p>')
def pill(text, tone='ok'):
background, color = {'ok': ('#E7F4EA', '#1E6B34'), 'info': ('#FFF4E0', DARK_ORANGE)}[tone]
return (f'<span style="display:inline-block;font-family:{FONT};font-size:12.5px;font-weight:700;'
f'letter-spacing:0.7px;text-transform:uppercase;background:{background};color:{color};'
f'border-radius:999px;padding:5px 11px">{escape(text)}</span>')
def code_box(code):
spaced = '&nbsp;'.join(escape(code))
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">'
f'<tr><td align="center" style="background:#FFF4E0;border:1px solid #F5D9A8;border-radius:12px;padding:22px">'
f'<div style="font-family:{FONT};font-size:12px;font-weight:700;letter-spacing:1.2px;'
f'text-transform:uppercase;color:{DARK_ORANGE}">Seu código</div>'
f'<div style="font-family:{FONT};font-size:38px;line-height:48px;font-weight:800;letter-spacing:6px;'
f'color:{INK}">{spaced}</div></td></tr></table>')
def button(text, url, dark=False):
background, color = (INK, ORANGE) if dark else (ORANGE, '#241703')
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td align="center">'
f'<a href="{escape(url, quote=True)}" style="display:inline-block;background:{background};color:{color};'
f'font-family:{FONT};font-size:16px;font-weight:800;text-decoration:none;border-radius:10px;'
f'padding:15px 30px">{escape(text)}</a></td></tr></table>')
def facts(rows):
cells = ''.join(
f'<tr><td style="{"" if i == 0 else f"border-top:1px solid {LINE};"}padding:12px 16px;width:92px;'
f'vertical-align:top;font-family:{FONT};font-size:15px;font-weight:600;color:{MUTED}">{escape(key)}</td>'
f'<td style="{"" if i == 0 else f"border-top:1px solid {LINE};"}padding:12px 16px 12px 0;'
f'font-family:{FONT};font-size:15px;line-height:22px;font-weight:500;color:{INK};white-space:pre-line">{escape(value)}</td></tr>'
for i, (key, value) in enumerate(rows))
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" '
f'style="border:1px solid {LINE};border-radius:12px;border-collapse:separate">{cells}</table>')
def callout(heading, text, warn=False):
background, border, color = ('#FFF1EC', '#F4C7B6', '#8A2A0A') if warn else ('#F4F2EE', '#E4DFD8', TEXT)
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr>'
f'<td style="background:{background};border:1px solid {border};border-radius:12px;padding:16px 18px">'
f'<div style="font-family:{FONT};font-size:15px;font-weight:700;color:{color}">{escape(heading)}</div>'
f'<div style="font-family:{FONT};font-size:14.5px;line-height:22px;color:{TEXT};padding-top:4px">'
f'{escape(text)}</div></td></tr></table>')
def steps(items):
"""The order's stages: (label, hint, done)."""
rows = []
for i, (label, hint, done) in enumerate(items):
top = '' if i == 0 else 'border-top:1px solid #F1EDE7;'
mark = (f'<div style="width:24px;height:24px;line-height:24px;border-radius:12px;background:{ORANGE};'
f'color:#241703;font-family:{FONT};font-size:14px;font-weight:800;text-align:center">&#10003;</div>'
if done else
'<div style="width:20px;height:20px;border-radius:12px;border:2px solid #D9D3CB;background:#FFFFFF"></div>')
rows.append(f'<tr><td style="{top}padding:11px 14px 11px 0;width:24px;vertical-align:middle">{mark}</td>'
f'<td style="{top}padding:11px 0;font-family:{FONT}">'
f'<div style="font-size:15px;font-weight:{700 if done else 500};color:{INK if done else MUTED}">'
f'{escape(label)}</div><div style="font-size:13px;line-height:19px;color:{MUTED}">{escape(hint)}</div>'
f'</td></tr>')
return (f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" '
f'style="border:1px solid {LINE};border-radius:12px;border-collapse:separate;padding:4px 16px">'
f'{"".join(rows)}</table>')
# The messages ---------------------------------------------------------------
def code(name, heading, purpose, digits, minutes, ignore):
return layout(f'{digits} é o seu código', 'Sua conta', [
title(heading),
para(f'{greeting(name)} Use o código abaixo para {purpose}.'),
code_box(digits),
small(f'O código vale por {minutes} minutos. Se não foi você que pediu, ignore este e-mail: {ignore}'),
])
def reset(name, link, minutes):
hours = 'por 1 hora' if minutes == 60 else f'por {minutes} minutos'
return layout('Clique no botão para criar uma nova senha.', 'Sua conta', [
title('Crie uma nova senha'),
para(f'{greeting(name)} Recebemos um pedido para criar uma nova senha na sua conta. '
'É só clicar no botão abaixo.'),
button('Criar nova senha', link),
small(f'O link vale {hours} e funciona uma vez só. Se não foi você, ignore este e-mail: '
'sua senha continua a mesma.'),
small('O botão não abriu? Copie este endereço no navegador: ',
f'<br><a href="{escape(link, quote=True)}" style="color:{DARK_ORANGE};word-break:break-all">'
f'{escape(link)}</a>'),
])
def account_exists(name, login_link):
return layout('Este e-mail já tem conta no DTF Dropstar.', 'Sua conta', [
title('Este e-mail já tem uma conta'),
para(f'{greeting(name)} Alguém tentou criar uma conta no DTF Dropstar com este e-mail, mas ele já está '
'cadastrado. Para ver seus pedidos, é só entrar.'),
button('Entrar na minha conta', login_link),
callout('Esqueceu a senha?', 'Na página de entrada, clique em “Esqueci minha senha” e enviamos um link '
'para criar outra.'),
small('Se não foi você, ignore este e-mail: nada muda na sua conta.'),
])
def email_changed(name, old, new):
return layout('O e-mail da sua conta foi trocado.', 'Sua conta', [
title('O e-mail da sua conta foi trocado'),
para(f'{greeting(name)} A partir de agora, sua conta no DTF Dropstar entra com outro e-mail:'),
facts([('Antes', old), ('Agora', new)]),
callout('Não foi você?', 'Fale com a Dropstar agora pelo WhatsApp: a gente ajuda a recuperar a conta.',
warn=True),
button('Falar no WhatsApp', WHATSAPP, dark=True),
])
def order_paid(name, number, rows, link):
return layout(f'Pagamento aprovado. O pedido #{number} já está com a nossa equipe.', 'Seu pedido', [
pill('Pagamento aprovado'),
title(f'Recebemos seu pedido #{number}'),
para(f'{greeting(name)} Seu pagamento foi aprovado e o pedido já está com a nossa equipe. Agora a gente '
'confere a arte e coloca na fila de impressão.'),
facts(rows),
steps([('Pagamento aprovado', 'Pedido recebido pela equipe', True),
('Arte conferida', 'A equipe confere se está tudo certo para imprimir', False),
('Impressão', 'Seu filme entra na máquina', False),
('Pronto', 'Você recebe o aviso pelo WhatsApp', False)]),
button('Ver meu pedido', link),
small('Acompanhe cada etapa em Minha conta. Ainda não tem conta? Crie com este e-mail e o mesmo CPF/CNPJ '
'do pedido: ele aparece lá na hora.'),
])

View File

@@ -21,12 +21,14 @@ import hmac
import json
import os
import time
from datetime import datetime, timedelta, timezone
from decimal import Decimal, InvalidOperation
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
@@ -35,6 +37,32 @@ MAX_SIGNATURE_AGE = 30 * 60
STATUSES = {'approved': 'approved', 'pending': 'pending', 'in_process': 'pending',
'authorized': 'pending', 'in_mediation': 'pending', 'rejected': 'rejected',
'cancelled': 'cancelled', 'refunded': 'refunded', 'charged_back': 'refunded'}
# A PIX code stops working after this; Mercado Pago then cancels the payment.
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:
@@ -43,7 +71,13 @@ class MercadoPagoPayment:
def __init__(self, access_token=None, webhook_secret=None, notification_url=None,
transport=None, clock=time.time):
self.access_token = access_token or os.environ.get('MP_ACCESS_TOKEN', '')
self.webhook_secret = (webhook_secret or os.environ.get('MP_WEBHOOK_SECRET', '')).encode()
# Trimmed: a space or line break pasted with the secret into the stack
# changes every HMAC, and Mercado Pago's own secret has none.
raw_secret = webhook_secret or os.environ.get('MP_WEBHOOK_SECRET', '')
self.webhook_secret = raw_secret.strip().encode()
self.secret_was_trimmed = raw_secret != raw_secret.strip()
# Which signed text matched the last notification verified (see verify).
self.last_signature = None
self.notification_url = notification_url or os.environ.get('MP_NOTIFICATION_URL', '')
if not self.access_token or not self.webhook_secret:
raise RuntimeError('Mercado Pago needs MP_ACCESS_TOKEN and MP_WEBHOOK_SECRET')
@@ -66,35 +100,54 @@ 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': '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
if method['type'] == 'pix':
body['payment_method_id'] = 'pix'
expires_at = (datetime.now(BRASILIA) + timedelta(minutes=PIX_MINUTES)).isoformat(timespec='milliseconds')
body['date_of_expiration'] = expires_at
elif method['type'] == 'card':
body.update(token=method['token'], payment_method_id=method['payment_method_id'],
installments=int(method.get('installments', 1)))
if method.get('issuer_id'):
body['issuer_id'] = method['issuer_id']
# 3-D Secure (the bank's confirmation) only for debit, which needs
# 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'
# 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").
else:
raise ValueError('Unsupported payment method')
# A PIX retry must return the same code. A card retry after a decline
# is a new attempt with a new token, so the token is part of the key;
# the intent route refuses new attempts once one is approved or in review.
key = f'dtf-quote-{quote_id}-pix' if method['type'] == 'pix' else \
# A PIX retry must return the same code; a new one, after the last
# expired, is the next attempt. A card retry after a decline is a new
# attempt with a new token, so the token is part of the key; the intent
# route refuses new attempts once one is approved or in review.
key = f"dtf-quote-{quote_id}-pix-{int(method.get('attempt', 1))}" if method['type'] == 'pix' else \
f"dtf-quote-{quote_id}-card-{hashlib.sha256(method['token'].encode()).hexdigest()[:24]}"
response = self.http.post('/v1/payments', json=body, headers={'X-Idempotency-Key': key})
response.raise_for_status()
payment = response.json()
transaction = (payment.get('point_of_interaction') or {}).get('transaction_data') or {}
# A payment waiting for 3-D Secure carries the bank's challenge page,
# which the Site shows in a frame by posting `creq` to that address.
three_ds = payment.get('three_ds_info') or {}
challenge = ({'url': three_ds['external_resource_url'], 'creq': three_ds['creq']}
if payment.get('status_detail') == 'pending_challenge'
and three_ds.get('external_resource_url') and three_ds.get('creq') else None)
return {'provider': self.name, 'id': str(payment['id']),
'status': STATUSES.get(payment.get('status'), 'pending'),
'status_detail': payment.get('status_detail'),
'total_cents': total_cents,
'pix_qr_code': transaction.get('qr_code'),
'pix_qr_code_base64': transaction.get('qr_code_base64'),
'ticket_url': transaction.get('ticket_url')}
'ticket_url': transaction.get('ticket_url'),
'expires_at': payment.get('date_of_expiration') or expires_at,
'challenge': challenge}
def lookup(self, payment_id: str) -> dict:
response = self.http.get(f'/v1/payments/{payment_id}')
@@ -104,6 +157,12 @@ class MercadoPagoPayment:
# Webhooks ------------------------------------------------------------
def verify(self, headers: Mapping[str, str], body: bytes, query: Mapping[str, str] | None = None) -> bool:
"""The notification is Mercado Pago's when its x-signature is the HMAC of
the documented text (id, request-id, ts) under our secret. A few close
variants of that text are also tried, each still needing the secret, so
a format that differs from the documentation is accepted and named in
self.last_signature rather than silently refused."""
self.last_signature = None
signature = headers.get('x-signature') or ''
parts = dict(part.strip().split('=', 1) for part in signature.split(',') if '=' in part)
ts, supplied = parts.get('ts', ''), parts.get('v1', '')
@@ -111,18 +170,28 @@ class MercadoPagoPayment:
return False
if abs(self.clock() - int(ts[:10])) > MAX_SIGNATURE_AGE:
return False
data_id = (query or {}).get('data.id', '')
if data_id.isalnum():
data_id = data_id.lower()
manifest = ''
if data_id:
manifest += f'id:{data_id};'
request_id = headers.get('x-request-id') or ''
if request_id:
manifest += f'request-id:{request_id};'
manifest += f'ts:{ts};'
expected = hmac.new(self.webhook_secret, manifest.encode(), hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, supplied.lower())
query_id = (query or {}).get('data.id', '')
try:
body_id = str(((json.loads(body) or {}).get('data') or {}).get('id') or '')
except (ValueError, AttributeError):
body_id = ''
def text(data_id, with_request=True):
manifest = f'id:{data_id};' if data_id else ''
if with_request and request_id:
manifest += f'request-id:{request_id};'
return manifest + f'ts:{ts};'
lowered = query_id.lower() if query_id.isalnum() else query_id
variants = [('documentado', text(lowered)), ('sem request-id', text(lowered, False)),
('id sem minúsculas', text(query_id)), ('id do corpo', text(body_id))]
for name, manifest in variants:
expected = hmac.new(self.webhook_secret, manifest.encode(), hashlib.sha256).hexdigest()
if hmac.compare_digest(expected, supplied.lower()):
self.last_signature = name
return True
return False
def parse(self, body: bytes, query: Mapping[str, str] | None = None) -> PaymentEvent | None:
try:
@@ -134,7 +203,15 @@ class MercadoPagoPayment:
payment_id = str((query or {}).get('data.id') or (data.get('data') or {}).get('id') or '')
if not payment_id.isdigit():
return None
payment = self.lookup(payment_id)
try:
payment = self.lookup(payment_id)
except httpx.HTTPStatusError as error:
# Signed by Mercado Pago but about no payment of ours, such as the
# panel's "Simular notificação". Anything else is raised so that a
# real notification is retried.
if error.response.status_code == 404:
return None
raise
return event_from_payment(payment, notification_id=str(data.get('id', '')))

65
app/mercadopago_probe.py Normal file
View File

@@ -0,0 +1,65 @@
"""Read-only look at the Mercado Pago account behind MP_ACCESS_TOKEN.
python -m app.mercadopago_probe [--bin 503143] [--valor 50]
Run from the api container's console (Portainer > Containers > api >
Console), or with "Verificar conta" on the Kanban's Integrations tab. It creates nothing and charges nothing: it asks Mercado Pago which
account the token belongs to, which card methods the account accepts, and how
it classifies a card number's first digits (type, issuer, instalments). That
is what payment errors such as 10111 (issuer) and 10113 (method excluded by a
rule) depend on.
"""
import argparse
import os
import sys
import httpx
from .core.secrets import load as load_secret_files
API = 'https://api.mercadopago.com'
def check(token, bin_='548083', amount='50', transport=None):
"""The account, its card methods and how a card's first digits are read."""
http = httpx.Client(base_url=API, timeout=15, transport=transport,
headers={'Authorization': f'Bearer {token}'})
result = {'token': 'test' if token.startswith('TEST-') else 'production'}
me = http.get('/users/me')
if me.status_code == 200:
user = me.json()
tags = user.get('tags') or []
result['account'] = {'id': user.get('id'), 'nickname': user.get('nickname'),
'site': user.get('site_id'), 'test_user': 'test_user' in tags, 'tags': tags}
else:
result['account'] = {'error': f'HTTP {me.status_code}'}
methods = http.get('/v1/payment_methods')
result['cards'] = ([{'id': m.get('id'), 'type': m.get('payment_type_id'), 'status': m.get('status')}
for m in methods.json() if m.get('payment_type_id') in ('credit_card', 'debit_card')]
if methods.status_code == 200 else {'error': f'HTTP {methods.status_code}'})
options = http.get('/v1/payment_methods/installments', params={'bin': bin_, 'amount': amount})
result['bin'] = ([{'method': o.get('payment_method_id'), 'type': o.get('payment_type_id'),
'issuer': (o.get('issuer') or {}).get('name'),
'installments': [c.get('installments') for c in o.get('payer_costs') or []]}
for o in options.json()]
if options.status_code == 200 else {'error': f'HTTP {options.status_code} {options.text[:200]}'})
return result
def main(argv=None):
parser = argparse.ArgumentParser(prog='python -m app.mercadopago_probe')
parser.add_argument('--bin', default='548083', help="the card's first six digits")
parser.add_argument('--valor', default='50', help='amount in reais for the instalment lookup')
args = parser.parse_args(argv)
load_secret_files()
token = os.environ.get('MP_ACCESS_TOKEN', '')
if not token:
print('MP_ACCESS_TOKEN is not set in this container.')
return 1
import json
print(json.dumps(check(token, args.bin, args.valor), indent=2, ensure_ascii=False))
return 0
if __name__ == '__main__':
sys.exit(main())

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

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

@@ -7,11 +7,15 @@ existing deployment keeps working unchanged.
Administered from the API container, the same way the schema is:
python -m local.operators list
python -m local.operators add maria@example.com --name "Maria"
python -m local.operators password maria@example.com
python -m local.operators disable maria@example.com
python -m local.operators enable maria@example.com
python -m app.operators list
python -m app.operators add maria@example.com --name "Maria" [--role admin]
python -m app.operators role maria@example.com superadmin
python -m app.operators password maria@example.com
python -m app.operators disable maria@example.com
python -m app.operators enable maria@example.com
The superadmin is the system's own account and is only set here; the
administrators manage everyone else on the Kanban's Usuários page.
Passwords are read from the terminal, never from an argument, so they do not
reach shell history or the process list.
@@ -21,10 +25,10 @@ import os
import sys
from uuid import uuid4
from .core.auth import password_hash
from .core.auth import ROLES, password_hash
from .core.db import connect
MIN_PASSWORD = 12
MIN_PASSWORD = 8
def seed_from_environment(cursor):
@@ -40,9 +44,11 @@ def seed_from_environment(cursor):
existing = cursor.execute(
'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',roles=ARRAY['superadmin'] WHERE email=%s", (email,))
return None
cursor.execute(
'INSERT INTO dtf_local.operators(id,email,name,password_hash) VALUES(%s,%s,%s,%s)',
"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
@@ -56,14 +62,27 @@ def _ask_password(email):
return first
def add(email, name=''):
def add(email, name='', role='admin'):
email = email.strip().lower()
if role not in ROLES:
raise SystemExit('Role must be one of: ' + ', '.join(ROLES))
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) VALUES(%s,%s,%s,%s)',
(uuid4(), email, name, password_hash(_ask_password(email))))
print(f'Added {email}.')
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}.')
def set_role(email, role):
email = email.strip().lower()
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,roles=%s WHERE email=%s RETURNING id',
(role, [role], email)).fetchone():
raise SystemExit(f'{email} does not exist.')
print(f'{email} is now {role}.')
def password(email):
@@ -93,7 +112,7 @@ def set_active(email, active):
def listing():
with connect() as c:
rows = c.execute('''SELECT email,name,active,last_login_at FROM dtf_local.operators
rows = c.execute('''SELECT email,name,role,active,last_login_at FROM dtf_local.operators
ORDER BY email''').fetchall()
if not rows:
print('No operator accounts. Set OPERATOR_EMAIL and OPERATOR_PASSWORD and run'
@@ -102,7 +121,7 @@ def listing():
for row in rows:
seen = row['last_login_at'].strftime('%Y-%m-%d %H:%M') if row['last_login_at'] else 'never'
state = 'active ' if row['active'] else 'DISABLED'
print(f"{state} {row['email']:<34} {row['name'][:20]:<20} last login {seen}")
print(f"{state} {row['email']:<34} {row['name'][:20]:<20} {row['role']:<10} last login {seen}")
def main(argv):
@@ -116,7 +135,12 @@ def main(argv):
email = rest[0]
if command == 'add':
name = rest[rest.index('--name') + 1] if '--name' in rest else ''
return add(email, name)
role = rest[rest.index('--role') + 1] if '--role' in rest else 'admin'
return add(email, name, role)
if command == 'role':
if len(rest) < 2:
raise SystemExit('usage: python -m app.operators role <email> <role>')
return set_role(email, rest[1])
if command == 'password':
return password(email)
if command == 'disable':

91
app/package.py Normal file
View File

@@ -0,0 +1,91 @@
"""The package an order ships in, as every carrier is quoted for it.
The weight comes from the client (a base per box plus a weight per billed
metre of film) and has no default: a carrier refuses to start without it, so
a guessed weight never prices a customer's freight. A box holds
JADLOG_METROS_POR_CAIXA metres; a longer order ships in as many boxes as it
needs, each with its own packaging weight. The box's sides (JADLOG_CAIXA_CM)
are what the Correios price by, and with the contract's factor
(JADLOG_CUBAGEM_KG_M3) what Jadlog's cubed weight is. The settings keep the
Jadlog names they had when Jadlog was the only carrier.
"""
import math
import os
import re
from decimal import Decimal
WEIGHT_SETTINGS = ('JADLOG_PESO_BASE_KG', 'JADLOG_PESO_POR_METRO_KG')
GRAMS = Decimal('0.001')
def box_cm(text):
"""The box's three sides in cm from "56x14x14" ("56 × 14 × 14", "56,5x14x14")."""
sides = [Decimal(side.strip().replace(',', '.')) for side in re.split(r'[x×*]', text.lower())]
if len(sides) != 3 or any(side <= 0 for side in sides):
raise RuntimeError('JADLOG_CAIXA_CM takes three sides in cm, such as 56x14x14')
return sides
class Package:
def __init__(self):
self.base_kg = Decimal(os.environ['JADLOG_PESO_BASE_KG'])
self.per_metre_kg = Decimal(os.environ['JADLOG_PESO_POR_METRO_KG'])
# A carrier's time counts from collection; the order is printed first.
self.production_days = int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0)
if self.base_kg < 0 or self.per_metre_kg <= 0 or self.production_days < 0:
raise RuntimeError('Package weight and production days must be positive')
# A box without its factor (or a factor without a box) would price by a guess.
box = (os.environ.get('JADLOG_CAIXA_CM') or '').strip()
factor = (os.environ.get('JADLOG_CUBAGEM_KG_M3') or '').strip()
if bool(box) != bool(factor):
raise RuntimeError('Set JADLOG_CAIXA_CM and JADLOG_CUBAGEM_KG_M3 together, or neither')
self.box_cm = box_cm(box) if box else None
self.cubage_kg_m3 = Decimal(factor.replace(',', '.')) if factor else None
if self.cubage_kg_m3 is not None and self.cubage_kg_m3 <= 0:
raise RuntimeError('JADLOG_CUBAGEM_KG_M3 must be positive')
per_box = (os.environ.get('JADLOG_METROS_POR_CAIXA') or '').strip()
self.metres_per_box = Decimal(per_box.replace(',', '.')) if per_box else None
if self.metres_per_box is not None and self.metres_per_box <= 0:
raise RuntimeError('JADLOG_METROS_POR_CAIXA must be positive')
def boxes(self, metres=None):
"""How many boxes the order fills; one when the capacity is not set."""
if metres is None or self.metres_per_box is None:
return 1
return max(1, math.ceil(Decimal(str(metres)) / self.metres_per_box))
def real_kg(self, metres):
return (self.boxes(metres) * self.base_kg + self.per_metre_kg * Decimal(str(metres))).quantize(GRAMS)
def box_weights_kg(self, metres):
"""Each box's real weight: full boxes first, the rest in the last one."""
metres = Decimal(str(metres))
count = self.boxes(metres)
if count == 1:
return [self.real_kg(metres)]
full = (self.base_kg + self.per_metre_kg * self.metres_per_box).quantize(GRAMS)
rest = metres - self.metres_per_box * (count - 1)
return [full] * (count - 1) + [(self.base_kg + self.per_metre_kg * rest).quantize(GRAMS)]
def cubed_kg(self, metres=None):
"""The boxes' volume in m³ times the contract's factor (one box without a
length); None without a box."""
if not self.box_cm:
return None
a, b, c = self.box_cm
return (self.boxes(metres) * a * b * c / Decimal(1_000_000) * self.cubage_kg_m3).quantize(GRAMS)
def weight_kg(self, metres):
"""What Jadlog charges by: the larger of the real and the cubed weight."""
real, cubed = self.real_kg(metres), self.cubed_kg(metres)
return max(real, cubed) if cubed is not None else real
def status(self):
"""The package rule, as the Kanban's Integrações shows it."""
cubed = self.cubed_kg()
return {'base_kg': str(self.base_kg), 'per_metre_kg': str(self.per_metre_kg),
'production_days': self.production_days,
'box_cm': [str(side) for side in self.box_cm] if self.box_cm else None,
'cubage_kg_m3': str(self.cubage_kg_m3) if self.cubage_kg_m3 else None,
'cubed_kg': str(cubed) if cubed is not None else None,
'metres_per_box': str(self.metres_per_box) if self.metres_per_box else None}

94
app/payment_messages.py Normal file
View File

@@ -0,0 +1,94 @@
"""What to tell a customer when a payment does not go through.
Mercado Pago answers with codes: a refused card has a status_detail
("cc_rejected_insufficient_amount"), a request it cannot process has cause
codes (324, "invalid identification number"). Shown as they come, they read
like a crash. Each becomes one plain sentence that says what happened and
what the customer can do; the code itself goes to the log and, for the team,
stays on the Kanban.
"""
TRY_OTHER = 'Use outro cartão ou pague com PIX.'
# Mercado Pago's status_detail for a card payment it refused.
REJECTIONS = {
'cc_rejected_bad_filled_card_number': 'O número do cartão está incorreto. Confira e tente de novo.',
'cc_rejected_bad_filled_date': 'A data de validade do cartão está incorreta. Confira e tente de novo.',
'cc_rejected_bad_filled_security_code': 'O código de segurança (CVV) está incorreto. Confira e tente de novo.',
'cc_rejected_bad_filled_other': 'Algum dado do cartão está incorreto. Confira o nome, o CPF e a validade e tente de novo.',
'cc_rejected_insufficient_amount': 'O cartão não tem limite suficiente para este valor. ' + TRY_OTHER,
'cc_amount_rate_limit_exceeded': 'O cartão atingiu o limite de valor permitido. ' + TRY_OTHER,
'cc_rejected_call_for_authorize': 'O banco precisa autorizar este pagamento. Ligue para o banco emissor e '
'tente de novo, ou use outro cartão.',
'cc_rejected_card_disabled': 'O cartão está bloqueado ou ainda não foi ativado. Fale com o banco emissor '
'ou use outro cartão.',
'cc_rejected_invalid_installments': 'O cartão não aceita esse número de parcelas. Escolha outro número de parcelas.',
'cc_rejected_duplicated_payment': 'Um pagamento igual acabou de ser feito com este cartão. Se precisar pagar '
'de novo, use outro cartão ou PIX.',
'cc_rejected_max_attempts': 'O cartão atingiu o limite de tentativas. ' + TRY_OTHER,
'cc_rejected_high_risk': 'O pagamento foi recusado pela análise de segurança. ' + TRY_OTHER,
'rejected_high_risk': 'O pagamento foi recusado pela análise de segurança. ' + TRY_OTHER,
'cc_rejected_blacklist': 'Não foi possível pagar com este cartão. ' + TRY_OTHER,
'cc_rejected_card_type_not_allowed': 'Este tipo de cartão não é aceito. Use um cartão de crédito ou pague com PIX.',
'cc_rejected_3ds_challenge': 'O banco não confirmou o pagamento. Tente de novo ou use outro cartão.',
'cc_rejected_3ds_mandatory': 'O banco não confirmou o pagamento. Tente de novo ou use outro cartão.',
'cc_rejected_card_error': 'Não foi possível processar o cartão. Tente de novo ou use outro cartão.',
'cc_rejected_other_reason': 'O banco emissor recusou o pagamento. ' + TRY_OTHER,
'rejected_insufficient_data': 'Faltaram dados para processar o pagamento. Confira os dados e tente de novo.',
'rejected_by_regulations': 'Não foi possível pagar com este cartão. ' + TRY_OTHER,
}
REJECTED = 'O pagamento foi recusado. Confira os dados ou ' + TRY_OTHER[0].lower() + TRY_OTHER[1:]
# Mercado Pago's cause codes for a request it refused before charging.
CAUSES = {
'205': 'Informe o número do cartão.',
'208': 'Informe o mês de validade do cartão.',
'209': 'Informe o ano de validade do cartão.',
'212': 'Informe o CPF ou CNPJ do titular do cartão.',
'213': 'Informe o CPF ou CNPJ do titular do cartão.',
'214': 'Informe o CPF ou CNPJ do titular do cartão.',
'221': 'Informe o nome do titular como está no cartão.',
'224': 'Informe o código de segurança (CVV).',
'E301': 'O número do cartão está incorreto. Confira e tente de novo.',
'E302': 'O código de segurança (CVV) está incorreto. Confira e tente de novo.',
'316': 'O nome do titular está incorreto. Digite como está no cartão.',
'322': 'O CPF ou CNPJ do titular está incorreto. Confira e tente de novo.',
'323': 'O CPF ou CNPJ do titular está incorreto. Confira e tente de novo.',
'324': 'O CPF ou CNPJ do titular está incorreto. Confira e tente de novo.',
'325': 'A data de validade do cartão está incorreta. Confira e tente de novo.',
'326': 'A data de validade do cartão está incorreta. Confira e tente de novo.',
'2067': 'O CPF ou CNPJ do titular está incorreto. Confira e tente de novo.',
'3034': 'O número do cartão está incorreto. Confira e tente de novo.',
'4033': 'O cartão não aceita esse número de parcelas. Escolha outro número de parcelas.',
}
NOT_PROCESSED = 'Não foi possível processar o pagamento com este cartão. Confira os dados ou ' + \
TRY_OTHER[0].lower() + TRY_OTHER[1:]
UNAVAILABLE = 'O Mercado Pago não respondeu agora. Tente de novo em alguns instantes.'
def rejection(status_detail):
"""The sentence for a refused card payment."""
return REJECTIONS.get(status_detail or '', REJECTED)
def refusal(data):
"""The sentence for a request Mercado Pago refused (its JSON error body)."""
for cause in (data or {}).get('cause') or []:
if isinstance(cause, dict) and str(cause.get('code')) in CAUSES:
return CAUSES[str(cause.get('code'))]
return NOT_PROCESSED
# The reasons a quote cannot be paid (app.payments.PaymentRefused), as the customer reads them.
QUOTE_REFUSALS = {
'quote not found': 'Não encontramos este pedido. Monte o pedido de novo.',
'quote was never reviewed': 'Este pedido ainda está sendo conferido pela equipe. Você poderá pagar assim que for aprovado.',
'quote was discarded': 'Esta cotação foi cancelada. Monte o pedido de novo para pagar.',
'quote uses an obsolete production layout; request a new quote':
'Este pedido foi montado numa versão anterior do Site. Monte o pedido de novo para pagar.',
'quote expired before payment': 'O prazo de 24 horas para pagar este pedido acabou. Monte o pedido de novo para pagar.',
}
def quote_refusal(reason):
return QUOTE_REFUSALS.get(str(reason), 'Não foi possível pagar este pedido. Monte o pedido de novo.')

View File

@@ -6,17 +6,21 @@ or a second WhatsApp message. Every delivery is recorded under the provider's
own event id and applied inside one transaction, so a duplicate is a no-op and a
crash mid-way is retried rather than half-applied.
Order creation lives here rather than in a route because two paths reach it: the
webhook, and the local development checkout. They must agree.
Order creation lives here rather than in a route because the paths that reach
it must agree: the webhook, reconcile() (the provider asked directly) and the
local development checkout.
"""
import logging
from datetime import datetime, timedelta, timezone
from uuid import UUID, uuid4
from psycopg.types.json import Jsonb
from . import mail, proof
from .core.auth import audit
from .core.models import PRODUCTION_VERSIONS
from .printjobs import queue as queue_print_files
from .runtime import enqueue, upload_row
from .runtime import PUBLIC_ORIGIN, enqueue, upload_row
from .scanning import require_clean
QUOTE_VALID_HOURS = 24
@@ -34,15 +38,91 @@ def approved_quote(c, quote_id, owner=None):
raise PaymentRefused('quote not found')
if not row['approved']:
raise PaymentRefused('quote was never reviewed')
if any(item.get('production', {}).get('version') != 2 for item in row['approved']['items']):
if row.get('discarded_at'):
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')
return row
def create_order(c, quote, payment):
TEST_PROVIDER = 'teste'
def is_test(order):
"""An operator's test order: it goes through production and notifies no one."""
return (order.get('payment') or {}).get('provider') == TEST_PROVIDER
# An order paid outside the system (Pix or cash at the counter, a card machine,
# the customer's credit) and registered by the team from its Site quote
# (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 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')
# 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.
UNPAID_HOLD = '2 days'
# A quote waiting for an operator's review keeps its files this long.
REVIEW_HOLD = '7 days'
# Once paid, the order keeps its originals for this long from the upload.
ORDER_RETENTION = '30 days'
def quote_uploads(quote_or_draft):
return [uid for item in quote_or_draft['items'] for uid in item['uploads']]
def hold_uploads(c, upload_ids, interval):
"""Keep these files at least `interval` from now; never shortens a hold."""
c.execute('''UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, now()+%s::interval)
WHERE id=ANY(%s) AND purged_at IS NULL''', (interval, [str(u) for u in upload_ids]))
def release_files(c, uploads):
"""Expire these uploads now, except any another order or an open quote
still uses: a customer can buy the same file again. Returns how many."""
free = []
for upload in uploads:
used = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.print_files WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.print_parts WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i
WHERE i->'uploads' ? %s
UNION ALL SELECT 1 FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i
WHERE q.discarded_at IS NULL AND q.expired_at IS NULL
AND NOT EXISTS (SELECT 1 FROM dtf_local.orders x WHERE x.quote_id=q.id)
AND i->'uploads' ? %s
LIMIT 1''', (upload,) * 5).fetchone()
if not used:
free.append(upload)
if free:
c.execute('''UPDATE dtf_local.uploads SET expires_at=now() WHERE id=ANY(%s::uuid[])
AND purged_at IS NULL''', (free,))
return len(free)
def create_order(c, quote, payment, origin):
"""Create the order for a reviewed quote, or return the one already there.
`origin` is where it came from (D-21): each way in names its own.
Returns (order, created). The caller decides what to do about a duplicate;
the important part is that asking twice cannot produce two orders, because
@@ -58,13 +138,38 @@ def create_order(c, quote, payment):
require_clean(upload_row(c, UUID(upload_id), quote['owner']))
order = c.execute(
'INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s) RETURNING *',
(uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment))).fetchone()
'''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
VALUES(%s,%s,%s,%s,%s,%s) RETURNING *''',
(uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment), origin)).fetchone()
# Paid: the files are kept for the order's retention, counted from upload.
c.execute('''UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, created_at+%s::interval)
WHERE id=ANY(%s) AND purged_at IS NULL''', (ORDER_RETENTION, quote_uploads(approved)))
queue_print_files(c, order['id'], len(approved['items']))
for provider in ('tiny', 'whatsapp'):
enqueue(c, f"{order['id']}:paid:{provider}", provider,
{'order_id': str(order['id']), 'number': order['number'],
'event': 'payment_approved', 'order': approved})
if approved.get('proof'):
# The customer asked for a proof: the order waits for their word.
order = c.execute('''UPDATE dtf_local.orders SET contact_since=now(), contact_by='Site', contact_note=%s
WHERE id=%s RETURNING *''', (proof.CUSTOMER_NOTE, order['id'])).fetchone()
c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (order['id'],))
# An order with a proof gets its proof card (app/proof.py).
proof.create_child(c, order)
if is_test(order):
return order, True
# 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.
if payment.get('provider') == MANUAL_PROVIDER:
paid = {'method': payment['method'], 'outside': True}
else:
paid = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved'
ORDER BY created_at DESC LIMIT 1''', (quote['id'],)).fetchone()
enqueue(c, f"{order['id']}:paid:tiny", 'tiny',
{'order_id': str(order['id']), 'number': order['number'],
'event': 'payment_approved', 'order': approved, 'origin': origin,
'payment': dict(paid) if paid else {}})
return order, True
@@ -96,7 +201,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}'
@@ -118,8 +223,44 @@ 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})
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)')
def reconcile(connect, provider, quote_id=None, limit=20):
"""Ask the provider about the payments of quotes that have no order yet and
apply what it says, exactly as a notification would. A notification can be
refused, lost or late; the provider's API is the authority either way, and
the event id (payment id and status) makes a webhook and this the same
delivery, applied once. Returns the outcomes of what was new."""
if not hasattr(provider, 'lookup'):
return []
from .mercadopago import event_from_payment
with connect() as c:
rows = c.execute('''SELECT i.provider_payment_id FROM dtf_local.payment_intents i
LEFT JOIN dtf_local.orders o ON o.quote_id=i.quote_id
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()
outcomes = []
for row in rows:
# Asked outside any transaction: no lock is held while the provider answers.
try:
event = event_from_payment(provider.lookup(row['provider_payment_id']))
except Exception:
logging.exception('Payment reconciliation lookup failed')
continue
with connect() as c:
stored = record(c, provider.name, event)
if stored is None:
continue
outcome = apply(c, event)
c.execute('UPDATE dtf_local.payment_events SET processed_at=now(), outcome=%s WHERE id=%s',
(outcome, stored['id']))
audit('payment_reconciled', payment_event=event.event_id, status=event.status, outcome=outcome)
outcomes.append(outcome)
return outcomes

View File

@@ -26,10 +26,23 @@ from decimal import Decimal
from PIL import Image, ImageOps
from .core.models import PRODUCTION_VERSIONS
PT_PER_CM = 72 / 2.54
# Acrobat's page limit. Longer layouts scale user space with /UserUnit (PDF 1.6)
# rather than cutting the film into pages a RIP might print with gaps.
# Acrobat's page limit, 200 inches (5,08 m). A longer sheet is written at its
# real size, on one page: CorelDRAW, where Dropstar checks the files, ignores
# /UserUnit and showed a 12,8 m sheet at a third of its size (2026-10-28).
# PRINT_PAGE_SCALE=true goes back to scaling user space with /UserUnit (PDF
# 1.6), for software that refuses pages over the limit. Either way the film is
# never cut into pages a RIP might print with gaps.
MAX_PAGE_PT = 14400
def page_unit(width_pt, height_pt):
"""The page's /UserUnit: 1 (real size) unless PRINT_PAGE_SCALE is on."""
if os.environ.get('PRINT_PAGE_SCALE', 'false').strip().lower() != 'true':
return 1
return max(1, math.ceil(max(width_pt, height_pt) / MAX_PAGE_PT))
# How far a file's proportions may drift from the quoted size before the item
# is refused: rounding in the Site keeps real files well inside this.
ASPECT_TOLERANCE = 0.01
@@ -46,7 +59,8 @@ Image.MAX_IMAGE_PIXELS = None
class Unsupported(Exception):
"""This item cannot be generated automatically; the reason is for the operator."""
"""This item cannot be generated automatically. The reason is shown to the
operator on the Kanban, so it is written in Portuguese."""
class Name(str):
@@ -153,14 +167,14 @@ class SourceImage:
self.image = Image.open(path)
self.format = self.image.format
except Image.DecompressionBombError as exc:
raise Unsupported(f'"{name}" is too large to generate automatically') from exc
raise Unsupported(f'"{name}" é grande demais para gerar automaticamente') from exc
except Exception as exc:
raise Unsupported(f'"{name}" is not an image this generator can read') from exc
raise Unsupported(f'"{name}" não é uma imagem que o gerador consiga ler') from exc
if self.format not in SUPPORTED_FORMATS:
raise Unsupported(f'"{name}" is {self.format or "an unknown format"}; '
'only JPEG, PNG, WebP and TIFF are generated automatically')
raise Unsupported(f'"{name}" está em {self.format or "formato desconhecido"}; '
'só JPEG, PNG, WebP, TIFF e PDF são gerados automaticamente')
if getattr(self.image, 'n_frames', 1) > 1 and self.format != 'TIFF':
raise Unsupported(f'"{name}" is animated or has several frames')
raise Unsupported(f'"{name}" é animado ou tem vários quadros')
# Browsers draw a photo upright according to its EXIF orientation, and
# the Site measured it that way, so the print must too.
try:
@@ -181,8 +195,8 @@ class SourceImage:
return self._embed_jpeg(pdf)
width, height = self.image.size
if width * height > MAX_DECODED_PIXELS:
raise Unsupported(f'"{self.name}" has {width} x {height} px, more than the '
'generator decodes; prepare this item by hand')
raise Unsupported(f'"{self.name}" tem {width} × {height} px, mais do que o '
'gerador processa; prepare este item à mão')
return self._embed_pixels(pdf)
def _colorspace(self, pdf, mode):
@@ -235,7 +249,7 @@ class SourceImage:
elif mode in ('P', 'PA', 'RGB', 'RGBA', 'RGBa'):
color_mode = 'RGB'
else:
raise Unsupported(f'"{self.name}" uses the {mode} colour mode, which is not generated automatically')
raise Unsupported(f'"{self.name}" usa o modo de cor {mode}, que não é gerado automaticamente')
if has_alpha:
image = image.convert('RGBA' if color_mode == 'RGB' else 'LA')
width, height = image.size
@@ -304,29 +318,29 @@ class PdfPage:
try:
self.pdf = pikepdf.open(path)
except pikepdf.PasswordError as exc:
raise Unsupported(f'"{name}" is password-protected') from exc
raise Unsupported(f'"{name}" está protegido por senha') from exc
except Exception as exc:
raise Unsupported(f'"{name}" is not a PDF this generator can read') from exc
raise Unsupported(f'"{name}" não é um PDF que o gerador consiga ler') from exc
try:
pages = len(self.pdf.pages)
if pages != 1:
raise Unsupported(f'"{name}" has {pages} pages; only single-page PDFs are generated automatically')
raise Unsupported(f'"{name}" tem {pages} páginas; só PDFs de uma página são gerados automaticamente')
self.page = self.pdf.pages[0]
self.rotation = int(self.page.rotation) % 360
if self.rotation not in (0, 90, 180, 270):
raise Unsupported(f'"{name}" has an unsupported page rotation')
raise Unsupported(f'"{name}" tem uma rotação de página não suportada')
box = [float(v) for v in self.page.cropbox]
except Unsupported:
self.pdf.close()
raise
except Exception as exc:
self.pdf.close()
raise Unsupported(f'"{name}" has a page this generator cannot read') from exc
raise Unsupported(f'"{name}" tem uma página que o gerador não consegue ler') from exc
self.x0, self.y0 = min(box[0], box[2]), min(box[1], box[3])
self.w, self.h = abs(box[2] - box[0]), abs(box[3] - box[1])
if self.w <= 0 or self.h <= 0:
self.pdf.close()
raise Unsupported(f'"{name}" has an empty page')
raise Unsupported(f'"{name}" tem uma página vazia')
# As displayed, which is what the proportions are checked against.
self.size = (self.h, self.w) if self.rotation in (90, 270) else (self.w, self.h)
@@ -366,14 +380,15 @@ def open_source(path, name):
return SourceImage(path, name)
def check_layout(item, sizes, vector=()):
def check_layout(item, sizes, vector=(), proof=False):
"""Refuse a layout the file cannot reproduce faithfully. Returns the lowest
DPI of the raster sources (vector pages have none)."""
DPI of the raster sources (vector pages have none). A proof is free of
charge, so its zero billed metres must not reject the item's full sheet."""
production = item['production']
height = Decimal(str(production['height_cm']))
billed = Decimal(str(item['billed_metres'])) * 100
if height > billed + HEIGHT_TOLERANCE_CM:
raise Unsupported(f'layout is {height} cm long but only {billed} cm were billed')
if not proof and height > billed + HEIGHT_TOLERANCE_CM:
raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados')
lowest = None
for placement in production['placements']:
width_px, height_px = sizes[placement['source_index']]
@@ -384,8 +399,8 @@ def check_layout(item, sizes, vector=()):
drift = abs((width_px / height_px) / (width_cm / length_cm) - 1)
if drift > ASPECT_TOLERANCE:
source = production['sources'][placement['source_index']]
raise Unsupported(f'file {placement["source_index"] + 1} has proportions that do not match '
f'the quoted {source["width_cm"]} x {source["length_cm"]} cm')
raise Unsupported(f'o arquivo {placement["source_index"] + 1} tem proporções diferentes '
f'das cotadas ({source["width_cm"]} × {source["length_cm"]} cm)')
if placement['source_index'] in vector:
continue
dpi = width_px / (width_cm / 2.54)
@@ -393,10 +408,78 @@ def check_layout(item, sizes, vector=()):
return lowest
def render(item, files, out, title):
# The footer (Dropstar, 2026-10-21): a 1,5 cm band after the last piece with one
# line of black text on no background, saying which order, item, date and length
# the sheet is, so a sheet cut off or dropped in the room is still known. The band
# is outside the billed length: the page grows by it and never covers artwork.
FOOTER_CM = Decimal('1.5')
# The line about 1 cm tall, from the top of a "d" to the bottom of a "p"
# (Dropstar, 2026-10-28; it was 18 pt, about 0,6 cm), smaller only when the
# line would not fit the film's width (the 27 cm UV).
FOOTER_PT = 31
FOOTER_FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'}
# Helvetica's widths (thousandths of the size), regular and bold, for the
# characters the line uses; anything else counts as wide.
_HELVETICA = dict(zip(' ,-./0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\xb7',
[278, 278, 333, 278, 278] + [556] * 10 + [278] +
[667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611,
722, 667, 944, 667, 667, 611] +
[556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278,
556, 500, 722, 500, 500, 500] + [278]))
_HELVETICA_BOLD = dict(zip(' ,-./0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\xb7',
[278, 278, 333, 278, 278] + [556] * 10 + [333] +
[722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611,
722, 667, 944, 667, 667, 611] +
[556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333,
611, 556, 778, 556, 556, 500] + [278]))
def text_width(text, bold=False):
"""The width of `text` in Helvetica at size 1, in points."""
widths = _HELVETICA_BOLD if bold else _HELVETICA
return sum(widths.get(ch, 1000) for ch in text) / 1000
# Dropstar's logo (sent 2026-10-23): black on transparent, so no white base is
# printed around it. It takes the place of the brand's name at the line's start.
FOOTER_LOGO = os.path.join(os.path.dirname(__file__), 'assets', 'logo-dropstar.png')
FOOTER_LOGO_CM = 1.3
def footer_commands(text, logo_size=None, width_pt=57 * PT_PER_CM):
"""The footer's line, 0,5 cm from the left: the logo then the rest, or,
without a logo, the line's first part (the brand) in bold. It is
FOOTER_PT, or less when that would not fit `width_pt`, the film."""
brand, _, rest = text.partition(' · ')
# A warning closing the line (ESPELHADO) goes in bold.
rest, mark, _ = rest.rpartition(' · ESPELHADO') if rest.endswith(' · ESPELHADO') else (rest, '', '')
def literal(value):
raw = value.encode('cp1252', 'replace')
return b'(' + raw.replace(b'\\', b'\\\\').replace(b'(', b'\\(').replace(b')', b'\\)') + b')'
def sized(room, line):
fit = room / max(sum(text_width(part, bold) for part, bold in line), 1e-9)
return int(min(FOOTER_PT, fit))
x = 0.5 * PT_PER_CM
if logo_size:
height = FOOTER_LOGO_CM * PT_PER_CM
width = height * logo_size[0] / logo_size[1]
start = x + width + 0.4 * PT_PER_CM
size = sized(width_pt - start - x, [(rest, False), (mark, True)])
y = (float(FOOTER_CM) * PT_PER_CM - size * 0.7) / 2
bottom = (float(FOOTER_CM) * PT_PER_CM - height) / 2
return (b'q %s 0 0 %s %s %s cm /Logo Do Q\n' % (serialize(width), serialize(height), serialize(x), serialize(bottom))
+ b'q 0 g BT /F2 %d Tf %s %s Td %s Tj /F1 %d Tf %s Tj ET Q\n'
% (size, serialize(start), serialize(y), literal(rest), size, literal(mark)))
middle = ' · ' + rest if rest else ''
size = sized(width_pt - 2 * x, [(brand, True), (middle, False), (mark, True)])
y = (float(FOOTER_CM) * PT_PER_CM - size * 0.7) / 2
return (b'q 0 g BT /F1 %d Tf %s %s Td %s Tj /F2 %d Tf %s Tj /F1 %d Tf %s Tj ET Q\n'
% (size, serialize(x), serialize(y), literal(brand), size, literal(middle), size, literal(mark)))
def render(item, files, out, title, footer=None):
"""Write the PDF for one approved order item.
`files` maps each source index to (local path, original name). Returns the
`files` maps each source index to (local path, original name). With
`footer`, the page gets the footer band and that line in it. Returns the
evidence the Kanban shows: page size, what was billed, and the lowest DPI.
Raster sources are written by the streaming writer above. PDF sources are
@@ -404,8 +487,8 @@ def render(item, files, out, title):
exported as PDF keeps its vectors, fonts and transparency.
"""
production = item['production']
if production.get('version') != 2:
raise Unsupported('item uses an obsolete production layout')
if production.get('version') not in PRODUCTION_VERSIONS:
raise Unsupported('o item usa uma montagem antiga')
sources = []
try:
for index in range(len(production['sources'])):
@@ -415,12 +498,13 @@ def render(item, files, out, title):
lowest_dpi = check_layout(item, [source.size for source in sources], vector)
width_pt = float(production['film_width_cm']) * PT_PER_CM
height_pt = float(production['height_cm']) * PT_PER_CM
unit = max(1, math.ceil(max(width_pt, height_pt) / MAX_PAGE_PT))
page_cm = Decimal(str(production['height_cm'])) + (FOOTER_CM if footer else 0)
height_pt = float(page_cm) * PT_PER_CM
unit = page_unit(width_pt, height_pt)
first = tempfile.TemporaryFile() if vector else out
try:
write_rasters(production, sources, first, title, width_pt, height_pt, unit)
write_rasters(production, sources, first, title, width_pt, height_pt, unit, footer)
if vector:
first.seek(0)
add_vector_pages(production, sources, first, out, height_pt)
@@ -432,6 +516,8 @@ def render(item, files, out, title):
source.close()
return {'film_width_cm': str(production['film_width_cm']),
'height_cm': str(production['height_cm']),
'page_height_cm': str(page_cm),
'footer': footer,
'billed_metres': str(item['billed_metres']),
'placements': len(production['placements']),
'sources': len(sources),
@@ -440,7 +526,7 @@ def render(item, files, out, title):
'user_unit': unit}
def write_rasters(production, sources, out, title, width_pt, height_pt, unit):
def write_rasters(production, sources, out, title, width_pt, height_pt, unit, footer=None):
pdf = PdfWriter(out)
images = {index: source.embed(pdf) for index, source in enumerate(sources)
if isinstance(source, SourceImage)}
@@ -453,12 +539,20 @@ def write_rasters(production, sources, out, title, width_pt, height_pt, unit):
matrix = placement_matrix(placement, height_pt)
commands.append(b'q ' + b' '.join(serialize(v) for v in matrix) +
b' cm /Im%d Do Q\n' % placement['source_index'])
resources = {'XObject': {f'Im{index}': ref for index, ref in images.items()}}
if footer:
logo = SourceImage(FOOTER_LOGO, 'logo') if os.path.exists(FOOTER_LOGO) else None
if logo:
resources['XObject']['Logo'] = logo.embed(pdf)
logo.close()
commands.append(footer_commands(footer, logo.size if logo else None, width_pt))
resources['Font'] = {key: {'Type': Name('Font'), 'Subtype': Name('Type1'), 'BaseFont': Name(font),
'Encoding': Name('WinAnsiEncoding')} for key, font in FOOTER_FONTS.items()}
content = pdf.stream({'Filter': Name('FlateDecode')}, deflate(commands))
pages = pdf.alloc()
page_box = [0, 0, width_pt / unit, height_pt / unit]
page = {'Type': Name('Page'), 'Parent': pages, 'MediaBox': page_box, 'TrimBox': page_box,
'Resources': {'XObject': {f'Im{index}': ref for index, ref in images.items()}},
'Contents': content}
'Resources': resources, 'Contents': content}
if unit > 1:
page['UserUnit'] = unit
page_ref = pdf.obj(page)

View File

@@ -2,54 +2,178 @@
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 an ordinary upload row owned by an identity derived from the
order, already marked clean: its only inputs are artwork that passed the
malware scan, and the bytes are written here. The operator still decides
whether it becomes the final file; generation never approves anything.
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
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
file; generation never approves anything.
Sheets of several GB are the normal order: a PNG or a PDF is read band by
band, so its size does not matter. Any other file above LARGE_SOURCE_BYTES
is prepared by hand from the original.
"""
import io
import logging
import multiprocessing
import os
import shutil
import tempfile
import time
from queue import Empty
from datetime import timedelta
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, render
from .printfile import Unsupported
from .printpng import part_cuts, render
from . import proof
from .proof import PROOF_SHEET_CM
from .tiny import purchase_order
CLAIM_TIMEOUT = timedelta(minutes=15)
LOCAL = ZoneInfo('America/Sao_Paulo')
# 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}')
def proof_part(heights_cm, original_height_cm, fraction):
"""Which part of a split final holds the finest stroke, and where inside it.
`heights_cm` are the parts' heights in order, `fraction` the stroke's
position on the original film (0 at the top, 1 at the bottom). A single
part returns the same fraction, as before.
"""
heights = [float(height) for height in heights_cm]
if not heights:
return 0, 0.0
position = min(1.0, max(0.0, float(fraction or 0))) * float(original_height_cm)
start = 0.0
for index, height in enumerate(heights):
end = start + height
if position <= end or index == len(heights) - 1:
inside = (position - start) / height if height > 0 else 0.0
return index, min(1.0, max(0.0, inside))
start = end
return len(heights) - 1, 1.0
def png_height_cm(storage, row):
"""A PNG's height in cm at 300 DPI, from its header alone (a Range read)."""
head = storage.client.get_object(Bucket=storage.bucket, Key=row['object_key'],
Range='bytes=0-65535')['Body'].read()
with Image.open(io.BytesIO(head)) as image:
height_px = image.size[1]
return float(Decimal(height_px) * Decimal('2.54') / Decimal(300))
def queue(c, order_id, items, only_missing=False):
"""Queue (or re-queue) generation for every item of an order."""
for index in range(items):
if only_missing:
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, finished_at=NULL, detail='{}'
WHERE dtf_local.print_files.status IN ('failed','manual')''',
(uuid4(), order_id, index))
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 '''
+ 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 FROM dtf_local.print_files p
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)
ORDER BY p.created_at FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
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()
def _render_child(result_queue, job, item, uploads):
"""Render in a killable process: a stuck image decoder cannot hold a card forever."""
from .adapters import LocalS3Storage
try:
result_queue.put(('ready', produce(LocalS3Storage(), job, item, uploads)))
except Unsupported as reason:
result_queue.put(('manual', str(reason)))
except BaseException as exc:
logging.exception('Print file generation failed')
result_queue.put(('error', type(exc).__name__))
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(seconds)
if process.is_alive():
process.terminate()
process.join(5)
if process.is_alive():
process.kill()
process.join()
return 'timeout', None
try:
return result_queue.get(timeout=5)
except Empty:
return 'error', f'processo encerrou com código {process.exitcode}'
finally:
result_queue.close()
result_queue.join_thread()
def render_one(storage):
@@ -57,83 +181,269 @@ def render_one(storage):
job = claim(c)
if not job:
return False
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
attempts=attempts+1 WHERE id=%s''', (job['id'],))
token = uuid4()
item = job['snapshot']['items'][job['item_index']]
uploads = c.execute('''SELECT id,name,object_key,scan_state,purged_at,expires_at,
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,
# or from the part of it that holds the finest stroke when the film was
# cut into parts (item 13).
if job['parent_id']:
finals = c.execute('''SELECT u.id,u.object_key FROM dtf_local.order_files f
JOIN dtf_local.uploads u ON u.id=f.upload_id
LEFT JOIN dtf_local.print_parts p ON p.order_id=f.order_id
AND p.item_index=f.item_index AND p.upload_id=f.upload_id
WHERE f.order_id=%s AND f.item_index=%s AND f.kind='final' AND f.active
AND u.purged_at IS NULL AND u.expires_at>now()
ORDER BY p.part NULLS LAST, f.created_at''',
(job['parent_id'], item['proof_parent_item_index'])).fetchall()
if finals:
source = finals[0]
if len(finals) > 1:
heights = [png_height_cm(storage, row) for row in finals]
index, fraction = proof_part(heights, item['production']['height_cm'],
item.get('proof_y_fraction'))
source = finals[index]
job['proof_fraction'] = fraction
source_ids = [source['id']]
item = {**item, 'uploads': [str(source['id'])]}
job['proof_fallback'] = True
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)''',
([UUID(u) for u in item['uploads']],)).fetchall()
(source_ids,)).fetchall()
# Every generated file shares its order's artwork retention deadline.
expiry = c.execute('SELECT min(created_at)+interval \'30 days\' AS e FROM dtf_local.uploads WHERE id=ANY(%s)',
([UUID(u) for u in item['uploads']],)).fetchone()['e']
(source_ids,)).fetchone()['e']
by_id = {str(row['id']): row for row in uploads}
try:
result = produce(storage, job, item, by_id)
except Unsupported as reason:
finish(job, 'manual', {'reason': str(reason)})
if job.get('wait_for_treatment'):
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
except Exception as exc:
logging.exception('Print file generation failed')
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 {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
scratch, parts, detail = result
stored = []
try:
for path, name in parts:
uid = uuid4()
key = f'originals/{uid}'
storage.store(key, path, 'image/png')
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. 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
path, name, size, detail = result
try:
uid = uuid4()
key = f'originals/{uid}'
storage.store(key, path, 'application/pdf')
finally:
os.unlink(path)
shutil.rmtree(scratch, ignore_errors=True)
for part, (uid, _, size, _) in zip(detail['parts'], stored):
part.update(upload_id=str(uid), size=size)
with connect() as c:
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state,scan_reason,scanned_at)
VALUES(%s,%s,%s,%s,%s,'',true,%s,'clean','generated from scanned artwork',now())''',
(uid, generated_identity(job['order_id']), name, size, key, expiry))
current = c.execute('''SELECT 1 FROM dtf_local.print_files WHERE id=%s AND claim_token=%s
AND status='rendering' FOR UPDATE''', (job['id'], job['claim_token'])).fetchone()
if not current:
return True
for uid, name, size, key in stored:
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state,scan_reason,scanned_at)
VALUES(%s,%s,%s,%s,%s,'',true,%s,'clean','generated from scanned artwork',now())''',
(uid, generated_identity(job['order_id']), name, size, key, expiry))
# claimed_at stays: the Prumo report measures generation from the claim.
c.execute('''UPDATE dtf_local.print_files SET status='ready', upload_id=%s, detail=%s,
finished_at=now() WHERE id=%s''', (uid, Jsonb(detail), job['id']))
audit('print_file_ready', order=str(job['order_id']), item=job['item_index'])
finished_at=now(),claim_token=NULL WHERE id=%s''', (stored[0][0], Jsonb(detail), job['id']))
c.execute('DELETE FROM dtf_local.print_parts WHERE order_id=%s AND item_index=%s',
(job['order_id'], job['item_index']))
for number, (uid, _, _, _) in enumerate(stored, 1):
c.execute('INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id) VALUES(%s,%s,%s,%s)',
(job['order_id'], job['item_index'], number, uid))
if job['snapshot'].get('proof_of'):
c.execute('''UPDATE dtf_local.order_files SET active=false
WHERE order_id=%s AND item_index=%s AND kind='final' ''',
(job['order_id'], job['item_index']))
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','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
def store_tiles(storage, folder, upload_id):
"""A part's pieces for the Kanban's viewer (item 7), beside the files the
storage policy lets the service write: originals/tiles/<upload>/<level>/<index>.png."""
if not os.path.isdir(folder):
return
for level in sorted(os.listdir(folder)):
for strip in sorted(os.listdir(os.path.join(folder, level))):
storage.store(f'originals/tiles/{upload_id}/{level}/{strip}', os.path.join(folder, level, strip), 'image/png')
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); 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):
"""The print file's footer line: DROPSTAR · Pedido DTF-123 · Item 1/2 ·
21/10/2026 · 0,90 m, and · ESPELHADO when the artwork is mirrored. The
order is named by its Kanban number, which Tiny keeps; the length is the
one billed."""
count = len(job['snapshot']['items'])
day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y')
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',')
proof_of = job['snapshot'].get('proof_of')
if proof_of:
return ' · '.join(['DROPSTAR', f'PROVA do #{proof_of}',
f'Classe {item.get("stroke_class") or "C3"}', day])
fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}',
f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m']
# A mirrored artwork (UV only) is named on the sheet, for the room to see
# before printing (Dropstar, 2026-10-23).
if any(source.get('mirrored') for source in item['production']['sources']):
fields.append('ESPELHADO')
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 (pdf path, name, size, evidence)."""
"""Fetch the item's artwork and render it. Returns (folder, [(png path,
name)], evidence); the caller removes the folder."""
if not (item.get('production') or {}).get('placements'):
raise Unsupported('o item não tem montagem: prepare o arquivo à mão')
for upload_id in item['uploads']:
row = uploads.get(upload_id)
if not row or row['scan_state'] != 'clean':
raise Unsupported('an original file is missing or not cleared by the malware scan')
raise Unsupported('um arquivo original está ausente ou não foi liberado pelo antivírus')
if row['purged_at'] or row['expired']:
raise Unsupported('an original file has passed its retention period')
number = job['number']
name = f'pedido-{number}-item-{job["item_index"] + 1}.pdf'
with tempfile.TemporaryDirectory(prefix='print-') as scratch:
files = {}
for index, upload_id in enumerate(item['uploads']):
local = os.path.join(scratch, f'source-{index}')
storage.fetch(uploads[upload_id]['object_key'], local)
files[index] = (local, uploads[upload_id]['name'])
handle, output = tempfile.mkstemp(prefix='print-', suffix='.pdf')
try:
with os.fdopen(handle, 'wb') as out:
detail = render(item, files, out, f'Pedido {number} - item {job["item_index"] + 1}')
except BaseException:
os.unlink(output)
raise
return output, name, os.path.getsize(output), detail
raise Unsupported('um arquivo original passou do prazo de guarda')
output = tempfile.mkdtemp(prefix='print-')
try:
with tempfile.TemporaryDirectory(prefix='print-') as scratch:
files = {}
for index, upload_id in enumerate(item['uploads']):
local = os.path.join(scratch, f'source-{index}')
storage.fetch(uploads[upload_id]['object_key'], local)
files[index] = (local, uploads[upload_id]['name'])
if job.get('proof_fallback'):
with Image.open(files[0][0]) as final:
width_px, height_px = final.size
width_cm = float(Decimal(width_px) * Decimal('2.54') / Decimal(300))
height_cm = float(Decimal(height_px) * Decimal('2.54') / Decimal(300))
if job.get('proof_fraction') is not None:
# Already relative to the chosen part (proof_part).
fraction = float(job['proof_fraction'])
else:
original_height = float(item['production']['height_cm'])
fraction = min(1, float(item.get('proof_y_fraction') or 0) * original_height / height_cm)
source = {'kind': 'sheet', 'width_cm': width_cm, 'length_cm': height_cm,
'copies': 1, 'rotation_degrees': 0, 'mirrored': False, 'measurement': 'file'}
item = {**item, 'proof_y_fraction': fraction,
'production': {'version': 3, 'film_width_cm': width_cm,
'height_cm': height_cm, 'sources': [source],
'placements': [{'source_index': 0, 'copy_index': 0,
'x_cm': 0, 'y_cm': 0, 'width_cm': width_cm,
'length_cm': height_cm, 'rotation_degrees': 0,
'mirrored': False}]}}
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'], 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,
pictures=pictures_by_source(item, job.get('pictures')))
except BaseException:
shutil.rmtree(output, ignore_errors=True)
raise
return output, parts, detail
def finish(job, status, detail):
with connect() as c:
c.execute('''UPDATE dtf_local.print_files SET status=%s, detail=%s,
finished_at=CASE WHEN %s='pending' THEN NULL ELSE now() END,
claimed_at=NULL WHERE id=%s''', (status, Jsonb(detail), status, job['id']))
claimed_at=NULL,claim_token=NULL WHERE id=%s AND claim_token=%s AND status='rendering' ''',
(status, Jsonb(detail), status, job['id'], job['claim_token']))
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)

752
app/printpng.py Normal file
View File

@@ -0,0 +1,752 @@
"""The print file as a PNG (Dropstar's third round, item 13, 2026-10-29).
FlexiPRINT's Spot OK 1 preset makes the white underbase from transparency, and
it reads that reliably only from a PNG: the montador writes each order item as
a 300 DPI PNG with an alpha channel on a transparent background, the same file
from payment to Finalizado. The customer may still send PNG or PDF; the output
is always PNG, and nothing converts it afterwards.
A 57 cm x 15 m sheet is 6732 x 177165 px, 4,7 GB as pixels, so nothing here
holds a whole sheet: the film is composed and written in bands of rows.
- Writing: each band is encoded by Pillow without compression, which still
chooses each row's PNG filter, and its filtered rows go into one zlib stream
for the whole file.
- A long PNG sheet is read band by band the same way backwards: the next
band's compressed rows, behind the last decoded row unfiltered, are wrapped
as a small PNG of their own that Pillow decodes.
- A PDF page is rendered band by band at 300 DPI by PDFium, vector all the way.
- 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 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
import os
import struct
import zlib
from decimal import Decimal
from PIL import Image, ImageDraw, ImageFont, ImageOps
from .core.models import PRODUCTION_VERSIONS
from .printfile import (FOOTER_CM, FOOTER_LOGO, FOOTER_LOGO_CM, MAX_DECODED_PIXELS, SUPPORTED_FORMATS,
Unsupported, check_layout)
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'))
# A cut through artwork only when no gap between pieces is this close to the limit.
CUT_SEARCH_CM = Decimal('200')
BAND_ROWS = 512
# Above this a source is read band by band instead of decoded whole.
STREAM_ABOVE_PIXELS = 40_000_000
FOOTER_TEXT_CM = 1.1
Image.MAX_IMAGE_PIXELS = None
def px(cm):
return int(round(float(cm) * PX_PER_CM))
# ---- Writing ----------------------------------------------------------------
def _chunk(fp, kind, data):
fp.write(struct.pack('>I', len(data)) + kind + data)
fp.write(struct.pack('>I', zlib.crc32(kind + data) & 0xffffffff))
class PngWriter:
"""An RGBA PNG written band by band: only one band is ever in memory."""
def __init__(self, fp, width, height):
self.fp, self.width, self.height = fp, width, height
self.rows = 0
# 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))
per_metre = round(DPI / 0.0254)
_chunk(fp, b'pHYs', struct.pack('>IIB', per_metre, per_metre, 1))
def band(self, image):
"""Append `image` (RGBA, the film's width) below what is written."""
if image.mode != 'RGBA' or image.width != self.width:
raise ValueError('a band must be RGBA and as wide as the film')
rows = image.height
if self.rows + rows > self.height:
raise ValueError('more rows than the file has')
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):
out = self.z.compress(data)
if out:
self.pending.append(out)
if sum(map(len, self.pending)) >= 1 << 20:
self._flush()
def _flush(self):
if self.pending:
_chunk(self.fp, b'IDAT', b''.join(self.pending))
self.pending = []
def close(self):
if self.rows != self.height:
raise ValueError(f'{self.rows} of {self.height} rows written')
self.pending.append(self.z.flush())
self._flush()
_chunk(self.fp, b'IEND', b'')
# ---- Reading ----------------------------------------------------------------
class PngRows:
"""A PNG's rows in order, band by band, without decoding the whole image.
Only 8-bit, non-interlaced files: anything else is decoded whole.
"""
CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
def __init__(self, path):
self.fp = open(path, 'rb')
if self.fp.read(8) != b'\x89PNG\r\n\x1a\n':
raise Unsupported('o PNG está corrompido')
self.extra = []
while True:
size, kind = struct.unpack('>I4s', self.fp.read(8))
if kind == b'IDAT':
self.idat_left = size
break
data = self.fp.read(size)
self.fp.read(4)
if kind == b'IHDR':
self.width, self.height, depth, color, _, _, interlace = struct.unpack('>IIBBBBB', data)
self.ihdr = data
if depth != 8 or interlace or color not in self.CHANNELS:
raise Unsupported('PNG de 16 bits ou entrelaçado')
self.row_bytes = 1 + self.width * self.CHANNELS[color]
elif kind in (b'PLTE', b'tRNS'):
self.extra.append((kind, data))
elif kind == b'IEND':
raise Unsupported('o PNG não tem imagem')
self.inflate = zlib.decompressobj()
self.buffer = b''
self.done = 0 # rows decoded so far
self.previous = None # the last decoded row, raw
def _compressed(self, want):
"""At least `want` bytes of filtered rows, unless the file ends first."""
parts, have = [self.buffer], len(self.buffer)
while have < want:
if not self.idat_left:
self.fp.read(4)
size, kind = struct.unpack('>I4s', self.fp.read(8))
if kind != b'IDAT':
break
self.idat_left = size
block = self.fp.read(min(self.idat_left, 1 << 20))
self.idat_left -= len(block)
out = self.inflate.decompress(block)
parts.append(out)
have += len(out)
data = b''.join(parts)
self.buffer = data[want:]
return data[:want]
def band(self, rows):
"""The next `rows` rows (fewer at the end) as an image in the file's mode."""
rows = min(rows, self.height - self.done)
if rows <= 0:
return None
filtered = self._compressed(rows * self.row_bytes)
if len(filtered) != rows * self.row_bytes:
raise Unsupported('o PNG terminou antes da última linha')
lead = 1 if self.previous is not None else 0
out = io.BytesIO()
out.write(b'\x89PNG\r\n\x1a\n')
_chunk(out, b'IHDR', struct.pack('>II', self.width, rows + lead) + self.ihdr[8:])
for kind, data in self.extra:
_chunk(out, kind, data)
body = (b'\x00' + self.previous if lead else b'') + filtered
_chunk(out, b'IDAT', zlib.compress(body, 0))
_chunk(out, b'IEND', b'')
out.seek(0)
image = Image.open(out)
image.load()
if lead:
image = image.crop((0, 1, self.width, rows + 1))
self.previous = image.crop((0, rows - 1, self.width, rows)).tobytes()
self.done += rows
return image
def close(self):
self.fp.close()
def rgba(image):
if image.mode == 'RGBA':
return image
if image.mode in ('I;16', 'I;16B', 'I;16L', 'I'):
image = image.convert('I').point(lambda value: value * (1 / 257)).convert('L')
return image.convert('RGBA')
class Source:
"""One customer file: its size as the Site measured it, and its pixels."""
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
if self.pdf:
import pypdfium2
try:
self.document = pypdfium2.PdfDocument(path)
except Exception as exc:
raise Unsupported(f'"{name}" não é um PDF que o gerador consiga ler') from exc
if len(self.document) != 1:
count = len(self.document)
self.document.close()
raise Unsupported(f'"{name}" tem {count} páginas; só PDFs de uma página são gerados automaticamente')
self.page = self.document[0]
self.size = self.page.get_size() # as displayed, /Rotate applied
self.streamable = True
return
try:
image = Image.open(path)
except Exception as exc:
raise Unsupported(f'"{name}" não é uma imagem que o gerador consiga ler') from exc
if image.format not in SUPPORTED_FORMATS:
raise Unsupported(f'"{name}" está em {image.format or "formato desconhecido"}; '
'só JPEG, PNG, WebP, TIFF e PDF são gerados automaticamente')
# Pillow decodes a whole PNG to look for EXIF after the pixels; only
# an orientation ahead of them is read, as is a JPEG's.
try:
self.orientation = (image.getexif().get(0x0112, 1)
if image.format != 'PNG' or 'exif' in image.info else 1)
except Exception:
self.orientation = 1
width, height = image.size
self.size = (height, width) if self.orientation in (5, 6, 7, 8) else (width, height)
self.streamable = False
if image.format == 'PNG' and self.orientation == 1:
try:
PngRows(path).close()
self.streamable = True
except Unsupported:
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.cut = (top, bottom)
self.size = (width, height - top - bottom)
def decoded(self, width, height):
"""The whole file at (width, height) px, upright, RGBA."""
if self.pdf:
if width * height > MAX_DECODED_PIXELS:
raise Unsupported(f'"{self.name}" ficaria grande demais para montar; prepare este item à mão')
scale = width / self.size[0]
image = self.page.render(scale=scale, fill_color=(0, 0, 0, 0)).to_pil()
return rgba(image).resize((width, height), Image.LANCZOS) if image.size != (width, height) else rgba(image)
image = Image.open(self.path)
if image.width * image.height > MAX_DECODED_PIXELS:
raise Unsupported(f'"{self.name}" tem {image.width} × {image.height} px, mais do que o '
'gerador processa; prepare este item à mão')
image.load()
if self.orientation != 1:
image = ImageOps.exif_transpose(image)
image = rgba(image)
return image if image.size == (width, height) else image.resize((width, height), Image.LANCZOS)
def close(self):
if self.pdf:
self.document.close()
# ---- Pieces -----------------------------------------------------------------
class Piece:
"""One placement on the film, in pixels, able to give the rows of the film
it covers, in order."""
def __init__(self, placement, source):
self.source = source
self.x, self.y = px(placement['x_cm']), px(placement['y_cm'])
self.w = max(1, px(Decimal(str(placement['x_cm'])) + Decimal(str(placement['width_cm']))) - self.x)
self.h = max(1, px(Decimal(str(placement['y_cm'])) + Decimal(str(placement['length_cm']))) - self.y)
self.rotation = placement['rotation_degrees'] % 360
self.mirrored = placement['mirrored']
self.reader = None
@property
def streamed(self):
return (self.source.streamable and not self.rotation and not self.mirrored and
self.w * self.h > STREAM_ABOVE_PIXELS)
def rows(self, top, bottom, cache):
"""The piece's rows [top, bottom) in film coordinates, as RGBA."""
a, b = top - self.y, bottom - self.y
if not self.streamed:
return self._placed(cache).crop((0, a, self.w, b))
if self.source.pdf:
return self._pdf_rows(a, b)
return self._png_rows(a, b)
def _placed(self, cache):
"""The whole piece, turned and scaled, shared by every copy."""
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)
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:
# Clockwise, as the Site turns it.
image = image.rotate(-self.rotation, expand=True)
cache[key] = image if image.size == (self.w, self.h) else image.resize((self.w, self.h), Image.LANCZOS)
return cache[key]
def _pdf_rows(self, a, b):
page_w, page_h = self.source.size
scale = self.w / page_w
top_pt, bottom_pt = a / scale, max(0.0, page_h - b / scale)
image = self.source.page.render(scale=scale, crop=(0, bottom_pt, 0, top_pt),
fill_color=(0, 0, 0, 0)).to_pil()
image = rgba(image)
return image if image.size == (self.w, b - a) else image.resize((self.w, b - a), Image.LANCZOS)
def _png_rows(self, a, b):
"""Rows [a, b) of the piece from a PNG read in order, scaled to the piece."""
if self.reader is None:
self.reader = PngRows(self.source.path)
self.buffer, self.buffer_top = None, 0
sw, sh = self.reader.width, self.reader.height
# 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 = 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:
self.buffer = band
else:
joined = Image.new('RGBA', (sw, self.buffer.height + band.height))
joined.paste(self.buffer, (0, 0))
joined.paste(band, (0, self.buffer.height))
self.buffer = joined
if want_top > self.buffer_top: # rows no band will need again
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 + 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):
if self.reader:
self.reader.close()
self.reader = None
# ---- Parts and footer -------------------------------------------------------
# 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'])))
for p in production['placements']]
cuts = [Decimal(0)]
while height - cuts[-1] > limit:
start = cuts[-1]
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)]
# 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
the film. Without a measured fraction it starts at the top, as before."""
height = Decimal(str(height_cm))
if height <= 0:
return [Decimal(0), Decimal(0)]
span = min(height, Decimal(str(limit_cm)))
if fraction is None:
return [Decimal(0), span]
center = min(Decimal(1), max(Decimal(0), Decimal(str(fraction)))) * height
start = min(height - span, max(Decimal(0), center - span / 2))
return [start, start + span]
def _font(size):
return ImageFont.load_default(size=size)
def footer_band(text, width):
"""The footer, 1,5 cm, black on transparent: the logo, then the line."""
height = px(FOOTER_CM)
band = Image.new('RGBA', (width, height))
draw = ImageDraw.Draw(band)
x = px(0.5)
if os.path.exists(FOOTER_LOGO):
logo = rgba(Image.open(FOOTER_LOGO))
logo_h = px(FOOTER_LOGO_CM)
logo = logo.resize((max(1, round(logo.width * logo_h / logo.height)), logo_h), Image.LANCZOS)
band.alpha_composite(logo, (x, (height - logo_h) // 2))
x += logo.width + px(0.4)
text = text.partition(' · ')[2]
room = width - x - px(0.5)
size = px(FOOTER_TEXT_CM)
while size > 10 and draw.textlength(text, font=_font(size)) > room:
size -= 4
font = _font(size)
top, bottom = font.getbbox(text)[1], font.getbbox(text)[3]
draw.text((x, (height - (bottom - top)) // 2 - top), text, font=font, fill=(0, 0, 0, 255),
stroke_width=max(1, size // 40), stroke_fill=(0, 0, 0, 255))
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, 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`,
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']
if production.get('version') not in PRODUCTION_VERSIONS:
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'])
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, ranges, width, line,
tiles=os.path.join(out_dir, 'tiles', name) if tiles else None))
parts.append((path, name))
finally:
for source in sources:
source.close()
return parts, {'format': 'png', 'dpi': DPI,
'film_width_cm': str(production['film_width_cm']),
'height_cm': str(production['height_cm']),
'width_px': width,
'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']),
'sources': len(sources),
'vector_sources': len(vector),
'min_dpi': round(lowest) if lowest else None}
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)
band = Image.new('RGBA', (width, band_bottom - band_top))
for piece in pieces:
if piece.y >= band_bottom:
break
if piece.y + piece.h <= band_top:
continue
a, b = max(band_top, piece.y), min(band_bottom, piece.y + piece.h)
rows = piece.rows(a, b, cache)
left = max(0, -piece.x)
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))
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:
piece.close()
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]
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(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

64
app/printpng_validate.py Normal file
View File

@@ -0,0 +1,64 @@
"""Small, bounded header check for the final file FlexiPRINT receives.
The original upload may be PNG or PDF. A *final* file is a transparent,
8-bit RGBA PNG tagged 300 DPI. Read only header chunks before IDAT, so even
a multi-gigabyte sheet is checked without decoding or downloading the film.
"""
import struct
PNG = b'\x89PNG\r\n\x1a\n'
HEADER_BYTES = 1 << 20
def final_png_issue(data):
if not data.startswith(PNG):
return 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.'
at = len(PNG)
rgba = False
dpi = None
image_data = False
while at + 12 <= len(data):
size = struct.unpack('>I', data[at:at + 4])[0]
kind = data[at + 4:at + 8]
end = at + 12 + size
if kind == b'IDAT':
image_data = True
break
if end > len(data):
return 'O cabeçalho do PNG final está incompleto ou inválido.'
body = data[at + 8:at + 8 + size]
if kind == b'IHDR':
if at != 8 or size != 13:
return 'O cabeçalho do PNG final está inválido.'
width, height, depth, color, compression, filtering, interlace = struct.unpack('>IIBBBBB', body)
rgba = bool(width and height and depth == 8 and color == 6 and
compression == 0 and filtering == 0 and interlace == 0)
elif kind == b'pHYs' and size == 9:
x, y, unit = struct.unpack('>IIB', body)
if unit == 1 and x and y:
dpi = (x * .0254, y * .0254)
at = end
if not rgba:
return 'O PNG final precisa ter transparência (canal alfa RGBA de 8 bits).'
if not dpi or any(abs(axis - 300) > 1 for axis in dpi):
return 'O PNG final precisa estar marcado como 300 DPI nos dois eixos.'
if not image_data:
return 'O PNG final está incompleto: faltam os dados da imagem.'
return None
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'):
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}')
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)

107
app/printtiles.py Normal file
View File

@@ -0,0 +1,107 @@
"""The print file in pieces, for the Kanban's viewer (Dropstar's third round, item 7).
"Abrir e conferir" shows the PNG at up to 100% (one file pixel, one screen
pixel). A 57 cm x 15 m film is 160 million pixels per 2 m: loaded whole it
freezes the designer's computer, so the viewer loads it in pieces, like a map.
The pieces are strips of the film's whole width, STRIP_ROWS tall, at 100%
and at each halving down to a few strips for the whole film: level 0 is the
file itself, level k is 1/2^k of it. They are written while the PNG is, from
the same bands, so the file is never read back.
"""
import io
import math
from PIL import Image
STRIP_ROWS = 512
# Levels stop when the whole film fits in about one screen.
SMALLEST_ROWS = 1024
def levels_for(height):
"""How many levels a film of `height` px gets: halving until it is short."""
count = 1
while math.ceil(height / 2 ** (count - 1)) > SMALLEST_ROWS and count < 12:
count += 1
return count
class Pyramid:
"""Fed the film's bands from the top, it hands each finished strip, as a
PNG, to `emit(level, index, png_bytes)`."""
def __init__(self, width, height, emit):
self.width, self.height, self.emit = width, height, emit
self.levels = levels_for(height)
self.pending = [None] * self.levels # rows of each level not yet a strip
self.count = [0] * self.levels # strips written per level
# A level's odd last row waits for its pair.
self.odd = [None] * self.levels
def band(self, image):
self._feed(0, image)
def _feed(self, level, image):
if level >= self.levels:
return
rows = self.pending[level]
if rows is None:
rows = image
else:
joined = Image.new('RGBA', (image.width, rows.height + image.height))
joined.paste(rows, (0, 0))
joined.paste(image, (0, rows.height))
rows = joined
while rows.height >= STRIP_ROWS:
self._strip(level, rows.crop((0, 0, rows.width, STRIP_ROWS)))
rows = rows.crop((0, STRIP_ROWS, rows.width, rows.height)) if rows.height > STRIP_ROWS else None
if rows is None:
break
self.pending[level] = rows
# The next level down, from these rows, two by two.
self._halve(level, image)
def _halve(self, level, image):
if level + 1 >= self.levels:
return
if self.odd[level] is not None:
joined = Image.new('RGBA', (image.width, image.height + 1))
joined.paste(self.odd[level], (0, 0))
joined.paste(image, (0, 1))
image, self.odd[level] = joined, None
if image.height % 2:
self.odd[level] = image.crop((0, image.height - 1, image.width, image.height))
image = image.crop((0, 0, image.width, image.height - 1))
if image.height:
small = image.resize((max(1, math.ceil(image.width / 2)), image.height // 2), Image.BOX)
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()
writer = PngWriter(out, image.width, image.height)
writer.band(image)
writer.close()
self.emit(level, self.count[level], out.getvalue())
self.count[level] += 1
def close(self):
"""Flush what is left at each level, from the top level down."""
for level in range(self.levels):
if self.odd[level] is not None and level + 1 < self.levels:
last = self.odd[level]
self.odd[level] = None
self._feed(level + 1, last.resize((max(1, math.ceil(last.width / 2)), 1), Image.BOX))
if self.pending[level] is not None and self.pending[level].height:
self._strip(level, self.pending[level])
self.pending[level] = None
return self.manifest()
def manifest(self):
return {'width': self.width, 'height': self.height, 'strip_rows': STRIP_ROWS,
'levels': [{'scale': 1 / 2 ** k, 'width': math.ceil(self.width / 2 ** k),
'height': math.ceil(self.height / 2 ** k), 'strips': self.count[k]}
for k in range(self.levels)]}

156
app/proof.py Normal file
View File

@@ -0,0 +1,156 @@
"""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
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
they approve the photo sent by WhatsApp. Either way the room
marks "Prova OK" once the proof is checked, and without it the order does not
reach Finalizado.
"""
from decimal import Decimal
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.')
def billed_metres(snapshot):
return sum((Decimal(str(item.get('billed_metres') or 0)) for item in snapshot.get('items') or []), Decimal(0))
def needs_proof(snapshot):
"""Whether the order prints a proof first: asked for, or above 10 m."""
return bool(snapshot.get('proof')) or billed_metres(snapshot) > PROOF_ABOVE_METRES
# ---- The proof card (Dropstar's third round, 2026-10-30 and 2026-11-03) -----
#
# 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
# 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.
PROOF_SHEET_CM = Decimal('15')
# Three proofs at most per order, one per item (Dropstar, 2026-10-23).
MAX_PROOFS = 3
PROVIDER = 'prova'
def proof_identity(order_id):
return uuid5(NAMESPACE_URL, f'dtf-proof:{order_id}')
def create_child(c, parent):
"""The parent's proof card, in Arte recebida, its proof sheets queued to be
generated. Returns it, or None when the order needs no proof."""
if parent.get('parent_id') or not needs_proof(parent['snapshot']):
return None
from .printjobs import queue
# A class has one proof. When several items share it, use the one with the
# finest measured line; no metre or product value is sold on this card.
classes = {}
for index, item in enumerate(parent['snapshot']['items']):
kind = item.get('stroke_class') or 'C3'
width = item.get('stroke_px') or 10000
if kind not in classes or width < classes[kind][0]:
classes[kind] = (width, index, item)
selected = [classes[kind] for kind in ('C1', 'C2', 'C3') if kind in classes][:MAX_PROOFS]
proof_items = [{**item, 'billed_metres': '0', 'total_cents': 0, 'unit_cents': 0,
'proof_parent_item_index': index} for _, index, item in selected]
freight = {**parent['snapshot'].get('freight', {}), 'total_cents': 0}
snapshot = {**parent['snapshot'], 'items': proof_items, 'total_cents': 0,
'freight': freight, 'proof_of': parent['number']}
child = c.execute('''INSERT INTO dtf_local.orders(id,owner,snapshot,payment,origin,parent_id,machine_id,machine_chosen)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
(uuid4(), proof_identity(parent['id']), Jsonb(snapshot), Jsonb({'provider': PROVIDER}),
parent['origin'], parent['id'], parent.get('machine_id'), parent.get('machine_chosen', False))).fetchone()
queue(c, child['id'], len(snapshot['items']))
return child
def open_child(c, parent_id):
"""The parent's proof card still waiting for its answer, if any."""
return c.execute('''SELECT * FROM dtf_local.orders WHERE parent_id=%s AND proof_result IS NULL
AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (parent_id,)).fetchone()
def waiting(c, order):
"""Whether the order waits for its proof: it has a proof card without an OK."""
return not order.get('parent_id') and not order.get('proof_ok_at') and bool(open_child(c, order['id']))
def manual_source_needed(c, order):
"""A proof child cannot decode an original; prepare the full parent PNG first."""
if order.get('parent_id') or order['state'] != 'rec':
return False
child = open_child(c, order['id'])
return bool(child and c.execute('''SELECT 1 FROM dtf_local.print_files
WHERE order_id=%s AND status='manual' LIMIT 1''', (child['id'],)).fetchone())
def require_unlocked(c, order):
"""A parent cannot enter production or have its final changed before the proof answer."""
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:
c.execute('''UPDATE dtf_local.orders SET state='tra', 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,'rec','tra',%s,'Prova OK')''', (parent['id'], operator))
return ready

155
app/prumo.py Normal file
View File

@@ -0,0 +1,155 @@
"""What the Prumo did to an order, in the order it happened (front 6).
The Site and the browser already make every decision; this module only turns
the fields they left on the order into the short report the designer reads
before opening the file. Nothing here changes an order or a price.
"""
from datetime import datetime
from decimal import Decimal
from zoneinfo import ZoneInfo
LOCAL = ZoneInfo('America/Sao_Paulo')
MANUAL = {'cdr', 'psd', 'psb', 'tif', 'tiff'}
# The stroke class in the customer's words, without the internal C1/C2/C3 code.
STROKE_SUMMARY = {
'C1': 'Sua arte tem traços muito finos; a impressão foi ajustada para eles.',
'C2': 'Sua arte tem traços médios; a impressão foi ajustada para eles.',
'C3': 'Sua arte tem áreas cheias; a impressão foi ajustada para elas.',
}
def _ext(name):
return (str(name or '').rsplit('.', 1)[-1] if '.' in str(name or '') else '').lower()
def _m(value):
try:
return f'{Decimal(str(value)):.2f}'.replace('.', ',')
except Exception:
return str(value)
def _cm(value):
try:
return f'{Decimal(str(value)):.1f}'.replace('.', ',')
except Exception:
return str(value)
def _hora(value):
if not value:
return ''
try:
moment = value if isinstance(value, datetime) else datetime.fromisoformat(str(value).replace('Z', '+00:00'))
return ' às ' + moment.astimezone(LOCAL).strftime('%H:%M')
except Exception:
return ''
def report(order, uploads):
"""One line per action that happened, for the card and the customer.
`uploads` maps an upload id (as text) to a row with `name` and
`original_name`. `order` is the order row with its snapshot and generated
print files.
"""
snapshot = order.get('snapshot') or {}
items = snapshot.get('items') or []
generated = {row.get('item_index'): row for row in (order.get('print_files') or [])}
lines = []
if snapshot.get('proof_of'):
lines.append(f'Prova do pedido #{snapshot["proof_of"]}')
multi = len(items) > 1
for index, item in enumerate(items):
lead = f'Item {index + 1}: ' if multi else ''
names = []
for uid in item.get('uploads') or []:
row = uploads.get(str(uid)) or {}
original = row.get('original_name') or row.get('name') or ''
final = row.get('name') or original
names.append(final)
if original and final and _ext(original) != _ext(final):
lines.append(f'{lead}Chegou {_ext(original).upper()}, era {_ext(final).upper()} por dentro — tratado como {_ext(final).upper()}')
# One format line per item, not one per file: the designer reads what
# the item is, and only the files that changed are named above.
formats = sorted({_ext(name).upper() or 'desconhecido' for name in names})
if len(formats) == 1:
count = f' ({len(names)} arquivos)' if len(names) > 1 else ''
lines.append(f'{lead}Formato detectado: {formats[0]}{count}')
elif formats:
lines.append(f'{lead}Formatos detectados: {", ".join(formats)}')
exts = {_ext(name) for name in names}
row = generated.get(index)
ready = bool(row and row.get('status') == 'ready')
if row and row.get('status') == 'manual':
lines.append(f'{lead}Arquivo exige preparo manual')
dpi = item.get('source_dpi')
if dpi:
lines.append(f'{lead}Resolução detectada: {dpi} DPI')
if ready:
detail = row.get('detail') or {}
if exts & {'pdf', 'ai'} and detail.get('format') == 'png':
lines.append(f'{lead}PDF → PNG {detail.get("dpi", 300)} DPI')
elif detail.get('format'):
lines.append(f'{lead}Arquivo final em {detail["format"].upper()} {detail.get("dpi", 300)} DPI')
dots = int(item.get('residue_accepted') or 0)
if dots:
lines.append(f'{lead}{dots} ponto{"s" if dots > 1 else ""} < 2 mm — cliente aceitou' +
_hora(item.get('residue_accepted_at')))
production = item.get('production') or {}
placements = production.get('placements') or []
if item.get('mode') in ('avulsa', 'uv'):
rotated = sum(1 for p in placements if p.get('rotation_degrees') in (90, 270))
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"))})')
if item.get('stroke_px') and item.get('stroke_class'):
lines.append(f'{lead}Menor traço {item["stroke_px"]} px → {item["stroke_class"]}')
if item.get('stroke_choice') == 'client_c3':
lines.append(f'{lead}Aviso de traço fino disparou — cliente escolheu proteger as áreas chapadas (C3)')
elif item.get('stroke_choice') == 'measured':
lines.append(f'{lead}Aviso de traço fino disparou — cliente escolheu imprimir em C1')
else:
lines.append(f'{lead}Aviso de traço fino não disparou')
if row:
detail = row.get('detail') or {}
parts = detail.get('parts') or []
if len(parts) > 1:
sizes = [Decimal(str(p.get('to_cm', 0))) - Decimal(str(p.get('from_cm', 0))) for p in parts]
lines.append(f'{lead}{_m(billed)} m → {len(parts)} partes (' +
' + '.join(_m(size) for size in sizes) + ')')
# From the claim, not from the queue: the customer waits for the
# generation, not for the file's turn.
if ready and row.get('finished_at') and row.get('claimed_at'):
seconds = (row['finished_at'] - row['claimed_at']).total_seconds()
lines.append(f'{lead}Prumo levou {max(1, round(seconds))} s')
return lines
def customer_summary(items):
"""The same facts in the customer's words, for the summary before paying."""
lines = []
for index, item in enumerate(items or []):
lead = f'Item {index + 1}: ' if len(items) > 1 else ''
dpi = item.get('source_dpi')
if dpi and dpi < 300:
lines.append(f'{lead}Sua arte foi medida em {dpi} DPI. O arquivo de impressão será preparado em 300 DPI após o pagamento.')
dots = int(item.get('residue_accepted') or 0)
if dots:
lines.append(f'{lead}Há {dots} pontinho{"s" if dots > 1 else ""} solto{"s" if dots > 1 else ""} '
'que você aceitou imprimir.')
if item.get('stroke_class') in STROKE_SUMMARY:
lines.append(f'{lead}{STROKE_SUMMARY[item["stroke_class"]]}')
if item.get('stroke_choice') == 'measured':
lines.append(f'{lead}Você escolheu imprimir o traço fino assim mesmo (C1).')
elif item.get('stroke_choice') == 'client_c3':
lines.append(f'{lead}Você escolheu proteger as áreas chapadas (C3).')
return lines

132
app/quote_review.py Normal file
View File

@@ -0,0 +1,132 @@
"""Quote approval: automatic at checkout, by an operator for the exceptions.
A quote the customer can pay is priced here from the server's own prices,
whether an operator approved it on the Kanban or the Site approved it the
moment it was created. The Site is a shop: a customer who can price the order
should be able to pay for it straight away, at any hour, so only orders a
person must look at before charging wait for the Kanban (review_reason).
Each product has one price (Dropstar, 2026-10-23): the grade no longer changes
what is charged. It is still worked out in the customer's browser and shown
with the order, so it is checked against the files before an automatic
approval (app/grade_check.py); a grade the files do not support waits for
review. The layout is still the browser's (roadmap 3.9): the API checks its
geometry. Operators see every order's grade and artwork at Arte recebida.
"""
import os
from decimal import Decimal
from fastapi import HTTPException
from psycopg.types.json import Jsonb
from . import cart_pricing, payments
from .proof import PROOF_ABOVE_METRES
from .core.models import PRODUCTION_VERSIONS
from .runtime import freight, upload_row
from .scanning import require_clean
AUTO = 'auto'
def auto_approve_enabled():
return os.environ.get('QUOTE_AUTO_APPROVE', 'true').lower() == 'true'
def max_auto_metres():
return Decimal(os.environ.get('QUOTE_AUTO_MAX_METRES', '50'))
def review_reason(draft):
"""Why this quote needs a person before it can be paid, or None."""
if not auto_approve_enabled():
return 'Aprovação automática desligada'
total = sum(Decimal(str(item['metres'])) for item in draft['items'])
if total > max_auto_metres():
return f'Pedido acima de {max_auto_metres():g} m'
for item in draft['items']:
if item.get('production', {}).get('version') not in PRODUCTION_VERSIONS:
return 'Montagem antiga'
return None
def approve(c, row, items, reviewer):
"""Price the reviewed items and bind them to the quote; returns the approval.
`row` must be locked by the caller."""
draft = row['draft']
if row['approved']:
raise HTTPException(409, 'Esta cotação já foi aprovada e não pode mudar.')
if any(item.get('production', {}).get('version') not in PRODUCTION_VERSIONS for item in draft['items']):
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.')
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.close_pieces != original.get('close_pieces', 0) or item.stroke_class != original.get('stroke_class') or item.stroke_px != original.get('stroke_px') or item.stroke_choice != original.get('stroke_choice') or (item.split and item.split.model_dump()) != original.get('split'):
raise HTTPException(422, 'A montagem e a confirmação do cliente não podem mudar na revisão.')
for upload_id in item.uploads:
upload = upload_row(c, upload_id, row['owner'])
require_clean(upload)
names[str(upload_id)] = upload['name']
# 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))
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 {}),
# 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.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.
payments.hold_uploads(c, payments.quote_uploads(approved), payments.UNPAID_HOLD)
return approved

142
app/receipt.py Normal file
View File

@@ -0,0 +1,142 @@
"""The pickup receipt (Dropstar's third round, item 14, 2026-10-29).
A PDF for the counter's 80 mm thermal roll: the order number large at the
top, the customer and their CPF or CNPJ, each product and its metres, the
amount and how it was paid, when it was issued, and blank lines for the
date of pickup and the signature. Only for orders picked up in Franca: one
sent by a carrier has none. The Kanban's folder saves it in Recibos/, and the
counter's print queue sends it to the Bematech.
"""
import io
import unicodedata
from datetime import datetime
from .core.pricing import sheet_label
from .printfile import Name, PdfWriter, deflate, serialize, _HELVETICA, _HELVETICA_BOLD
from .printjobs import LOCAL, file_prefix
MM = 72 / 25.4
WIDTH = 80 * MM
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',
'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}
def code(order):
"""DTF-123: the order as the Kanban, the files and Tiny name it."""
return file_prefix(order['number'], 0).rsplit('-item-', 1)[0]
def is_pickup(snapshot):
return ((snapshot or {}).get('freight') or {}).get('service') == 'pickup'
def money(cents):
whole, cents = divmod(int(cents), 100)
return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}'
def document(value):
digits = ''.join(ch for ch in str(value or '') if ch.isdigit())
if len(digits) == 14:
return 'CNPJ', f'{digits[:2]}.{digits[2:5]}.{digits[5:8]}/{digits[8:12]}-{digits[12:]}'
if len(digits) == 11:
return 'CPF', f'{digits[:3]}.{digits[3:6]}.{digits[6:9]}-{digits[9:]}'
return 'CPF/CNPJ', str(value or '')
def width(text, bold=False):
"""The width of `text` in Helvetica at size 1: an accented letter is as
wide as its letter."""
table = _HELVETICA_BOLD if bold else _HELVETICA
total = 0
for ch in text:
base = unicodedata.normalize('NFD', ch)[0]
total += table.get(ch) or table.get(base) or EXTRA.get(ch) or 600
return total / 1000
def wrap(text, size, bold=False):
"""The text in lines that fit the roll, broken between words."""
lines, line = [], ''
for word in str(text).split():
attempt = f'{line} {word}' if line else word
if line and width(attempt, bold) * size > ROOM:
lines.append(line)
line = word
else:
line = attempt
return lines + [line] if line else lines or ['']
def literal(text):
raw = text.encode('cp1252', 'replace')
return b'(' + raw.replace(b'\\', b'\\\\').replace(b'(', b'\\(').replace(b')', b'\\)') + b')'
def lines(order, paid_with, issued):
"""What the receipt says, top to bottom: (text, size, bold, space before)."""
snapshot = order['snapshot']
customer = snapshot.get('customer') or {}
kind, number = document(customer.get('cnpj'))
name = code(order)
# The number as large as the roll takes, up to 34 pt.
big = min(34, int(ROOM / width(name, True)))
out = [('DROPSTAR · Recibo de retirada', 9, True, 0), (name, big, True, 4)]
if paid_with == 'teste':
out.append(('PEDIDO DE TESTE', 10, True, 2))
out.append(('Cliente', 7.5, False, 10))
out += [(part, 10, True, 1) for part in wrap(customer.get('name') or customer.get('mail') or '', 10, True)]
out += [(kind, 7.5, False, 6), (number, 10, False, 1)]
out.append(('Produto', 7.5, False, 10))
for item in snapshot.get('items') or []:
metres = str(item.get('billed_metres') or item.get('metres') or '').replace('.', ',')
out += [(part, 9.5, False, 2) for part in wrap(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))}{sheet_label(item)} — {metres} m", 9.5)]
coupon = snapshot.get('coupon') or {}
if coupon:
out.append((f"Cupom {coupon.get('code', '')}: - {money(coupon.get('discount_cents') or 0)}", 9, False, 4))
out += [('Valor', 7.5, False, 10), (money(snapshot.get('total_cents') or 0), 12, True, 1),
('Pagamento', 7.5, False, 6), (METHODS.get(paid_with, 'Teste' if paid_with == 'teste' else paid_with or '—'), 10, False, 1),
(f"Emitido em {issued.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')}", 8.5, False, 10),
('Retirado em ____/____/________', 10, False, 22),
('Assinatura ______________________', 10, False, 26)]
return out
def render(order, paid_with, issued=None):
"""The receipt's PDF bytes, 80 mm wide and as long as what it says."""
rows = lines(order, paid_with, issued or datetime.now(LOCAL))
height = MARGIN * 2 + sum(size * 1.2 + space for _, size, _, space in rows)
y = height - MARGIN
commands = [b'0 g\n']
for text, size, bold, space in rows:
y -= space + size
commands.append(b'BT /%s %s Tf %s %s Td %s Tj ET\n' % (b'F1' if bold else b'F2', serialize(size),
serialize(MARGIN), serialize(y), literal(text)))
y -= size * 0.2
out = io.BytesIO()
pdf = PdfWriter(out)
content = pdf.stream({'Filter': Name('FlateDecode')}, deflate(commands))
pages = pdf.alloc()
fonts = {key: {'Type': Name('Font'), 'Subtype': Name('Type1'), 'BaseFont': Name(font),
'Encoding': Name('WinAnsiEncoding')} for key, font in FONTS.items()}
box = [0, 0, WIDTH, height]
page = pdf.obj({'Type': Name('Page'), 'Parent': pages, 'MediaBox': box, 'Resources': {'Font': fonts},
'Contents': content})
pdf.obj({'Type': Name('Pages'), 'Kids': [page], 'Count': 1}, pages)
root = pdf.obj({'Type': Name('Catalog'), 'Pages': pages})
info = pdf.obj({'Title': f'Recibo {code(order)}',
'Producer': 'DTF System'})
pdf.finish(root, info)
return out.getvalue()
def file_name(order):
"""Recibo-DTF-123.pdf"""
return f'Recibo-{code(order)}.pdf'

131
app/reviews.py Normal file
View File

@@ -0,0 +1,131 @@
"""The review photo or video of the printed sheet (Fase 2, front 2).
In Revisão the card gets "Revisar": the Revisor takes a photo or a short video
(up to 30 s) of the sheet with the computer's or the phone's camera in the
browser, or sends one already recorded. It is attached to the order as
DTF-<n>-revisao-<seq>.<ext>, with when and who (dtf_local.order_reviews), and
the computers with the order folders turned on copy it to Kanban/Revisões/.
An order above 1 m cannot reach Finalizado without a photo; a smaller one may.
Once the order is in Finalizado, the customer's order page shows the photos
(the "ready" notice links to it). Videos stay on the card.
Kept for REVIEW_KEEP_DAYS, longer than artwork: it is the evidence when a
customer says the sheet came out wrong.
"""
from decimal import Decimal
from fastapi import HTTPException
from . import grade_check
from .proof import billed_metres
PHOTO_MIN_PX = 1600 # the longer side; enough to read the footer
VIDEO_MAX_SECONDS = 30 # enforced by the recorder and the file check in the browser
PHOTO_MAX_BYTES = 30 * 1048576
VIDEO_MAX_BYTES = 150 * 1048576
REQUIRED_ABOVE_METRES = Decimal('1')
REVIEW_KEEP_DAYS = 180
FOLDER = 'Revisões'
# Extension -> (kind, MIME). HEIC is left out: browsers cannot show it.
FORMATS = {'jpg': ('photo', 'image/jpeg'), 'jpeg': ('photo', 'image/jpeg'),
'png': ('photo', 'image/png'), 'webp': ('photo', 'image/webp'),
'mp4': ('video', 'video/mp4'), 'webm': ('video', 'video/webm'),
'mov': ('video', 'video/quicktime')}
def file_name(number, seq, ext):
"""DTF-13-revisao-1.jpg: the name in the folder and on the card."""
return f'DTF-{number}-revisao-{seq}.{ext}'
FORMAT_MESSAGE = ('Use foto JPG, PNG ou WebP de até 30 MB, ou vídeo MP4, WebM ou MOV de até 150 MB.')
# What each extension must start with. MP4 and MOV share the ISO container:
# the "ftyp" box sits at byte 4.
SIGNATURES = {'jpg': (b'\xff\xd8\xff', 0), 'jpeg': (b'\xff\xd8\xff', 0),
'png': (b'\x89PNG\r\n\x1a\n', 0),
'webp': (b'WEBP', 8),
'mp4': (b'ftyp', 4), 'mov': (b'ftyp', 4),
'webm': (b'\x1a\x45\xdf\xa3', 0)}
def kind_of(name, size):
"""('photo' | 'video', mime, ext) for an accepted file, or HTTPException 422
with a Portuguese message naming the accepted formats and size limits."""
ext = name.rsplit('.', 1)[-1].lower() if '.' in name else ''
if ext not in FORMATS:
raise HTTPException(422, FORMAT_MESSAGE)
kind, mime = FORMATS[ext]
limit = PHOTO_MAX_BYTES if kind == 'photo' else VIDEO_MAX_BYTES
if size > limit:
raise HTTPException(422, FORMAT_MESSAGE)
return kind, mime, ext
def check(storage, upload):
"""Read the start of the stored file (a Range read, as grade_check.Files.head)
and confirm its signature matches the extension. For a photo, return its
(width, height) and refuse (422) when the longer side is below PHOTO_MIN_PX;
for a video, return (None, None). Returns (kind, ext, width, height)."""
kind, mime, ext = kind_of(upload['name'], upload['size'])
head = storage.client.get_object(Bucket=storage.bucket, Key=upload['object_key'],
Range=f'bytes=0-{grade_check.HEAD_BYTES - 1}')['Body'].read()
# WebP is a RIFF container with its own form type, like the scanner's check.
if ext == 'webp':
matches = head[:4] == b'RIFF' and head[8:12] == b'WEBP'
else:
signature, offset = SIGNATURES[ext]
matches = head[offset:].startswith(signature)
if not matches:
raise HTTPException(422, 'O conteúdo do arquivo não corresponde à extensão.')
if kind == 'video':
return kind, ext, None, None
size = grade_check.image_size(head)
if not size or not all(size):
raise HTTPException(422, 'Não foi possível ler a foto.')
width, height = size
if max(width, height) < PHOTO_MIN_PX:
raise HTTPException(422, f'A foto precisa ter pelo menos {PHOTO_MIN_PX} px no lado maior para ler o rodapé.')
return kind, ext, width, height
def required(snapshot):
"""Whether finishing this order needs a review photo: billed metres above
REQUIRED_ABOVE_METRES (proof.billed_metres)."""
return billed_metres(snapshot) > REQUIRED_ABOVE_METRES
def has_photo(c, order_id):
return c.execute("SELECT 1 FROM dtf_local.order_reviews WHERE order_id=%s AND kind='photo' LIMIT 1",
(order_id,)).fetchone() is not None
def attach(c, order, upload, kind, ext, width, height, user):
"""Record the review: the next seq for the order, the upload renamed to
file_name(...) and kept REVIEW_KEEP_DAYS from now. Returns the new row."""
# The order's row is the lock: two reviewers adding at once take one seq
# each, never the same one.
c.execute('SELECT id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (order['id'],))
seq = c.execute('SELECT COALESCE(max(seq),0)+1 AS seq FROM dtf_local.order_reviews WHERE order_id=%s',
(order['id'],)).fetchone()['seq']
name = file_name(order['number'], seq, ext)
c.execute("UPDATE dtf_local.uploads SET name=%s, expires_at=now()+make_interval(days => %s) WHERE id=%s",
(name, REVIEW_KEEP_DAYS, upload['id']))
row = c.execute('''INSERT INTO dtf_local.order_reviews(order_id,seq,upload_id,kind,width,height,created_by)
VALUES(%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
(order['id'], seq, upload['id'], kind, width, height, user)).fetchone()
return {**row, 'name': name}
def by_order(c, order_ids):
"""{order_id (str): [ {id, seq, kind, name, width, height, created_by,
created_at}, ... ]} in seq order, for the board."""
if not order_ids:
return {}
rows = c.execute('''SELECT r.id,r.order_id,r.seq,r.kind,r.width,r.height,r.created_by,r.created_at,u.name
FROM dtf_local.order_reviews r JOIN dtf_local.uploads u ON u.id=r.upload_id
WHERE r.order_id=ANY(%s) ORDER BY r.order_id,r.seq''', (order_ids,)).fetchall()
out = {}
for row in rows:
out.setdefault(str(row['order_id']), []).append(
{key: row[key] for key in ('id', 'seq', 'kind', 'name', 'width', 'height', 'created_by', 'created_at')})
return out

View File

@@ -12,7 +12,9 @@ from uuid import uuid5, NAMESPACE_URL
from fastapi import HTTPException
from psycopg.types.json import Jsonb
from . import catalog
from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime
from .freight import FreightOptions
from .core.secrets import load as load_secret_files
# Secret files must resolve before any configuration below is read.
@@ -25,7 +27,16 @@ if os.environ.get('PAYMENT_ADAPTER') == 'mercadopago':
payment = MercadoPagoPayment()
else:
payment = FakePayment()
freight = FakeFreight()
# Every carrier configured; the simulated one only where there is none.
_carriers = []
if os.environ.get('FREIGHT_ADAPTER') == 'jadlog':
from .jadlog import JadlogFreight
_carriers.append(JadlogFreight())
from . import correios as _correios
from . import prumo
if _correios.configured():
_carriers.append(_correios.CorreiosFreight())
freight = FreightOptions(_carriers or [FakeFreight()])
ENVIRONMENT = os.environ.get('APP_ENV', 'local')
PUBLIC_ORIGIN = os.environ.get('PUBLIC_ORIGIN', 'http://localhost')
ALLOWED_HOSTS = [host for host in os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',') if host]
@@ -42,29 +53,114 @@ BOARD_QUOTE_LIMIT = int(os.environ.get('BOARD_QUOTE_LIMIT', '100'))
PART_BYTES = int(os.environ.get('UPLOAD_PART_BYTES', '8388608'))
if not 5242880 <= PART_BYTES <= 67108864:
raise RuntimeError('UPLOAD_PART_BYTES must be between 5 and 64 MiB')
STATES = {'rec': 'Arte recebida', 'tra': 'Arte tratada', 'fil': 'Fila de impressão',
'imp': 'Imprimindo', 'cor': 'Correção', 'fin': 'Finalizado'}
TRANSITIONS = {'rec': ['tra','cor'], 'tra': ['fil','cor'], 'fil': ['imp','cor'],
'imp': ['fin','cor'], 'cor': ['rec','tra'], 'fin': []}
# Dropstar's flow of 2026-10-23: Arte conferida is the print queue (Fila de
# impressão, 'fil', left the board), and Revisão checks the printed sheet
# before Finalizado. After a correction the new art goes back through Arte
# recebida or Arte conferida; Gestão may also take it straight to Revisão.
# Who may make each move is app/core/auth.py's MOVES.
STATES = {'rec': 'Arte recebida', 'tra': 'Arte conferida', 'imp': 'Imprimindo',
'cor': 'Correção', 'rev': 'Revisão', 'fin': 'Finalizado'}
TRANSITIONS = {'rec': ['tra','cor'], 'tra': ['imp','cor'], 'imp': ['rev','cor'],
'rev': ['fin','cor'], 'cor': ['rec','tra','rev'], 'fin': []}
# Undoing a move made by mistake: one stage back, with an internal reason. It
# is not a correction: the customer is not told and approved finals stay.
BACK = {'tra': 'rec', 'imp': 'tra', 'rev': 'imp', 'fin': 'rev'}
def real_delivery():
"""Whether a real carrier is configured; a simulated price is local only."""
return any(carrier.name != 'fake' for carrier in freight.carriers)
def delivery_services():
"""The delivery options the cart may offer: none outside the local stack
without a real carrier, so a customer sees only pickup."""
if ENVIRONMENT != 'local' and not real_delivery():
return []
return [{'service': service, 'description': label} for service, label in freight.services.items()]
def require_delivery_available(service):
"""Outside the local stack, a simulated freight price must never reach a
customer: until a real freight provider exists, only pickup is offered."""
if service != 'pickup' and ENVIRONMENT != 'local' and not real_delivery():
raise HTTPException(503, 'A entrega ainda não está disponível. Escolha a retirada em Franca.')
def upload_row(c, upload_id, session_id, lock=False):
row = c.execute('SELECT * FROM dtf_local.uploads WHERE id=%s AND owner=%s' +
(' FOR UPDATE' if lock else ''), (upload_id, session_id)).fetchone()
if not row:
raise HTTPException(404, 'Upload not found')
raise HTTPException(404, 'Arquivo não encontrado. Escolha o arquivo de novo.')
days = 30 if row['complete'] else 1
if row['purged_at'] or row['expires_at'] <= datetime.now(timezone.utc) or row['created_at'] < datetime.now(timezone.utc) - timedelta(days=days):
raise HTTPException(410, 'Upload expired; select the file again')
raise HTTPException(410, 'Este arquivo expirou. Escolha o arquivo de novo.')
return row
def quote_view(c, row):
order = c.execute('SELECT id,number,state FROM dtf_local.orders WHERE quote_id=%s', (row['id'],)).fetchone()
expired = row['approved_at'] and row['approved_at'] < datetime.now(timezone.utc)-timedelta(hours=24)
def order_code(order_id):
"""What a customer calls an order: the first 8 characters of its id, in
capitals ("F6B9CDBC"). It is stable and says nothing about how many orders
the store has, unlike the sequential number the operators work with."""
return str(order_id).replace('-', '')[:8].upper()
def quote_views(c, rows):
"""quote_view for a list of quotes, in two queries whatever its length: the
board shows up to 240 quotes, and asking per quote made 480 queries."""
ids = [row['id'] for row in rows]
if not ids:
return []
orders = {r['quote_id']: {k: r[k] for k in ('id', 'number', 'state')} for r in c.execute(
'SELECT quote_id,id,number,state FROM dtf_local.orders WHERE quote_id=ANY(%s)', (ids,)).fetchall()}
attempts = {r['quote_id']: {k: r[k] for k in ('method', 'status', 'status_detail', 'expires_at', 'created_at')}
for r in c.execute('''SELECT DISTINCT ON (quote_id) quote_id,method,status,
response->>'status_detail' AS status_detail, response->>'expires_at' AS expires_at, created_at
FROM dtf_local.payment_intents WHERE quote_id=ANY(%s) ORDER BY quote_id, created_at DESC''', (ids,)).fetchall()}
return [quote_view(c, row, order=orders.get(row['id']), attempt=attempts.get(row['id']), known=True) for row in rows]
def quote_view(c, row, order=None, attempt=None, known=False):
from .quote_review import review_reason # it imports this module
from .payments import QUOTE_VALID_HOURS # it imports this module too
if not known:
order = c.execute('SELECT id,number,state FROM dtf_local.orders WHERE quote_id=%s', (row['id'],)).fetchone()
# The latest payment attempt, so the payment page can tell a refused card
# (the notification updates it) from one still waiting.
# Its PIX expiry and time let the Kanban tell "tried to pay" from "never tried".
attempt = c.execute('''SELECT method,status,response->>'status_detail' AS status_detail,
response->>'expires_at' AS expires_at, created_at
FROM dtf_local.payment_intents WHERE quote_id=%s ORDER BY created_at DESC LIMIT 1''', (row['id'],)).fetchone()
if attempt and attempt['status'] == 'rejected':
from .payment_messages import rejection
attempt = {**attempt, 'message': rejection(attempt['status_detail'])}
expires_at = (row['approved_at'] + timedelta(hours=QUOTE_VALID_HOURS)
if row['approved_at'] else None)
expired = (bool(row.get('expired_at')) or
bool(row['approved_at'] and row['approved_at'] <
datetime.now(timezone.utc)-timedelta(hours=QUOTE_VALID_HOURS)))
items = (row['approved'] or row['draft']).get('items') or []
treatment = (row['approved'] or {}).get('treatment')
if not treatment and (row['draft'] or {}).get('treatment'):
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'],
'status': 'paid' if order else 'expired' if expired else 'approved' if row['approved'] else 'pending_review',
'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',
'review_reason': None if row['approved'] else (row.get('review_note') or review_reason(row['draft'])),
'payment': attempt,
'order': order}
@@ -75,7 +171,7 @@ def enqueue(c, event_key, provider, payload):
def owned_order(c, oid, identity, lock=False):
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s AND owner=%s'+(' FOR UPDATE' if lock else ''), (oid,identity)).fetchone()
if not row: raise HTTPException(404, 'Order not found')
if not row: raise HTTPException(404, 'Pedido não encontrado.')
return row

View File

@@ -1,4 +1,15 @@
"""Local ClamAV boundary. Unknown/error/over-limit results NEVER release artwork."""
"""Releasing artwork: ClamAV up to its size limit, a format check above it.
Unknown or error results NEVER release artwork. ClamAV scans files up to
scan_limit_bytes() (at most 2 GB). Since 2026-10-21 a file is at most 1 GB and
the scan limit is the same, so every file is scanned. Were the upload limit
raised above it again, a larger file would be released only if its first bytes
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
import time
@@ -6,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':
@@ -30,10 +42,9 @@ class ClamAV:
return self.command(b'VERSION').decode('utf-8','replace')
def scan(self, stream, size):
if size > scan_limit_bytes():
return 'rejected', 'File exceeds the malware scan limit'
with socket.create_connection(('scanner',3310),timeout=10) as sock:
sock.settimeout(150)
# A 2 GB file takes minutes to stream and scan.
sock.settimeout(900)
sock.sendall(b'zINSTREAM\0')
sent=0
for chunk in stream.iter_chunks(chunk_size=65536):
@@ -52,6 +63,67 @@ class ClamAV:
if result.endswith(b' FOUND'):return 'rejected','Malware or unsafe scan condition detected'
return 'error','Scanner could not verify this file'
# What each accepted extension must start with. AI files are PDF or PostScript;
# CDR and WebP are RIFF containers with their own form type.
TIFF = (b'II*\x00', b'MM\x00*', b'II+\x00', b'MM\x00+')
SIGNATURES = {
'png': (b'\x89PNG\r\n\x1a\n',),
'jpg': (b'\xff\xd8\xff',), 'jpeg': (b'\xff\xd8\xff',),
'tif': TIFF, 'tiff': TIFF,
'pdf': (b'%PDF-',), 'ai': (b'%PDF-', b'%!PS'),
'psd': (b'8BPS',), 'psb': (b'8BPS',),
}
RIFF_FORMS = {'cdr': re.compile(rb'^RIFF....CDR', re.S), 'webp': re.compile(rb'^RIFF....WEBP', re.S)}
HEAD_BYTES = 64
# Dropstar's rule D-13 (2026-10-26): the content decides a file's type, never
# its extension. A third of their ".cdr" files are PDFs renamed.
def detected_format(head):
"""The format a file's first bytes show, as an extension, or None."""
for ext in ('pdf', 'png', 'jpg', 'tif', 'psd'):
if any(head.startswith(sig) for sig in SIGNATURES[ext]):
return ext
for ext, form in RIFF_FORMS.items():
if form.match(head):
return ext
return None
def real_name(name, head):
"""The file's name with the extension of what it really is: a ".cdr" that
is a PDF is "x.pdf", a JPG called ".png" is "x.jpg". A name its content
agrees with stays, so an Illustrator file, which is a PDF inside, is still
".ai" and handled by hand; unknown content keeps the name too."""
found = detected_format(head)
if not found or format_matches(name, head):
return name
stem, dot, _ = name.rpartition('.')
return (stem if dot else name) + '.' + found
def head_of(storage, row):
"""A stored file's first bytes."""
return storage.client.get_object(Bucket=storage.bucket, Key=row['object_key'],
Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read()
def format_matches(name, head):
"""Whether a file's first bytes are those of the format its name claims."""
ext = name.rsplit('.', 1)[-1].lower() if '.' in name else ''
if ext in RIFF_FORMS:
return bool(RIFF_FORMS[ext].match(head))
return any(head.startswith(sig) for sig in SIGNATURES.get(ext, ()))
def check_large(head, row):
"""Release decision for a file above the antivirus limit."""
# The content decides (D-13): a ".cdr" that is a PDF is still a PDF.
if format_matches(row['name'], head) or detected_format(head):
return 'clean', 'Acima do limite do antivírus; formato do arquivo conferido'
return 'rejected', 'O conteúdo do arquivo não corresponde ao formato do nome'
def scan_one(storage, scanner=None):
scanner=scanner or ClamAV()
with connect() as c:
@@ -59,17 +131,37 @@ def scan_one(storage, scanner=None):
AND expires_at>now() AND scan_state IN ('pending','error') AND scan_after<=now()
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1''').fetchone()
if not row:return False
name=row['name']
try:
stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body']
try:state,reason=scanner.scan(stream,row['size'])
finally:stream.close()
# Every later decision reads the stored name (the manual charge,
# the JPG refusal, the grade, the print file, the folders), so the
# name is made to say what the file is (D-13).
head=head_of(storage,row)
name=real_name(name,head)
if row['size'] > scan_limit_bytes():
state,reason=check_large(head,row)
else:
stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body']
try:state,reason=scanner.scan(stream,row['size'])
finally:stream.close()
except Exception:
state,reason='error','Malware scanner unavailable; file remains blocked'
c.execute("""UPDATE dtf_local.uploads SET scan_state=%s,scan_reason=%s,scanned_at=now(),
# 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""",(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

@@ -35,6 +35,9 @@ CREATE TABLE IF NOT EXISTS dtf_local.accounts (
id uuid PRIMARY KEY, email text UNIQUE NOT NULL, password_hash text NOT NULL,
profile jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
);
-- Confirmed with an e-mailed code (at signup or on a change): only then does
-- the account bring guest orders placed with its CPF/CNPJ and e-mail.
ALTER TABLE dtf_local.accounts ADD COLUMN IF NOT EXISTS email_verified boolean NOT NULL DEFAULT false;
CREATE TABLE IF NOT EXISTS dtf_local.sessions (
id uuid PRIMARY KEY, owner uuid NOT NULL,
expires_at timestamptz NOT NULL DEFAULT now() + interval '7 days'
@@ -77,6 +80,8 @@ CREATE TABLE IF NOT EXISTS dtf_local.security_events (
);
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS expires_at timestamptz;
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS purged_at timestamptz;
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS original_name text;
UPDATE dtf_local.uploads SET original_name=name WHERE original_name IS NULL;
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_state text NOT NULL DEFAULT 'pending';
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_reason text;
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scanned_at timestamptz;
@@ -107,6 +112,13 @@ CREATE TABLE IF NOT EXISTS dtf_local.provider_tokens (
connected_by text NOT NULL, connected_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Renewal health, cleared by the next successful renewal or connection.
-- refused_at: the provider rejected the refresh token, so only a new
-- connection helps. offline: the grant is not bound to a login session.
ALTER TABLE dtf_local.provider_tokens ADD COLUMN IF NOT EXISTS refresh_failed_at timestamptz;
ALTER TABLE dtf_local.provider_tokens ADD COLUMN IF NOT EXISTS refresh_error text;
ALTER TABLE dtf_local.provider_tokens ADD COLUMN IF NOT EXISTS refused_at timestamptz;
ALTER TABLE dtf_local.provider_tokens ADD COLUMN IF NOT EXISTS offline boolean NOT NULL DEFAULT false;
-- Single-use states for an operator-started OAuth connection. They protect the
-- callback, which arrives cross-site without the operator's cookie.
CREATE TABLE IF NOT EXISTS dtf_local.oauth_states (
@@ -126,6 +138,24 @@ CREATE TABLE IF NOT EXISTS dtf_local.print_files (
created_at timestamptz NOT NULL DEFAULT now(), finished_at timestamptz,
UNIQUE(order_id,item_index)
);
ALTER TABLE dtf_local.print_files ADD COLUMN IF NOT EXISTS claim_token uuid;
-- Each run of the off-server database backup (ops/db_backup.py), which the
-- Kanban shows so a backup that stopped working does not go unnoticed.
CREATE TABLE IF NOT EXISTS dtf_local.backups (
id uuid PRIMARY KEY, started_at timestamptz NOT NULL, finished_at timestamptz NOT NULL,
status text NOT NULL CHECK(status IN ('ok','failed')), object_key text, bytes bigint, detail text
);
CREATE INDEX IF NOT EXISTS backups_finished ON dtf_local.backups(finished_at DESC);
-- "Fazer backup agora" in the Kanban; the backup service looks every minute.
CREATE TABLE IF NOT EXISTS dtf_local.backup_requests (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, requested_at timestamptz NOT NULL DEFAULT now(),
requested_by text NOT NULL
);
-- Why a quote waits for review, when the reason came from its files (the grade
-- the server recomputed) and cannot be worked out again from the draft alone.
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS review_note text;
CREATE INDEX IF NOT EXISTS uploads_owner ON dtf_local.uploads(owner);
@@ -146,6 +176,9 @@ CREATE INDEX IF NOT EXISTS order_files_upload ON dtf_local.order_files(upload_id
-- index stays the size of the backlog rather than of all history.
CREATE INDEX IF NOT EXISTS outbox_pending ON dtf_local.outbox(available_at, id)
WHERE delivered_at IS NULL;
-- The system sends no WhatsApp messages (the client's own n8n does, from Tiny):
-- its old log rows would wait for an adapter that no longer exists.
DELETE FROM dtf_local.outbox WHERE provider='whatsapp';
-- The scanner and the retention sweep both walk live uploads in arrival order.
-- now() cannot appear in a partial index predicate, so the time comparisons stay
@@ -173,6 +206,41 @@ CREATE INDEX IF NOT EXISTS payment_events_unprocessed ON dtf_local.payment_event
CREATE INDEX IF NOT EXISTS print_files_open ON dtf_local.print_files(created_at)
WHERE status IN ('pending','rendering');
-- The generated files of each item (item 13, 2026-10-29): one PNG, or the parts
-- of a film over 15 m, in order. print_files.upload_id stays the first.
CREATE TABLE IF NOT EXISTS dtf_local.print_parts (
order_id uuid NOT NULL, item_index integer NOT NULL, part integer NOT NULL CHECK(part >= 1),
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id) ON DELETE CASCADE,
PRIMARY KEY(order_id,item_index,part),
FOREIGN KEY(order_id,item_index) REFERENCES dtf_local.print_files(order_id,item_index) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS print_parts_upload ON dtf_local.print_parts(upload_id);
-- What each machine's hot folder gets (item 10, app/hotfolder.py): one row per
-- file or part, per entry into Imprimindo (round), written by one computer.
CREATE TABLE IF NOT EXISTS dtf_local.hot_parts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
round integer NOT NULL, seq integer NOT NULL, item_index integer NOT NULL,
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id) ON DELETE CASCADE,
name text NOT NULL, folder text,
state text NOT NULL DEFAULT 'queued'
CHECK(state IN ('queued','claimed','written','consumed','withdraw','gone')),
claimed_at timestamptz, claimed_by text, written_at timestamptz, done_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE(order_id, round, seq)
);
CREATE INDEX IF NOT EXISTS hot_parts_open ON dtf_local.hot_parts(order_id)
WHERE state IN ('queued','claimed','written','withdraw');
INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id)
SELECT order_id,item_index,1,upload_id FROM dtf_local.print_files WHERE upload_id IS NOT NULL
ON CONFLICT DO NOTHING;
-- A movement that undid an earlier one (a mistaken move), shown as such.
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS back boolean NOT NULL DEFAULT false;
CREATE INDEX IF NOT EXISTS movements_finished_latest ON dtf_local.movements(order_id, created_at DESC)
WHERE to_state='fin' AND NOT back;
-- The Kanban lists payment events a person must act on (money without an
-- order, or a reversed payment on an existing order) until resolved.
ALTER TABLE dtf_local.payment_events ADD COLUMN IF NOT EXISTS resolved_at timestamptz;
@@ -183,3 +251,422 @@ CREATE INDEX IF NOT EXISTS payment_events_open_issues ON dtf_local.payment_event
-- Payment intents look up by quote (customer retry) and by provider id (webhook).
CREATE INDEX IF NOT EXISTS payment_intents_quote ON dtf_local.payment_intents(quote_id, created_at DESC);
-- A small picture of each artwork (about 480 px), made by the customer's
-- browser from the file it already read, so the Kanban shows what an order is
-- without opening the original. It goes when the file's bytes go.
CREATE TABLE IF NOT EXISTS dtf_local.upload_thumbnails (
upload_id uuid PRIMARY KEY REFERENCES dtf_local.uploads(id),
mime text NOT NULL, data bytea NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
);
-- An operator may discard an unpaid quote (it leaves the Kanban and can no
-- longer be paid) and cancel a paid order (it leaves the board but keeps its
-- payment and history; a refund is made at the provider).
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS discarded_at timestamptz;
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS discarded_by text;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancelled_at timestamptz;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancelled_by text;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancel_reason text;
-- An order's place in its column's queue, when an operator dragged it up or
-- down. Empty means "by payment time"; it is cleared when the order moves on.
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS queue_key double precision;
-- The company name behind each customer's CNPJ, from the public registry
-- (app/cnpj.py). failed_at alone: the lookup failed and is retried later.
CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names (
cnpj text PRIMARY KEY, legal_name text, trade_name text,
fetched_at timestamptz, failed_at timestamptz
);
-- Who may do what on the Kanban. superadmin is the system's own account (set
-- 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; 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';
-- 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.
CREATE TABLE IF NOT EXISTS dtf_local.machines (
id uuid PRIMARY KEY, name text UNIQUE NOT NULL, products text[] NOT NULL DEFAULT '{}',
active boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS limit_metres numeric(8,1) CHECK (limit_metres > 0);
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS machine_id uuid REFERENCES dtf_local.machines(id) ON DELETE SET NULL;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS machine_chosen boolean NOT NULL DEFAULT false;
-- Until now only a person's choice was stored.
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='machine-chosen-v1') THEN
UPDATE dtf_local.orders SET machine_chosen=true WHERE machine_id IS NOT NULL;
INSERT INTO dtf_local.migrations VALUES('machine-chosen-v1');
END IF;
END $$;
-- Remove the old automatic suggestions before printing. Keep real choices
-- and machines already printing, whose hot-folder files may be in flight.
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='machine-pull-only-v1') THEN
UPDATE dtf_local.orders SET machine_id=NULL, machine_chosen=false
WHERE NOT machine_chosen AND state IN ('rec','tra','cor');
INSERT INTO dtf_local.migrations VALUES('machine-pull-only-v1');
END IF;
END $$;
-- Acceptable time per stage (front 11): Gestão edits these; a card past the
-- limit turns yellow, at twice the limit red. `responsible` is who the board
-- names for that column. The final stage counts days without pickup.
CREATE TABLE IF NOT EXISTS dtf_local.stage_limits (
state text PRIMARY KEY CHECK (state IN ('rec','tra','imp','rev','fin')),
hours numeric NOT NULL CHECK (hours > 0),
responsible text NOT NULL DEFAULT '',
updated_by text NOT NULL DEFAULT 'sistema',
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Videos are uploaded by Gestão; the Site reads only enabled, scanned files.
CREATE TABLE IF NOT EXISTS dtf_local.site_videos (
id text PRIMARY KEY CHECK (id IN ('subindo','nota','png','avulsas','retirada','sala')),
upload_id uuid REFERENCES dtf_local.uploads(id),
captions_id uuid REFERENCES dtf_local.uploads(id),
video_key text,
captions_key text,
product text CHECK (product IN ('file','avulsa','uvfile','uv')),
enabled boolean NOT NULL DEFAULT false,
updated_by text NOT NULL DEFAULT 'sistema',
updated_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE dtf_local.site_videos ADD COLUMN IF NOT EXISTS video_key text;
ALTER TABLE dtf_local.site_videos ADD COLUMN IF NOT EXISTS captions_key text;
INSERT INTO dtf_local.stage_limits(state,hours,responsible) VALUES
('rec',2,'Designer'), ('tra',6,'Operador'), ('imp',4,'Operador'),
('rev',2,'Revisor'), ('fin',72,'Atendimento')
ON CONFLICT (state) DO NOTHING;
-- The machines an operator works on; none means every machine.
CREATE TABLE IF NOT EXISTS dtf_local.operator_machines (
operator_id uuid NOT NULL REFERENCES dtf_local.operators(id) ON DELETE CASCADE,
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
PRIMARY KEY (operator_id, machine_id)
);
-- E-mail (app/mail.py): queued in the transaction that caused it, sent by the
-- worker. A recovery message's text is erased once sent; the subject stays.
CREATE TABLE IF NOT EXISTS dtf_local.mail_queue (
id bigserial PRIMARY KEY, kind text NOT NULL,
to_addr text NOT NULL, subject text NOT NULL, body text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(), available_at timestamptz NOT NULL DEFAULT now(),
attempts int NOT NULL DEFAULT 0, last_error text, sent_at timestamptz, failed_at timestamptz
);
-- The HTML version of a customer message (app/mail_html.py); erased with the
-- text for a code or a recovery link.
ALTER TABLE dtf_local.mail_queue ADD COLUMN IF NOT EXISTS html text;
CREATE INDEX IF NOT EXISTS mail_queue_pending ON dtf_local.mail_queue(available_at, id)
WHERE sent_at IS NULL AND failed_at IS NULL;
-- A customer's password recovery: only the token's hash is kept, for an hour,
-- and it works once.
CREATE TABLE IF NOT EXISTS dtf_local.password_resets (
token_hash text PRIMARY KEY, account_id uuid NOT NULL REFERENCES dtf_local.accounts(id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(), expires_at timestamptz NOT NULL, used_at timestamptz
);
CREATE INDEX IF NOT EXISTS password_resets_account ON dtf_local.password_resets(account_id);
-- Kanban users who get the team's alerts by e-mail.
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS alerts boolean NOT NULL DEFAULT false;
-- "Aguardando contato": an order whose file needs a word with the customer
-- before printing. A mark on the card, not a stage: the order stays where it is.
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_since timestamptz;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_by text;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_note text;
-- A signup waiting for its e-mail code. The account is created only when the
-- code is entered; the password is already hashed and the code only hashed.
CREATE TABLE IF NOT EXISTS dtf_local.account_signups (
id uuid PRIMARY KEY, email text NOT NULL, profile jsonb NOT NULL, password_hash text NOT NULL,
code_hash text, created_at timestamptz NOT NULL DEFAULT now(), sent_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL, sends int NOT NULL DEFAULT 1, attempts int NOT NULL DEFAULT 0,
done_at timestamptz
);
CREATE INDEX IF NOT EXISTS account_signups_created ON dtf_local.account_signups(created_at);
-- A customer changing the account's e-mail: the change waits for the code sent
-- to the new address, as a signup does, and the old address is told.
CREATE TABLE IF NOT EXISTS dtf_local.email_changes (
id uuid PRIMARY KEY, account_id uuid NOT NULL REFERENCES dtf_local.accounts(id) ON DELETE CASCADE,
new_email text NOT NULL, code_hash text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
sent_at timestamptz NOT NULL DEFAULT now(), expires_at timestamptz NOT NULL,
sends int NOT NULL DEFAULT 1, attempts int NOT NULL DEFAULT 0, done_at timestamptz
);
-- Accounts confirmed by a code before email_verified existed. The signups
-- are deleted after a day; the code e-mail sent before the account existed
-- stays in the queue.
UPDATE dtf_local.accounts a SET email_verified=true WHERE NOT a.email_verified AND (
EXISTS (SELECT 1 FROM dtf_local.account_signups s WHERE s.email=a.email AND s.done_at IS NOT NULL)
OR EXISTS (SELECT 1 FROM dtf_local.email_changes e WHERE e.account_id=a.id AND e.new_email=a.email AND e.done_at IS NOT NULL)
OR EXISTS (SELECT 1 FROM dtf_local.mail_queue m WHERE m.kind='code' AND lower(m.to_addr)=a.email
AND m.created_at<=a.created_at));
-- 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.
-- 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
-- "Prova OK" once it is checked, and without it the order does not reach
-- Finalizado.
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_ok_at timestamptz;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_ok_by text;
-- Fila de impressão left the board (Dropstar, 2026-10-23): Arte conferida is
-- the queue. An order still in it moves there once, with a line in its history.
WITH moved AS (UPDATE dtf_local.orders SET state='tra', version=version+1, updated_at=now()
WHERE state='fil' RETURNING id)
INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
SELECT id,'fil','tra','sistema','A Fila de impressão saiu do quadro: Arte conferida é a fila.' FROM moved;
-- Each time an order waited for a word with the customer ("Aguardando
-- contato"): that wait has no deadline and does not count in the time figures
-- of Números (Dropstar's rule D-38, 2026-10-26). An open wait has no end. The
-- waits already open when this table came are recorded from their start.
CREATE TABLE IF NOT EXISTS dtf_local.contact_waits (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
started_at timestamptz NOT NULL, ended_at timestamptz
);
CREATE INDEX IF NOT EXISTS contact_waits_order ON dtf_local.contact_waits(order_id);
INSERT INTO dtf_local.contact_waits(order_id, started_at)
SELECT o.id, o.contact_since FROM dtf_local.orders o
WHERE o.contact_since IS NOT NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.contact_waits w WHERE w.order_id=o.id);
-- Every card is born with its origin (Dropstar's rules D-21 and D-35,
-- 2026-10-26): site, dropflow (the montador's batches) or atendimento (an
-- order the team enters). No order without one, and no default: a default
-- would become the origin of almost everything, so each way in names its own.
-- The orders from before this column all came from the Site.
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;
-- 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
-- after (D-03); an Administrador authorizes or declines it, never one they
-- opened, and only an authorized rework counts. Bad art the customer approved
-- is recorded apart, outside the goal (D-04). printed_by is who sent the
-- sheet to Revisão, as the rework enters the printer's pay.
CREATE TABLE IF NOT EXISTS dtf_local.reworks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
cause text NOT NULL CHECK (cause IN ('impressao','perfil_cor','tratamento','pedido','arte_cliente')),
metres numeric NOT NULL CHECK (metres > 0),
note text NOT NULL DEFAULT '',
printed_by text,
opened_by text NOT NULL, opened_at timestamptz NOT NULL DEFAULT now(),
authorized boolean, decided_by text, decided_at timestamptz, decline_reason text
);
CREATE INDEX IF NOT EXISTS reworks_order ON dtf_local.reworks(order_id);
-- The pickup receipt (Dropstar's third round, item 14, 2026-10-29): due when
-- an order to be picked up reaches Finalizado; one computer's folder claims
-- it and saves the PDF in Recibos/, where the counter's print queue sends it
-- to the Bematech. Claimed once, so it is never printed twice.
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_due_at timestamptz;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_saved_at timestamptz;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_saved_by text;
-- "Retirado": when, who handed it over and, optionally, a photo of the
-- signed receipt. Finalizado means ready; this means delivered.
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_at timestamptz;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_by text;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_photo uuid REFERENCES dtf_local.uploads(id) ON DELETE SET NULL;
-- The machine a session works on (Dropstar's third round, item 12, 2026-10-30):
-- chosen after signing in, per session, so one person may be on two machines,
-- one per computer. machine_answered: the question was answered, "Não estou em
-- máquina" included. The links Usuários showed before (operator_machines)
-- are no longer read.
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_id uuid REFERENCES dtf_local.machines(id) ON DELETE SET NULL;
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_at timestamptz;
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_answered boolean NOT NULL DEFAULT false;
-- The contraction class chosen per item (item 9), keyed by item index, with
-- who chose it and when; the measured class stays in the order's snapshot.
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contraction jsonb NOT NULL DEFAULT '{}'::jsonb;
-- The proof card (Dropstar, 2026-10-30, app/proof.py): an order of its own,
-- child of the order it proves, with no quote of its own; its answer, Prova OK
-- or reprovada with its reason, by whom and when.
ALTER TABLE dtf_local.orders ALTER COLUMN quote_id DROP NOT NULL;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS parent_id uuid REFERENCES dtf_local.orders(id) ON DELETE CASCADE;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_result text CHECK (proof_result IN ('ok','rejected'));
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_decided_at timestamptz;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_decided_by text;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_reason text;
CREATE INDEX IF NOT EXISTS orders_parent ON dtf_local.orders(parent_id) WHERE parent_id IS NOT NULL;
-- An order's own rows go with it, so deleting an order takes its proof cards
-- and theirs too. Done once: a constraint already cascading is left alone.
DO $$
DECLARE r record;
BEGIN
FOR r IN SELECT c.conname, c.conrelid::regclass AS tbl FROM pg_constraint c
WHERE c.contype='f' AND c.confrelid='dtf_local.orders'::regclass AND c.confdeltype<>'c'
AND c.conrelid IN ('dtf_local.movements'::regclass, 'dtf_local.order_files'::regclass,
'dtf_local.print_files'::regclass)
LOOP
EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I', r.tbl, r.conname);
EXECUTE format('ALTER TABLE %s ADD CONSTRAINT %I FOREIGN KEY (order_id) REFERENCES dtf_local.orders(id) ON DELETE CASCADE',
r.tbl, r.conname);
END LOOP;
END $$;
-- When the session was last used (Usuários: who is on the system now).
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS seen_at timestamptz;
-- The machine of whoever moved a card, as it was named then: "Imprimindo ·
-- Thales · máquina2".
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS machine text;
-- An approved quote nobody paid in 24 h expires (Fase 2, front 9, app/unpaid.py).
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS expired_at timestamptz;
-- The Revisor's photo or short video of the printed sheet (Fase 2, front 2,
-- app/reviews.py): DTF-<n>-revisao-<seq>, the record of when and by whom it
-- was checked. A photo is required to finish an order above 1 m.
CREATE TABLE IF NOT EXISTS dtf_local.order_reviews (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
seq integer NOT NULL CHECK(seq >= 1),
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id) ON DELETE CASCADE,
kind text NOT NULL CHECK(kind IN ('photo','video')),
width integer, height integer,
created_by text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE(order_id, seq)
);
CREATE INDEX IF NOT EXISTS order_reviews_order ON dtf_local.order_reviews(order_id);
-- Each machine's sheet (Fase 2, front 1, app/machine_log.py): what it cost and
-- when it started, typed once by Gestão; what goes into it, entered by the
-- room; and the minimum of each supply that raises the alert.
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS price_cents bigint CHECK (price_cents >= 0);
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS installed_on date;
-- When the counters start: a machine with no cleaning on record counts from
-- here, not from everything it printed before the sheet existed.
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS log_since timestamptz NOT NULL DEFAULT now();
CREATE TABLE IF NOT EXISTS dtf_local.machine_entries (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
kind text NOT NULL CHECK(kind IN ('supply','part','event')),
item text NOT NULL,
quantity numeric(12,3) CHECK (quantity > 0),
cost_cents bigint CHECK (cost_cents >= 0),
serial text, note text,
stop_minutes integer CHECK (stop_minutes > 0),
from_alert boolean NOT NULL DEFAULT false,
created_by text NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS machine_entries_machine ON dtf_local.machine_entries(machine_id, created_at);
CREATE TABLE IF NOT EXISTS dtf_local.machine_minimums (
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
item text NOT NULL, minimum numeric(12,3) NOT NULL CHECK (minimum >= 0),
PRIMARY KEY(machine_id, item)
);
-- "Adiar uma vez": an alert postponed lets one more card be pulled, once per
-- cycle (the cycle starts at the event that resets its counter).
CREATE TABLE IF NOT EXISTS dtf_local.machine_snoozes (
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
alert text NOT NULL, cycle_from timestamptz NOT NULL,
snoozed_by text NOT NULL, snoozed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(machine_id, alert, cycle_from)
);
-- Orders generated before the print file was a PNG with its strips (item 13)
-- open blank in the 100% viewer. Those not approved yet are generated again,
-- once: the same layout, now as PNG with strips. An approved final, a
-- customer's correction or a cancelled order is left as it is.
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='png-regenerate-v1') THEN
UPDATE dtf_local.print_files p SET status='pending', attempts=0, claimed_at=NULL, claim_token=NULL,
finished_at=NULL, upload_id=NULL, detail='{}'
FROM dtf_local.orders o
WHERE o.id=p.order_id AND o.state='rec' AND o.cancelled_at IS NULL
AND p.status='ready' AND NOT (p.detail ? 'format')
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.active);
INSERT INTO dtf_local.migrations VALUES('png-regenerate-v1');
END IF;
END $$;
-- Front 8: what the Site sells and at what price, edited in the Kanban's Site tab.
CREATE TABLE IF NOT EXISTS dtf_local.products (
id text PRIMARY KEY CHECK (id IN ('file','avulsa','uvfile','uv','tratamento')),
enabled boolean NOT NULL DEFAULT true,
updated_by text NOT NULL DEFAULT 'sistema',
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO dtf_local.products(id) VALUES ('file'),('avulsa'),('uvfile'),('uv'),('tratamento')
ON CONFLICT (id) DO NOTHING;
CREATE TABLE IF NOT EXISTS dtf_local.product_prices (
id bigserial PRIMARY KEY,
product text NOT NULL REFERENCES dtf_local.products(id),
unit_cents integer NOT NULL CHECK (unit_cents >= 0 AND unit_cents <= 10000000),
starts_at timestamptz NOT NULL,
created_by text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
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).
ALTER TABLE dtf_local.product_prices ADD COLUMN IF NOT EXISTS bands jsonb NOT NULL DEFAULT '[]';
-- Front 8.3: discount coupons, created in the Kanban's Site tab. The id is
-- generated in Python (schema.sql does not use gen_random_uuid). A deleted
-- code may be created again; the orders that used it keep its id and code.
CREATE TABLE IF NOT EXISTS dtf_local.coupons (
id uuid PRIMARY KEY,
code text NOT NULL CHECK (code ~ '^[A-Z0-9-]{3,30}$'),
kind text NOT NULL CHECK (kind IN ('percent','per_metre')),
value integer NOT NULL CHECK (value > 0), -- percent: 1..90; per_metre: cents per billed metre
valid_from timestamptz NOT NULL DEFAULT now(),
valid_until timestamptz,
min_metres numeric(8,1),
max_uses integer CHECK (max_uses > 0),
max_uses_per_customer integer CHECK (max_uses_per_customer > 0),
product text CHECK (product IN ('file','avulsa','uvfile','uv')), -- NULL = every product
note text NOT NULL DEFAULT '',
paused boolean NOT NULL DEFAULT false,
deleted_at timestamptz,
created_by text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX IF NOT EXISTS coupons_live_code ON dtf_local.coupons(code) WHERE deleted_at IS NULL;

View File

@@ -13,13 +13,36 @@ workers never spend the same one.
Orders are created by contact and product id: the customer's contact is found
by CNPJ or created, and each product mode maps to a product that must already
exist in Tiny (PRODUCT_SETTINGS).
exist in Tiny (PRODUCT_SETTINGS), sold by the metre. A mode can instead be
sold as the client's own SKUs per length (SKU_SETTINGS): the order is then a
sum, 1,30 m = 1 × "1 metro" + 1 × "30 cm", at the price the customer paid.
Idempotency: the outbox may deliver the same event more than once. Every order
carries numeroOrdemCompra = "DTF-<order number>", and before creating one the
customer's recent orders are searched for that number, so a second delivery
finds the first order instead of creating another.
finds the first order instead of creating another. The same number goes in
numeroPedidoEcommerce (Dropstar, 2026-10-23), which n8n reads as
numero_ecommerce.
Customer notices: the client sends WhatsApp messages from Tiny's order
situação (Tiny webhook -> their middleware -> n8n), on Aprovado, Pronto para
envio, Enviado and Entregue. With TINY_STATUS_UPDATES on, the Kanban moves
the Tiny order along with it (Dropstar's flow, 2026-10-23: two changes of
situação, none for Imprimindo, Correção or Revisão):
paid (Arte recebida) -> Aprovada (the "approved" notice)
Arte conferida (queue) -> Preparando envio (no notice)
Finalizado -> Pronto para envio (pickup or delivery)
cancelled -> Cancelada (no notice)
After Pronto para envio the order goes on in Tiny like any other: Enviada,
Entregue.
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
@@ -34,14 +57,126 @@ 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',
'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',
'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',
'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', '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 28,5 cm · folha montada',
'uv': 'DTF UV 28,5 cm · artes avulsas'}
'uvfile': 'DTF UV 27 cm · folha montada',
'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.
READY_SEARCH_DAYS = 45
# Tiny v3 order situações (PUT /pedidos/{id}/situacao).
ABERTA, APROVADA, PRONTO_ENVIO, ENVIADA, ENTREGUE, CANCELADA, NAO_ENTREGUE = 0, 3, 7, 5, 6, 2, 9
PREPARANDO, FATURADA, INCOMPLETA = 4, 1, 8
SITUACOES = {0: 'Aberta', 3: 'Aprovada', 4: 'Preparando envio', 1: 'Faturada', 7: 'Pronto para envio',
5: 'Enviada', 6: 'Entregue', 2: 'Cancelada', 8: 'Dados incompletos', 9: 'Não entregue'}
# The client's customer notices (Tiny webhook -> middleware -> n8n -> WhatsApp)
# react to these situações. Off until go-live: while n8n still sends the
# designer message for DTFIMP products on "Aprovado", setting it would reach
# Site customers.
# Where the order came from (D-21) and, when the team registered it, how it was
# paid outside the system (D-35), for whoever reads the order in Tiny.
ORIGIN_NOTES = {'site': 'Site DTF', 'atendimento': 'Atendimento DTF', 'dropflow': 'Dropflow DTF'}
OUTSIDE_NOTES = {'pix': 'Pix', 'card': 'cartão', 'cash': 'dinheiro', 'credit': 'crédito do cliente'}
def internal_note(payload):
paid = payload.get('payment') or {}
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'
# The client's custom "retirar pessoalmente" forma de envio (v2 code X), which
# the pickup notice is keyed on. Found in Tiny by name; this setting, an id,
# only overrides that.
PICKUP_SETTING = 'TINY_FORMA_ENVIO_RETIRADA'
PICKUP_NAME = 'retir'
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 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; 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
# Dropflow's orders in their own category, "DTF DROPFLOW" (sent 2026-10-27):
# 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
# is the forma de frete with its contract code (app/correios.py).
CARRIERS = {'pac': 'correios', 'sedex': 'correios', 'jadlog': 'jadlog'}
STATE_MINUTES = 10
# Renewal runs about every four hours against a one-day refresh token, so
# less than this left means renewals have been failing for hours.
EXPIRY_WARNING = timedelta(hours=12)
# Brazil has had no daylight saving since 2019; the order date is the local day.
BRASILIA = timezone(timedelta(hours=-3))
@@ -54,6 +189,12 @@ 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 TinyNotConnected(TinyError):
"""No authorised connection yet: an operator must click "Conectar Tiny"."""
@@ -68,7 +209,100 @@ def configured():
def required_settings():
return ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'] + list(PRODUCT_SETTINGS.values())
"""The OAuth application, and a product id for each mode not sold by SKU."""
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))]
# The stack passes every setting, empty when unset, so empty means "the
# default". A setting given for a mode replaces its default, in either form.
def setting(name):
return os.environ.get(name, '').strip()
def sku_prefix(mode):
return setting(SKU_SETTINGS[mode]) or ('' if setting(STEP_SETTINGS[mode]) else SKU_DEFAULTS.get(mode, ''))
def step_sku(mode):
return setting(STEP_SETTINGS[mode]) or ('' if setting(SKU_SETTINGS[mode]) else STEP_DEFAULTS.get(mode, ''))
def metre_sku(mode):
"""The metre SKU paired with a 10 cm SKU, or '' when the 10 cm one goes alone."""
if not step_sku(mode):
return ''
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):
return [code for code in (metre_sku(mode), step_sku(mode)) if code]
return sku_codes(sku_prefix(mode)) if sku_prefix(mode) else []
def sku_codes(prefix):
"""The metre SKU and the nine of 10 to 90 cm, as the client's catalogue names them."""
return [f'{prefix}.100CM'] + [f'{prefix}.{cm:04d}CM' for cm in range(10, 100, 10)]
def tenths(item):
"""The billed length in 10 cm steps; the Site bills in them."""
billed = Decimal(item['billed_metres'])
steps = billed * 10
if steps != steps.to_integral_value():
raise TinyError(f'{billed} m is not a whole number of 10 cm steps')
return int(steps), int(billed * int(item['unit_cents']))
def step_lines(item, code, metre=''):
"""(code, quantity, cents each) for a 10 cm SKU, after whole metres of the
metre SKU when there is one, adding up to the item's total; a rest that
does not divide goes on one line of its own."""
steps, total = tenths(item)
lines = []
if metre and steps >= 10:
metres, steps = divmod(steps, 10)
unit = int(item['unit_cents'])
lines.append((metre, metres, unit))
total -= metres * unit
if not steps:
return lines
return lines + split_steps(code, steps, total)
def split_steps(code, steps, total):
each, rest = divmod(total, steps)
if not rest:
return [(code, steps, each)]
return [(code, steps - 1, each), (code, 1, each + rest)] if steps > 1 else [(code, 1, total)]
def sku_lines(item, prefix):
"""(code, quantity, cents each) adding up to the item: whole metres as the
metre SKU, the rest as one 10 cm SKU. The Site bills in 10 cm steps, so
the rest always has a SKU; the lines carry the price the customer paid."""
billed = Decimal(item['billed_metres'])
centimetres = billed * 100
if centimetres != centimetres.to_integral_value() or int(centimetres) % 10:
raise TinyError(f'{billed} m is not a whole number of 10 cm steps')
metres, rest = divmod(int(centimetres), 100)
unit = int(item['unit_cents'])
lines = [(f'{prefix}.100CM', metres, unit)] if metres else []
if rest:
# What is left of the item's total, so the order adds up to the cent.
lines.append((f'{prefix}.{rest:04d}CM', 1, int(billed * unit) - metres * unit))
return lines
def status_updates():
return os.environ.get(STATUS_UPDATES_SETTING, '').lower() == 'true'
# OAuth -------------------------------------------------------------------
@@ -86,44 +320,80 @@ class TinyAuth:
self.http = httpx.Client(timeout=20, transport=transport)
self.clock = clock
def authorize_url(self, operator):
def authorize_url(self, operator, offline=True):
"""Start a connection. The state is single-use, short-lived, and only an
authenticated operator can create one, which is what protects the
callback: Tiny's redirect back is cross-site, so the operator's
SameSite=Strict cookie does not travel with it."""
SameSite=Strict cookie does not travel with it.
offline_access asks for a grant that is not bound to a login session,
so the connection lasts as long as it keeps being renewed. Tiny's
documented refresh token otherwise lasts one day."""
state = secrets.token_urlsafe(32)
with self.connect() as c:
c.execute("DELETE FROM dtf_local.oauth_states WHERE expires_at<now()")
c.execute('''INSERT INTO dtf_local.oauth_states(state,provider,operator,expires_at)
VALUES(%s,'tiny',%s,now()+%s)''', (state, operator, timedelta(minutes=STATE_MINUTES)))
return f'{AUTH}/auth?' + urlencode({'response_type': 'code', 'client_id': self.client_id,
'redirect_uri': self.redirect_uri, 'scope': 'openid',
'redirect_uri': self.redirect_uri,
'scope': 'openid offline_access' if offline else 'openid',
'state': state})
def _claim(self, c, state):
row = c.execute('''DELETE FROM dtf_local.oauth_states WHERE state=%s AND provider='tiny'
AND expires_at>now() RETURNING operator''', (state,)).fetchone()
if not row:
raise TinyError('Unknown or expired authorisation state')
return row['operator']
def complete(self, code, state):
"""Exchange the authorisation code; returns the operator who started it."""
with self.connect() as c:
row = c.execute('''DELETE FROM dtf_local.oauth_states WHERE state=%s AND provider='tiny'
AND expires_at>now() RETURNING operator''', (state,)).fetchone()
if not row:
raise TinyError('Unknown or expired authorisation state')
operator = self._claim(c, state)
tokens = self._token({'grant_type': 'authorization_code', 'code': code,
'redirect_uri': self.redirect_uri})
self._store(c, tokens, row['operator'])
return row['operator']
self._store(c, tokens, operator)
return operator
def status(self):
def without_offline(self, state):
"""Tiny refused the offline_access scope for this application: spend the
operator's state and start again with a session-bound grant."""
with self.connect() as c:
row = c.execute('''SELECT connected_by,connected_at,refresh_expires_at
FROM dtf_local.provider_tokens WHERE provider='tiny' ''').fetchone()
operator = self._claim(c, state)
return self.authorize_url(operator, offline=False)
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}
expired = row['refresh_expires_at'] and row['refresh_expires_at'] <= datetime.now(timezone.utc)
return {'connected': not expired, 'connected_by': row['connected_by'],
'connected_at': row['connected_at'], 'expires_at': row['refresh_expires_at']}
now = datetime.now(timezone.utc)
expires = row['refresh_expires_at']
expired = bool(expires and expires <= now)
if row['refused_at']:
problem = 'refused'
elif expired:
problem = 'expired'
elif row['refresh_failed_at']:
problem = 'renewal-failing'
elif expires and expires - now < EXPIRY_WARNING:
problem = 'expiring'
else:
problem = None
return {'connected': not expired and not row['refused_at'], 'problem': problem,
'connected_by': row['connected_by'], 'connected_at': row['connected_at'],
'renewed_at': row['updated_at'], 'expires_at': expires, 'offline': row['offline'],
'failed_at': row['refresh_failed_at']}
def access_token(self):
"""A valid access token, refreshing (and rotating) under a row lock."""
"""A valid access token, refreshing (and rotating) under a row lock.
A failed renewal is recorded after the lock is released, so the Kanban
can show it. A refused refresh token is never tried again: only a new
connection helps, and retrying it would only repeat the refusal."""
with self.connect() as c:
row = c.execute('''SELECT * FROM dtf_local.provider_tokens WHERE provider='tiny'
FOR UPDATE''').fetchone()
@@ -132,11 +402,25 @@ class TinyAuth:
now = datetime.now(timezone.utc)
if row['access_expires_at'] > now + timedelta(seconds=60):
return row['access_token']
if row['refused_at']:
raise TinyNotConnected('Tiny refused the stored refresh token; connect again on the Kanban')
if row['refresh_expires_at'] and row['refresh_expires_at'] <= now:
raise TinyNotConnected('The Tiny connection expired; connect again on the Kanban')
tokens = self._token({'grant_type': 'refresh_token', 'refresh_token': row['refresh_token']})
self._store(c, tokens, row['connected_by'], refreshed=True)
return tokens['access_token']
try:
tokens = self._token({'grant_type': 'refresh_token', 'refresh_token': row['refresh_token']})
except (TinyError, httpx.HTTPError, ValueError) as exc:
failure = exc
else:
self._store(c, tokens, row['connected_by'], refreshed=True)
return tokens['access_token']
# Only against the token that failed: another worker may have renewed since.
with self.connect() as c:
c.execute('''UPDATE dtf_local.provider_tokens SET refresh_failed_at=now(), refresh_error=%s,
refused_at=CASE WHEN %s THEN now() ELSE refused_at END
WHERE provider='tiny' AND refresh_token=%s''',
(str(failure)[:300] or type(failure).__name__, isinstance(failure, TinyNotConnected),
row['refresh_token']))
raise failure
def _token(self, form):
response = self.http.post(f'{AUTH}/token', data={**form, 'client_id': self.client_id,
@@ -152,18 +436,21 @@ class TinyAuth:
def _store(self, c, tokens, operator, refreshed=False):
now = datetime.now(timezone.utc)
access_expires = now + timedelta(seconds=int(tokens.get('expires_in', 300)))
# An offline grant reports refresh_expires_in 0: no fixed end.
refresh_in = tokens.get('refresh_expires_in')
refresh_expires = now + timedelta(seconds=int(refresh_in)) if refresh_in else None
offline = 'offline_access' in str(tokens.get('scope') or '').split()
c.execute('''INSERT INTO dtf_local.provider_tokens(provider,access_token,refresh_token,
access_expires_at,refresh_expires_at,connected_by,connected_at,updated_at)
VALUES('tiny',%s,%s,%s,%s,%s,now(),now())
access_expires_at,refresh_expires_at,connected_by,connected_at,updated_at,offline)
VALUES('tiny',%s,%s,%s,%s,%s,now(),now(),%s)
ON CONFLICT(provider) DO UPDATE SET access_token=EXCLUDED.access_token,
refresh_token=EXCLUDED.refresh_token, access_expires_at=EXCLUDED.access_expires_at,
refresh_expires_at=EXCLUDED.refresh_expires_at, updated_at=now(),
refresh_expires_at=EXCLUDED.refresh_expires_at, updated_at=now(), offline=EXCLUDED.offline,
refresh_failed_at=NULL, refresh_error=NULL, refused_at=NULL,
connected_by=CASE WHEN %s THEN dtf_local.provider_tokens.connected_by ELSE EXCLUDED.connected_by END,
connected_at=CASE WHEN %s THEN dtf_local.provider_tokens.connected_at ELSE now() END''',
(tokens['access_token'], tokens['refresh_token'], access_expires, refresh_expires,
operator, refreshed, refreshed))
operator, offline, refreshed, refreshed))
# Orders ------------------------------------------------------------------
@@ -172,12 +459,80 @@ def money(cents):
return float(Decimal(cents) / 100)
def contact_payload(order):
def punctuated(document):
"""A CPF or CNPJ as Tiny keeps it, 130.323.978-71 or 11.222.333/0001-81:
its searches match that exact text, so the bare digits find nothing."""
d = ''.join(ch for ch in str(document) if ch.isdigit())
if len(d) == 11:
return f'{d[:3]}.{d[3:6]}.{d[6:9]}-{d[9:]}'
if len(d) == 14:
return f'{d[:2]}.{d[2:5]}.{d[5:8]}/{d[8:12]}-{d[12:]}'
return d
def search_forms(document):
"""Punctuated first, as Tiny keeps it; then the bare digits, for a contact
someone typed in without punctuation."""
d = ''.join(ch for ch in str(document) if ch.isdigit())
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
recipient or the e-mail. A CPF (11 digits) is a person (F), a CNPJ a
company (J)."""
customer = order['customer']
destination = order.get('destination')
contact = {'nome': (destination or {}).get('recipient') or customer['mail'],
'tipoPessoa': 'J', 'cpfCnpj': customer['cnpj'], 'email': customer['mail'],
company = company or {}
contact = {'nome': (company.get('legal') or customer.get('name') or (destination or {}).get('recipient')
or customer['mail']),
'tipoPessoa': 'F' if len(customer['cnpj']) == 11 else 'J', 'cpfCnpj': punctuated(customer['cnpj']), 'email': customer['mail'],
'celular': customer['zap'], 'situacao': 'A'}
if company.get('trade'):
contact['fantasia'] = company['trade']
if destination:
contact['endereco'] = address(destination)
return contact
@@ -190,87 +545,433 @@ def address(destination):
'uf': destination['state'], 'pais': 'Brasil'}
def order_payload(payload, contact_id, today=None):
"""The v3 'pedido' for a paid order's approved snapshot."""
def business_days_after(day, days):
"""The day `days` working days (Monday to Friday) after `day`."""
while days > 0:
day += timedelta(days=1)
if day.weekday() < 5:
days -= 1
return day
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
frete of a delivery service or pickup."""
order = payload['order']
items = []
for item in order['items']:
setting = PRODUCT_SETTINGS[item['mode']]
product = os.environ.get(setting, '')
note = PRODUCTS[item['mode']] + f" · nota {item['grade']}"
prefix, step = sku_prefix(item['mode']), step_sku(item['mode'])
if step or prefix:
if product_id is None:
raise TinyError(f"{SKU_SETTINGS[item['mode']]} needs the SKUs looked up in Tiny")
lines = step_lines(item, step, metre_sku(item['mode'])) if step else sku_lines(item, prefix)
for index, (code, quantity, cents) in enumerate(lines):
line = {'produto': {'id': product_id(code)}, 'quantidade': quantity, 'valorUnitario': money(cents)}
if index == 0:
line['infoAdicional'] = note + f" · {item['billed_metres']} m"
items.append(line)
continue
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': PRODUCTS[item['mode']] + f" · nota {item['grade']}"})
'infoAdicional': note})
treatment = order.get('treatment') or {}
if treatment.get('cents'):
# 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']
pickup = freight.get('service') == 'pickup'
pedido = {'data': (today or local_today()).isoformat(),
service = freight.get('service')
pickup = service == 'pickup'
day = today or local_today()
pedido = {'data': day.isoformat(),
'idContato': contact_id,
'numeroOrdemCompra': purchase_order(payload['number']),
'itens': items,
'valorFrete': money(freight['total_cents']),
'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''),
'observacoesInternas': f"Site DTF · pago · {payload['order_id']}"}
'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.
pedido['valorDesconto'] = money(coupon.get('discount_cents') or 0)
carrier = shipping(service) if shipping else None
if carrier:
pedido['transportador'] = {'fretePorConta': FREIGHT_PAID_BY, **carrier}
# 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:
# 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)}}
method = (payload.get('payment') or {}).get('method')
received = RECEIPT_METHODS.get(method)
if received:
total = money(order['total_cents'])
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'],
'nomeDestinatario': destination['recipient']}
del pedido['enderecoEntrega']['numero']
# The channel id is optional in Tiny's v3 model; TINY_ECOMMERCE_ID adds it.
pedido['ecommerce'] = {'numeroPedidoEcommerce': purchase_order(payload['number'])}
ecommerce = os.environ.get('TINY_ECOMMERCE_ID', '')
if ecommerce.isdigit():
pedido['ecommerce'] = {'id': int(ecommerce), 'numeroPedidoEcommerce': purchase_order(payload['number'])}
pedido['ecommerce']['id'] = int(ecommerce)
return pedido
def configured_product(orders, mode):
"""The Tiny product a mode's setting points at, or a reason it cannot be used."""
setting = PRODUCT_SETTINGS[mode]
value = os.environ.get(setting, '')
if not value.isdigit():
return None, f'{setting} sem id'
found = orders.request('GET', f'/produtos/{value}')
if found.get('situacao') != 'A':
return found, f"produto {value} não está ativo no Tiny ({found.get('situacao')})"
return found, 'ok'
def configured_skus(orders, mode):
"""Whether every SKU of a mode sold by SKU is an active product in Tiny."""
missing = []
for code in mode_codes(mode):
try:
orders.product_id(code)
except TinyError:
missing.append(code)
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."""
found = orders.request('GET', '/formas-envio', params={'nome': PICKUP_NAME, 'limit': 100}).get('itens') or []
named = [f for f in found if PICKUP_NAME in str(f.get('nome', '')).lower()]
# The account also has "Retirar na loja", unused: the exact name decides.
exact = [f for f in named if ' '.join(str(f.get('nome', '')).lower().split()) == PICKUP_EXACT]
if len(exact) == 1:
return exact[0], 'ok'
if len(named) == 1:
return named[0], 'ok'
if not named:
return None, 'nenhuma forma de envio com "retir" no nome no Tiny'
return None, 'mais de uma forma de envio com "retir" no nome: ' + ', '.join(
f"{f.get('nome')} ({f.get('id')})" for f in named) + f'; escolha uma em {PICKUP_SETTING}'
def find_shipping(orders, service):
"""The forma de envio and de frete for a service, as {'formaEnvio': ...,
'formaFrete': ...} (and the DropStar carrier for pickup), or None when Tiny
has no such forma de envio: the order then goes without it."""
if service == 'pickup':
method, _ = configured_pickup(orders)
if not method:
return None
detail = orders.request('GET', f"/formas-envio/{method['id']}")
options = detail.get('formasFrete') or []
# "Retirar em loja", as the store's pickup orders.
frete = next((f for f in options if PICKUP_NAME in str(f.get('nome', '')).lower()), options[0] if options else None)
found = {'id': PICKUP_CARRIER, 'formaEnvio': {'id': int(method['id'])}}
if frete:
found['formaFrete'] = {'id': int(frete['id'])}
return found
name = CARRIERS.get(service)
if not name:
return None
listed = orders.request('GET', '/formas-envio', params={'nome': name, 'limit': 100}).get('itens') or []
method = next((f for f in listed if str(f.get('nome', '')).strip().lower() == name), None)
if not method:
return None
options = orders.request('GET', f"/formas-envio/{method['id']}").get('formasFrete') or []
if name == 'correios':
from .correios import SERVICES
setting, default, _ = SERVICES[service]
code = (os.environ.get(setting) or default).strip()
frete = next((f for f in options if str(f.get('codigo', '')).strip() == code), None)
else:
frete = options[0] if options else None
found = {'formaEnvio': {'id': int(method['id'])}}
if frete:
found['formaFrete'] = {'id': int(frete['id'])}
return found
def configured_pickup(orders):
"""The forma de envio used for pickup orders, or why there is none."""
value = os.environ.get(PICKUP_SETTING, '')
if value.isdigit():
return orders.request('GET', f'/formas-envio/{value}'), 'ok'
return find_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 (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):
orders.request('GET', path, params={'limit': 1, **filters})
return 'ok'
# Unfiltered, a large account's order list times out ("Sua consulta levou
# muito tempo"): yesterday's orders prove the same permission.
since = (local_today() - timedelta(days=1)).isoformat()
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:
try:
results[name] = read()
except TinyNotConnected:
raise
except TinyError as exc:
results[name] = str(exc)[:200]
except httpx.HTTPError:
results[name] = 'sem resposta do Tiny'
return results
class TinyOrders:
def __init__(self, auth=None, transport=None, today=None):
def __init__(self, auth=None, transport=None, today=None, names=None):
missing = [name for name in required_settings() if not os.environ.get(name)]
if auth is None and missing:
raise RuntimeError('Tiny needs ' + ', '.join(missing))
self.auth = auth or TinyAuth()
self.http = httpx.Client(base_url=API, transport=transport, timeout=30)
self.today = today
self.skus = {}
self.carriers = {}
# The company's names by CNPJ, for new contacts (app.cnpj.company).
self.names = names
def request(self, method, path, **kwargs):
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 >= 400:
raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}')
return response.json() if response.content else {}
def contact(self, order):
cnpj = order['customer']['cnpj']
found = self.request('GET', '/contatos', params={'cpfCnpj': cnpj, 'limit': 5})
for entry in found.get('itens') or []:
if ''.join(ch for ch in str(entry.get('cpfCnpj') or '') if ch.isdigit()) == cnpj:
return entry['id']
return self.request('POST', '/contatos', json=contact_payload(order))['id']
def shipping(self, service):
"""The forma de envio and de frete of a service, looked up once."""
if service not in self.carriers:
self.carriers[service] = find_shipping(self, service)
return self.carriers[service]
def find(self, payload):
"""An order a previous delivery already created, or None."""
wanted = purchase_order(payload['number'])
since = ((self.today or local_today()) - timedelta(days=SEARCH_DAYS)).isoformat()
found = self.request('GET', '/pedidos', params={'cpfCnpj': payload['order']['customer']['cnpj'],
'dataInicial': since, 'limit': 100})
for entry in found.get('itens') or []:
detail = self.request('GET', f"/pedidos/{entry['id']}")
if detail.get('numeroOrdemCompra') == wanted:
return detail
def product_id(self, code):
"""The id of the active product with this SKU code, remembered once found."""
if code not in self.skus:
found = self.request('GET', '/produtos', params={'codigo': code, 'situacao': 'A', 'limit': 10})
# The filter may match more than the exact code: DTFIMP.TX.010CM is
# a different product from DTFIMP.TX.0010CM.
match = [p for p in found.get('itens') or []
if str(p.get('sku') or p.get('codigo') or '') == code and p.get('situacao', 'A') == 'A']
if not match:
raise TinyError(f'SKU {code} não encontrado entre os produtos ativos do Tiny')
self.skus[code] = int(match[0]['id'])
return self.skus[code]
def find_contact(self, cnpj):
"""The id of the customer's existing contact, or None."""
for form in search_forms(cnpj):
found = self.request('GET', '/contatos', params={'cpfCnpj': form, 'limit': 5})
for entry in found.get('itens') or []:
if ''.join(ch for ch in str(entry.get('cpfCnpj') or '') if ch.isdigit()) == cnpj:
return entry['id']
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, 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'], None
def contact_seller(self, contact_id):
"""The seller (vendedor) in a contact's registration, or None. A
failed reading leaves the order without one: it must still go."""
try:
seller = (self.request('GET', f'/contatos/{contact_id}').get('vendedor') or {}).get('id')
except TinyRateLimit:
# Busy for a moment: the whole delivery is tried again, the seller with it.
raise
except TinyError as exc:
logging.warning('Tiny: could not read the seller of contact %s: %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."""
wanted = purchase_order(payload['number'])
since = ((self.today or local_today()) - timedelta(days=days)).isoformat()
seen = set()
for form in search_forms(payload['order']['customer']['cnpj']):
found = self.request('GET', '/pedidos', params={'cpfCnpj': form, 'dataInicial': since, 'limit': 100})
for entry in found.get('itens') or []:
if entry['id'] in seen:
continue
seen.add(entry['id'])
detail = self.request('GET', f"/pedidos/{entry['id']}")
if detail.get('numeroOrdemCompra') == wanted:
return detail
return None
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 []
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})
def deliver(self, event_key, payload):
if payload.get('event') != 'payment_approved':
# Production progress is not written to Tiny; only the sale is.
return {'provider': 'tiny', 'event_key': event_key, 'status': 'not-applicable',
'event': payload.get('event')}
event = payload.get('event')
if event == 'payment_approved':
return self.sale(event_key, payload)
if event == 'ready' and status_updates():
return self.ready(event_key, payload)
if event == 'production_started' and status_updates():
# Not past it: an order the team already invoiced stays where it is.
return self.move(event_key, payload, PREPARANDO, (ABERTA, APROVADA))
if event == 'cancelled' and status_updates():
return self.move(event_key, payload, CANCELADA, (ABERTA, APROVADA, PREPARANDO, INCOMPLETA))
# Other production events have no Tiny situação and are not written.
return {'provider': 'tiny', 'event_key': event_key, 'status': 'not-applicable', 'event': event}
def sale(self, event_key, payload):
"""Create the order once; with status updates on, approve it once.
An order is created "Aberta" and then set to "Aprovada", so a retry
after a failure between the two finds it still open and finishes the
job, and an order someone has already moved on is left alone."""
existing = self.find(payload)
if existing:
return {'provider': 'tiny', 'event_key': event_key, 'status': 'already-created',
'tiny_id': str(existing.get('id')), 'tiny_number': str(existing.get('numeroPedido'))}
contact_id = self.contact(payload['order'])
created = self.request('POST', '/pedidos', json=order_payload(payload, contact_id, self.today))
return {'provider': 'tiny', 'event_key': event_key, 'status': 'created',
'tiny_id': str(created.get('id')), 'tiny_number': str(created.get('numeroPedido'))}
receipt = {'provider': 'tiny', 'event_key': event_key, 'status': 'already-created',
'tiny_id': str(existing.get('id')), 'tiny_number': str(existing.get('numeroPedido'))}
tiny_id, situacao = existing.get('id'), existing.get('situacao')
else:
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,
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:
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]
return receipt
def ready(self, event_key, payload):
"""The order reached Finalizado: "Pronto para envio", for pickup and
delivery alike (Dropstar, 2026-10-23). From there the team ships it in
Tiny as any other order."""
return self.move(event_key, payload, PRONTO_ENVIO, (ABERTA, APROVADA, PREPARANDO, FATURADA, INCOMPLETA))
def move(self, event_key, payload, target, from_situacoes):
"""Set the order's situação to `target` when it is still in one of
`from_situacoes`; anywhere else it was moved on in Tiny and stays."""
base = {'provider': 'tiny', 'event_key': event_key}
tiny_id = payload.get('tiny_id')
detail = self.request('GET', f'/pedidos/{tiny_id}') if tiny_id else self.find(payload, READY_SEARCH_DAYS)
if not detail:
raise TinyError(f"{purchase_order(payload['number'])} is not in Tiny yet; the outbox will retry")
base.update(tiny_id=str(detail.get('id')), tiny_number=str(detail.get('numeroPedido')))
situacao = detail.get('situacao')
if situacao not in from_situacoes:
return {**base, 'status': 'status-unchanged', 'situacao': SITUACOES.get(situacao, str(situacao))}
self.set_situacao(detail['id'], target)
return {**base, 'status': 'status-updated', 'situacao': SITUACOES[target]}

396
app/tiny_probe.py Normal file
View File

@@ -0,0 +1,396 @@
"""Supervised checks against the client's real Tiny, run by hand from a
container console (docker exec, or Portainer > Containers > worker > Console).
Tiny has no sandbox, so this is how the adapter is proven on the real account.
python -m app.tiny_probe produtos [termo] list active products (read-only)
python -m app.tiny_probe formas-envio [termo] list formas de envio, to find pickup (read-only)
python -m app.tiny_probe conferir connection, the products or SKUs and pickup (read-only)
python -m app.tiny_probe campos what a complete order needs from Tiny: payment methods,
categories, sellers, Correios/Jadlog freight (read-only)
python -m app.tiny_probe exemplo NUMERO the structure of an existing order, without the
customer's details, to copy in Site orders (read-only)
python -m app.tiny_probe pedido --cnpj ... --email ... --celular ... [--modo file] [--metros 1.3]
show the test order; --confirmar creates it, then cancels it
python -m app.tiny_probe cancelar TINY_ID cancel a test order (DTF-TESTE-...) left open; nothing else
python -m app.tiny_probe usuarios the account's users and their type, and which one the
integration is connected as (read-only; needs the app's
Usuários (Leitura) and a reconnect)
python -m app.tiny_probe diagnostico --cpf ... --email ... --celular ...
when Tiny refuses the order: sends it again without one
part at a time, stops at the first it accepts (cancelled)
The test order goes through TinyOrders.deliver, exactly as the worker sends a
paid order. The duplicate guard is then proven read-only first (the order must
be found by its purchase-order number) and only then by a second delivery,
which must return the existing order. If the search cannot find the order, the
second delivery is not attempted: it would create a duplicate. Either way the
test order is then cancelled through the API (Tiny has no delete, and the
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
from decimal import Decimal, InvalidOperation
from .core.pricing import PRICES
from .core.secrets import load as load_secret_files
from . import tiny
FIND_ATTEMPTS = 4
FIND_WAIT_SECONDS = 5
def test_order(cnpj, email, celular, mode, now=None, metres='1'):
number = 'TESTE-' + (now or datetime.now(tiny.BRASILIA)).strftime('%Y%m%d%H%M')
unit = PRICES[mode]
total = int(Decimal(metres) * unit)
return {'order_id': 'teste-integracao', 'number': number, 'event': 'payment_approved',
'order': {'customer': {'cnpj': cnpj, 'mail': email, 'zap': celular},
'items': [{'mode': mode, 'grade': 100, 'billed_metres': metres, 'unit_cents': unit,
'total_cents': total}],
'freight': {'service': 'pickup', 'total_cents': 0},
'destination': None, 'total_cents': total}}
def produtos(orders, termo, out):
params = {'situacao': 'A', 'limit': 100}
if termo:
params['nome'] = termo
found = orders.request('GET', '/produtos', params=params).get('itens') or []
for item in found:
preco = (item.get('precos') or {}).get('preco')
out(f"{item['id']}\t{item.get('sku') or '-'}\t{item.get('descricao')}\tR$ {preco}")
out(f'{len(found)} produto(s) ativo(s)' + (f' com "{termo}"' if termo else '') + '.')
def formas_envio(orders, termo, out):
params = {'limit': 100}
if termo:
params['nome'] = termo
found = orders.request('GET', '/formas-envio', params=params).get('itens') or []
for item in found:
out(f"{item.get('id')}\t{item.get('tipo')}\t{item.get('nome')}")
out(f'{len(found)} forma(s) de envio' + (f' com "{termo}"' if termo else '') +
'. A retirada é a do tipo 6 (Customizado) que a equipe usa para retirar pessoalmente.')
# What a complete order (as the store's own orders reach Tiny) looks up, each
# with the app permission it needs in Tiny's Aplicativos screen.
LOOKUPS = (('Formas de recebimento', '/formas-recebimento', 'Forma de Recebimento (Leitura)'),
('Categorias de receita e despesa', '/categorias-receita-despesa', 'Contas Receber (Leitura)'),
('Vendedores', '/vendedores', 'Contatos (Leitura)'),
('Intermediadores', '/intermediadores', 'Intermediadores (Leitura)'))
# The parts of an existing order worth copying; the customer and the address
# are left out. Every other field is listed by name only.
EXAMPLE_FIELDS = ('situacao', 'data', 'dataPrevista', 'naturezaOperacao', 'vendedor', 'transportador',
'pagamento', 'categoria', 'ecommerce', 'intermediador', 'listaPreco', 'deposito',
'numeroOrdemCompra', 'valorFrete', 'origemPedido', 'marcadores')
def short(item):
return json.dumps(item, ensure_ascii=False, separators=(', ', ': '))[:240]
def listed(found):
return found if isinstance(found, list) else (found.get('itens') or [])
def campos(orders, out):
ok = True
for label, path, permission in LOOKUPS:
try:
found = listed(orders.request('GET', path, params={'limit': 100}))
except tiny.TinyError as exc:
ok = False
denied = ': 403 ' in str(exc) or ': 401 ' in str(exc)
out(f'{label}: ' + (f'sem permissão. Libere "{permission}" no aplicativo e reconecte. ({exc})' if denied
else str(exc)))
continue
out(f'{label}: {len(found)}')
for item in found:
out(' ' + short(item))
# Correios and Jadlog, with whatever freight options Tiny keeps for them.
methods = listed(orders.request('GET', '/formas-envio', params={'limit': 100}))
for method in methods:
if not any(word in str(method.get('nome', '')).lower() for word in ('correio', 'jadlog')):
continue
out(f"Forma de envio {method.get('id')} · tipo {method.get('tipo')} · {method.get('nome')}")
try:
out(' ' + short(orders.request('GET', f"/formas-envio/{method['id']}")))
except tiny.TinyError as exc:
out(f' {exc}')
return ok
def exemplo(orders, numero, out):
found = listed(orders.request('GET', '/pedidos', params={'numero': numero, 'limit': 5}))
match = [p for p in found if str(p.get('numeroPedido') or p.get('numero') or '') == str(numero)]
if not match:
out(f'Pedido {numero} não encontrado.')
return False
detail = orders.request('GET', f"/pedidos/{match[0]['id']}")
try:
detail['marcadores'] = orders.request('GET', f"/pedidos/{match[0]['id']}/marcadores")
except tiny.TinyError as exc:
detail['marcadores'] = f'não lidos: {exc}'
out(json.dumps({k: detail[k] for k in EXAMPLE_FIELDS if k in detail}, ensure_ascii=False, indent=2))
out('Outros campos (sem valores): ' + ', '.join(sorted(k for k in detail if k not in EXAMPLE_FIELDS)))
return True
def conferir(orders, out):
ok = True
for mode, setting in tiny.PRODUCT_SETTINGS.items():
prefix, step = tiny.sku_prefix(mode), tiny.step_sku(mode)
if step:
result = tiny.configured_skus(orders, mode)
ok &= result == 'ok'
metre = tiny.metre_sku(mode)
out(f'{tiny.STEP_SETTINGS[mode]} ({tiny.PRODUCTS[mode]}): {result} '
f'({metre + " por metro e " if metre else ""}{step} a cada 10 cm)')
continue
if prefix:
result = tiny.configured_skus(orders, mode)
ok &= result == 'ok'
out(f'{tiny.SKU_SETTINGS[mode]} ({tiny.PRODUCTS[mode]}): {result} '
f'({prefix}.100CM e {prefix}.0010CM a {prefix}.0090CM)')
continue
product, result = tiny.configured_product(orders, mode)
ok &= result == 'ok'
described = f"{product.get('sku') or '-'} · {product.get('descricao')}" if product else ''
out(f'{setting} ({tiny.PRODUCTS[mode]}): {result} {described}'.rstrip())
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'):
ok &= result == 'ok'
out(f'{name}: {result}')
out('Tudo conferido.' if ok else 'Há pendências acima.')
return ok
def pedido(orders, payload, confirm, out, wait=time.sleep):
cnpj = payload['order']['customer']['cnpj']
known = orders.find_contact(cnpj)
if known:
out(f"Contato {tiny.punctuated(cnpj)}: já existe no Tiny (id {known})")
else:
# Named as the worker names a new customer: the company in the CNPJ registry.
company = orders.names(cnpj) if orders.names else None
name = tiny.contact_payload(payload['order'], company)['nome']
out(f'Contato {tiny.punctuated(cnpj)}: não existe; será criado como "{name}"')
out('Pedido que será enviado:')
out(json.dumps(tiny.order_payload(payload, known or 0, product_id=orders.product_id,
shipping=orders.shipping),
ensure_ascii=False, indent=2))
out(f'Marcador: {tiny.TAG} (incluído logo depois de criar o pedido)')
if not confirm:
out('Nada foi criado. Repita com --confirmar para criar este pedido no Tiny.')
return None
first = orders.deliver('teste-integracao', payload)
out(f"1º envio: {first['status']} · Tiny id {first['tiny_id']} · nº {first['tiny_number']}")
try:
for attempt in range(FIND_ATTEMPTS):
found = orders.find(payload)
if found:
break
if attempt < FIND_ATTEMPTS - 1:
wait(FIND_WAIT_SECONDS)
else:
out(f'FALHA: a busca por {tiny.purchase_order(payload["number"])} não encontrou o pedido. '
'Um reenvio criaria um duplicado; o 2º envio não foi feito.')
return False
# What Tiny kept of the e-commerce number, read back from the order.
wanted = tiny.purchase_order(payload['number'])
shop = orders.request('GET', f"/pedidos/{first['tiny_id']}").get('ecommerce') or {}
out(f"E-commerce no Tiny: numeroPedidoEcommerce {shop.get('numeroPedidoEcommerce') or '(vazio)'}" +
(f" · canal {shop.get('nome') or '?'} (id {shop['id']})" if shop.get('id') else ' · sem canal'))
numbered = shop.get('numeroPedidoEcommerce') == wanted
if not numbered:
out(f'FALHA: o Tiny não guardou {wanted} em numeroPedidoEcommerce.')
second = orders.deliver('teste-integracao', payload)
out(f"2º envio: {second['status']} · Tiny id {second['tiny_id']}")
found_again = second['status'] == 'already-created' and second['tiny_id'] == first['tiny_id']
out('OK: o reenvio encontrou o mesmo pedido.' if found_again else 'FALHA: o reenvio não devolveu o mesmo pedido.')
return numbered and found_again
finally:
# Whatever happened above, the test order does not stay open.
cancelar(orders, first['tiny_id'], out)
def connected_as(orders):
"""Who logged in when the integration was connected: the name and e-mail
in the access token's claims (an OpenID token), never the token itself."""
try:
part = orders.auth.access_token().split('.')[1]
claims = json.loads(base64.urlsafe_b64decode(part + '=' * (-len(part) % 4)))
except Exception:
return {}
return {key: claims[key] for key in ('name', 'email', 'preferred_username') if claims.get(key)}
def usuarios(orders, out):
"""The account's users, with their type, and the one the integration
acts as: the API does what that user may do (read-only)."""
me = connected_as(orders)
if me:
out('Integração conectada como: ' + ' · '.join(str(v) for v in me.values()))
try:
found = orders.request('GET', '/usuarios', params={'limit': 100}).get('itens') or []
except tiny.TinyError as exc:
if ': 403 ' in str(exc) or ': 401 ' in str(exc):
out(f'Tiny recusou a lista de usuários ({exc}). Marque Usuários (Leitura) nas permissões do '
'aplicativo e conecte o Tiny de novo no Kanban (Integrações).')
return False
raise
ours = {str(v).lower() for v in me.values()}
for user in found:
mine = str(user.get('email') or '').lower() in ours or str(user.get('emailComunicacao') or '').lower() in ours
out(f"{user.get('id')}\t{user.get('tipo') or '-'}\t{user.get('nome')}\t{user.get('email')}"
+ ('\t<- integração' if mine else ''))
out(f'{len(found)} usuário(s).')
return True
def diagnostico(orders, payload, out):
"""Which part of the order Tiny refuses, when it says only 403. The same
test order is sent whole, then without one part at a time, then with only
what an order cannot go without; the first version Tiny accepts names the
part, and that order is cancelled at once. The contact must exist already:
this never creates one."""
cnpj = payload['order']['customer']['cnpj']
known = orders.find_contact(cnpj)
if not known:
out(f'Contato {tiny.punctuated(cnpj)} não existe no Tiny; use o CPF de um contato que já existe.')
return False
out(f'Contato {tiny.punctuated(cnpj)}: já existe no Tiny (id {known})')
full = tiny.order_payload(payload, known, product_id=orders.product_id, shipping=orders.shipping)
without = lambda key: {k: v for k, v in full.items() if k != key}
versions = [('completo', full)] + [(f'sem {key}', without(key)) for key in
('ecommerce', 'pagamento', 'transportador', 'dataPrevista')
if key in full]
versions.append(('só o essencial (data, contato, itens, nº de compra)',
{k: full[k] for k in ('data', 'idContato', 'numeroOrdemCompra', 'itens')}))
for name, body in versions:
try:
created = orders.request('POST', '/pedidos', json=body)
except tiny.TinyError as exc:
out(f'{name}: recusado ({exc})')
continue
out(f"{name}: ACEITO (Tiny id {created.get('id')}). O que falta no completo é o que foi tirado aqui.")
cancelar(orders, created.get('id'), out)
return True
out('Todas as versões foram recusadas, até a essencial: não é o conteúdo do pedido, é a permissão '
'do usuário do Tiny para incluir pedidos de venda.')
return False
def cancelar(orders, tiny_id, out):
"""Cancel a test order through the API and read it back. Only orders
this probe made (purchase order DTF-TESTE-...) are touched."""
try:
detail = orders.request('GET', f'/pedidos/{tiny_id}')
number = detail.get('numeroPedido')
if not str(detail.get('numeroOrdemCompra') or '').startswith(tiny.purchase_order('TESTE-')):
out(f'Recusado: o pedido {tiny_id} não é um pedido de teste (DTF-TESTE-...); nada foi alterado.')
return False
if detail.get('situacao') != tiny.CANCELADA:
orders.set_situacao(tiny_id, tiny.CANCELADA)
detail = orders.request('GET', f'/pedidos/{tiny_id}')
except tiny.TinyError as exc:
out(f'FALHA ao cancelar o pedido {tiny_id}: {exc}. Rode: python -m app.tiny_probe cancelar {tiny_id}')
return False
situacao = detail.get('situacao')
if situacao == tiny.CANCELADA:
out(f'Pedido nº {number} cancelado no Tiny.')
return True
out(f'FALHA: o pedido nº {number} ficou em {tiny.SITUACOES.get(situacao, situacao)}. '
f'Rode: python -m app.tiny_probe cancelar {tiny_id}')
return False
def main(argv=None, orders=None, out=print):
parser = argparse.ArgumentParser(prog='python -m app.tiny_probe')
commands = parser.add_subparsers(dest='command', required=True)
listing = commands.add_parser('produtos')
listing.add_argument('termo', nargs='?', default='')
methods = commands.add_parser('formas-envio')
methods.add_argument('termo', nargs='?', default='')
commands.add_parser('conferir')
commands.add_parser('campos')
example = commands.add_parser('exemplo')
example.add_argument('numero')
cancel = commands.add_parser('cancelar')
cancel.add_argument('tiny_id', type=int)
order = commands.add_parser('pedido')
order.add_argument('--cnpj', '--cpf', dest='cnpj', required=True, help='CNPJ ou CPF do cliente')
order.add_argument('--email', required=True)
order.add_argument('--celular', required=True)
order.add_argument('--modo', choices=sorted(tiny.PRODUCT_SETTINGS), default='file')
order.add_argument('--metros', default='1', help='metragem cobrada, em passos de 10 cm (ex.: 1.3)')
order.add_argument('--confirmar', action='store_true')
commands.add_parser('usuarios')
probe = commands.add_parser('diagnostico')
probe.add_argument('--cnpj', '--cpf', dest='cnpj', required=True, help='CNPJ ou CPF de um contato que já existe')
probe.add_argument('--email', required=True)
probe.add_argument('--celular', required=True)
args = parser.parse_args(argv)
if orders is None:
load_secret_files()
from .cnpj import company
# The same names for new contacts as the worker uses (app/worker.py).
orders = tiny.TinyOrders(auth=tiny.TinyAuth(), names=company)
try:
if args.command == 'produtos':
produtos(orders, args.termo, out)
return 0
if args.command == 'formas-envio':
formas_envio(orders, args.termo, out)
return 0
if args.command == 'conferir':
return 0 if conferir(orders, out) else 1
if args.command == 'campos':
return 0 if campos(orders, out) else 1
if args.command == 'exemplo':
return 0 if exemplo(orders, args.numero, out) else 1
if args.command == 'cancelar':
return 0 if cancelar(orders, args.tiny_id, out) else 1
if args.command == 'usuarios':
return 0 if usuarios(orders, out) else 1
cnpj = ''.join(ch for ch in args.cnpj if ch.isdigit())
if len(cnpj) not in (11, 14):
out('Informe um CPF (11 dígitos) ou um CNPJ (14 dígitos).')
return 2
if args.command == 'diagnostico':
return 0 if diagnostico(orders, test_order(cnpj, args.email, args.celular, 'file'), out) else 1
try:
metres = Decimal(args.metros.replace(',', '.'))
except InvalidOperation:
metres = Decimal(0)
if metres < 1 or (metres * 10) % 1:
out('Informe a metragem a partir de 1 m, em passos de 10 cm (ex.: 1.3).')
return 2
payload = test_order(cnpj, args.email, args.celular, args.modo, metres=str(metres))
return 0 if pedido(orders, payload, args.confirmar, out) is not False else 1
except tiny.TinyError as exc:
out(f'Tiny: {exc}')
return 1
if __name__ == '__main__':
sys.exit(main())

72
app/unpaid.py Normal file
View File

@@ -0,0 +1,72 @@
"""Orders made on the Site and never paid (Dropstar's Fase 2, front 9, 05/11/2026).
An approved quote is an order the customer did not pay yet: Kanban's
Cotações › "Aguardando pagamento" lists it, with how long ago it came and
when it expires, so the seller can charge it by WhatsApp. After
QUOTE_VALID_HOURS (24 h) without payment it expires on its own: its files
are freed for deletion and the customer gets an e-mail ("seu pedido expirou,
suba de novo quando quiser"). Never while a payment attempt is still live
(a Pix not yet expired, a card being processed), so a late payment always
finds its files. Números counts orders made, paid and expired, and the
abandonment rate.
"""
from datetime import datetime, timedelta, timezone
from . import mail, payments
from .payments import 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).
FINAL_INTENT = ('approved', 'rejected', 'cancelled', 'expired', 'refunded')
def expire(c, origin):
"""Expire the approved, unpaid quotes past QUOTE_VALID_HOURS: set
quotes.expired_at, free their files (payments.release_files) and queue the
customer's e-mail (mail.quote_expired). Returns how many expired."""
rows = c.execute('''SELECT q.* FROM dtf_local.quotes q
WHERE q.approved IS NOT NULL AND q.discarded_at IS NULL AND q.expired_at IS NULL
AND q.approved_at <= now() - make_interval(hours => %s)
AND NOT EXISTS (SELECT 1 FROM dtf_local.orders o WHERE o.quote_id=q.id)
AND NOT EXISTS (
SELECT 1 FROM dtf_local.payment_intents i
WHERE i.quote_id=q.id
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)
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()
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
# as open, or its own files would stay held.
payments.release_files(c, payments.quote_uploads(row['approved']))
# Only a quote that just ran out is news to the customer: the backlog
# from before this front existed expires silently on the first pass.
if row['approved_at'] > datetime.now(timezone.utc) - timedelta(hours=2 * QUOTE_VALID_HOURS):
mail.quote_expired(c, row, origin)
return len(rows)
def figures(c, start, end):
"""Números, for quotes approved between the local days `start` and `end`
(inclusive): {'made': n, 'paid': n, 'expired': n, 'waiting': n,
'abandon_pct': float | None}. Paid has an order; expired has expired_at;
waiting is neither yet. abandon_pct is expired / (paid + expired) * 100,
one decimal, None when both are 0."""
row = c.execute('''SELECT count(*) AS made,
count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.orders o WHERE o.quote_id=q.id)) AS paid,
count(*) FILTER (WHERE q.expired_at IS NOT NULL) AS expired,
count(*) FILTER (WHERE q.expired_at IS NULL
AND NOT EXISTS (SELECT 1 FROM dtf_local.orders o WHERE o.quote_id=q.id)) AS waiting
FROM dtf_local.quotes q
WHERE q.discarded_at IS NULL AND q.approved_at IS NOT NULL
AND (q.approved_at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s''',
(start, end)).fetchone()
paid, expired = row['paid'], row['expired']
decided = paid + expired
return {'made': row['made'], 'paid': paid, 'expired': expired, 'waiting': row['waiting'],
'abandon_pct': round(expired / decided * 100, 1) if decided else None}

View File

@@ -5,8 +5,11 @@ 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 .adapters import FakeTiny, FakeWhatsApp, LocalS3Storage, require_runtime
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
from .printjobs import render_loop
@@ -14,14 +17,19 @@ from .scanning import ClamAV, scan_loop
load_secret_files()
require_runtime()
adapters = {'tiny': FakeTiny(), 'whatsapp': FakeWhatsApp()}
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
adapters['tiny'] = TinyOrders()
from .cnpj import company
adapters['tiny'] = TinyOrders(names=company)
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
@@ -33,25 +41,61 @@ 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']}/")
c.execute('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s', (row['id'],))
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (row['id'],))
c.execute('DELETE FROM dtf_local.sessions WHERE expires_at<=now()')
c.execute("DELETE FROM dtf_local.account_signups WHERE created_at<now()-interval '1 day'")
c.execute("DELETE FROM dtf_local.email_changes WHERE created_at<now()-interval '1 day'")
c.execute("DELETE FROM dtf_local.password_resets WHERE expires_at<now()-interval '1 day'")
c.execute('DELETE FROM dtf_local.operator_sessions WHERE expires_at<=now()')
c.execute("DELETE FROM dtf_local.login_attempts WHERE started_at<now()-interval '1 day'")
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.
@@ -74,17 +118,66 @@ def tiny_keepalive():
except Exception:
logging.exception('Tiny connection refresh failed')
def reconcile_payments():
"""Every minute: the payments of open quotes, asked of the provider, so an
approval becomes the order even when its notification never arrives."""
global last_reconcile
if time.monotonic()-last_reconcile < 60:
return
last_reconcile = time.monotonic()
from . import payments
from .runtime import payment
payments.reconcile(connect, payment)
def resolve_names():
"""Every minute: the company names of a few new customers' CNPJs, on a
thread of their own, so a slow registry never holds up orders."""
global last_names, names_thread
if time.monotonic()-last_names < 60 or (names_thread and names_thread.is_alive()):
return
last_names = time.monotonic()
from . import cnpj
def run():
try:
cnpj.resolve(connect)
except Exception:
logging.exception('CNPJ name lookup failed')
names_thread = threading.Thread(target=run, daemon=True)
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).
with connect() as c:
unpaid.expire(c, os.environ.get('PUBLIC_ORIGIN', 'http://localhost'))
last_cleanup = time.monotonic()
mail.send_pending(connect)
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):
@@ -105,6 +198,7 @@ class Health(BaseHTTPRequestHandler):
pass
if __name__ == '__main__':
observability.init('worker')
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.
@@ -36,7 +40,30 @@ x-app: &app
MP_WEBHOOK_SECRET: ${MP_WEBHOOK_SECRET:-}
MP_NOTIFICATION_URL: ${MP_NOTIFICATION_URL:-}
MP_PUBLIC_KEY: ${MP_PUBLIC_KEY:-}
FREIGHT_ADAPTER: fake
FREIGHT_ADAPTER: ${FREIGHT_ADAPTER:-fake}
JADLOG_TOKEN: ${JADLOG_TOKEN:-}
JADLOG_CNPJ: ${JADLOG_CNPJ:-}
JADLOG_CONTA: ${JADLOG_CONTA:-}
JADLOG_CONTRATO: ${JADLOG_CONTRATO:-}
JADLOG_PESO_BASE_KG: ${JADLOG_PESO_BASE_KG:-}
JADLOG_PESO_POR_METRO_KG: ${JADLOG_PESO_POR_METRO_KG:-}
JADLOG_CAIXA_CM: ${JADLOG_CAIXA_CM:-}
JADLOG_CUBAGEM_KG_M3: ${JADLOG_CUBAGEM_KG_M3:-}
JADLOG_METROS_POR_CAIXA: ${JADLOG_METROS_POR_CAIXA:-}
FREIGHT_PRODUCTION_DAYS: ${FREIGHT_PRODUCTION_DAYS:-0}
# Correios: off locally unless an access code is set in .env.
CORREIOS_CODIGO_ACESSO: ${CORREIOS_CODIGO_ACESSO:-}
CORREIOS_USUARIO: ${CORREIOS_USUARIO:-}
CORREIOS_CARTAO: ${CORREIOS_CARTAO:-}
CORREIOS_CONTRATO: ${CORREIOS_CONTRATO:-}
CORREIOS_COD_PAC: ${CORREIOS_COD_PAC:-}
CORREIOS_COD_SEDEX: ${CORREIOS_COD_SEDEX:-}
# Carts the Site priced are approved at checkout; larger ones wait for review.
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-0}
# Fixed price of the designer's treatment per order; 0 hides the option.
TREATMENT_CENTS: ${TREATMENT_CENTS:-0}
TINY_ADAPTER: ${TINY_ADAPTER:-fake}
TINY_CLIENT_ID: ${TINY_CLIENT_ID:-}
TINY_CLIENT_SECRET: ${TINY_CLIENT_SECRET:-}
@@ -45,16 +72,38 @@ x-app: &app
TINY_PRODUCT_TEXTIL_AVULSA: ${TINY_PRODUCT_TEXTIL_AVULSA:-}
TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-}
TINY_PRODUCT_UV_AVULSA: ${TINY_PRODUCT_UV_AVULSA:-}
TINY_PRODUCT_TREATMENT: ${TINY_PRODUCT_TREATMENT:-}
TINY_SKU_TEXTIL_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-}
TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-}
TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-}
TINY_SKU_UV_AVULSA: ${TINY_SKU_UV_AVULSA:-}
TINY_SKU10_TEXTIL_FOLHA: ${TINY_SKU10_TEXTIL_FOLHA:-}
TINY_SKU10_TEXTIL_AVULSA: ${TINY_SKU10_TEXTIL_AVULSA:-}
TINY_SKU10_UV_FOLHA: ${TINY_SKU10_UV_FOLHA:-}
TINY_SKU10_UV_AVULSA: ${TINY_SKU10_UV_AVULSA:-}
TINY_SKU_METRO_TEXTIL_FOLHA: ${TINY_SKU_METRO_TEXTIL_FOLHA:-}
TINY_SKU_METRO_TEXTIL_AVULSA: ${TINY_SKU_METRO_TEXTIL_AVULSA:-}
TINY_SKU_METRO_UV_FOLHA: ${TINY_SKU_METRO_UV_FOLHA:-}
TINY_SKU_METRO_UV_AVULSA: ${TINY_SKU_METRO_UV_AVULSA:-}
TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-}
WHATSAPP_ADAPTER: fake
# log keeps each e-mail in the database and the worker's log, with the
# recovery link readable there; smtp with the SMTP_* settings in .env.
MAIL_ADAPTER: ${MAIL_ADAPTER:-log}
MAIL_FROM: ${MAIL_FROM:-DTF Dropstar <nao-responda@localhost>}
MAIL_REPLY_TO: ${MAIL_REPLY_TO:-}
SMTP_HOST: ${SMTP_HOST:-}
SMTP_PORT: ${SMTP_PORT:-}
SMTP_SECURITY: ${SMTP_SECURITY:-starttls}
SMTP_USER: ${SMTP_USER:-}
SMTP_PASSWORD: ${SMTP_PASSWORD:-}
STORAGE_ADAPTER: s3-local
MOCK_FREIGHT_CENTS: ${MOCK_FREIGHT_CENTS:-1500}
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-5368709120}
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-4294967296}
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}
SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-134217728}
MAX_PENDING_UPLOADS: ${MAX_PENDING_UPLOADS:-30}
SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-2097152000}
networks: [local]
init: true
security_opt: [no-new-privileges:true]
@@ -138,6 +187,9 @@ services:
S3_APP_USER: ${S3_APP_USER:-dtf_app}
S3_APP_PASSWORD: ${S3_APP_PASSWORD:-local-app-storage-only}
S3_BUCKET: ${S3_BUCKET:-dtf-local-artwork}
S3_BACKUP_BUCKET: dtf-local-backups
S3_BACKUP_USER: dtf_backup
S3_BACKUP_PASSWORD: local-backup-storage-only
networks: [local]
depends_on:
storage: {condition: service_healthy}
@@ -165,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}
@@ -177,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}
@@ -187,6 +247,28 @@ services:
timeout: 3s
retries: 12
# The daily database backup, against the local backup bucket. Idle until
# BACKUP_AGE_RECIPIENT is set; tests/backup_test.py runs it with a throwaway key.
backup:
build:
context: .
dockerfile: infra/Dockerfile
command: python -m ops.db_backup serve
environment:
DATABASE_ADMIN_URL: postgresql://${POSTGRES_USER:-dtf_local}:${POSTGRES_PASSWORD:-local-database-only}@db:5432/${POSTGRES_DB:-dtf_local}
BACKUP_S3_ENDPOINT: http://storage:9000
BACKUP_BUCKET: dtf-local-backups
BACKUP_ACCESS_KEY_ID: dtf_backup
BACKUP_SECRET_ACCESS_KEY: local-backup-storage-only
BACKUP_REGION: us-east-1
BACKUP_AGE_RECIPIENT: ${BACKUP_AGE_RECIPIENT:-}
networks: [local]
read_only: true
tmpfs: [/tmp]
depends_on:
db-init: {condition: service_completed_successfully}
storage-init: {condition: service_completed_successfully}
site:
build:
context: .
@@ -195,6 +277,8 @@ services:
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:${STORAGE_PORT:-9000}}
# 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
@@ -219,6 +303,8 @@ services:
WEB_INDEX: kanban.html
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"
@@ -13,8 +15,14 @@ LABEL org.opencontainers.image.title="DTF Portal/API" \
# The base is pinned, so its OS packages are frozen at the digest's build date.
# Upgrade them here or the image ships known-fixed Debian vulnerabilities, which
# is what the production image was doing while the local one already did this.
RUN apt-get update \
# pg_dump and age are for the database backup (ops/db_backup.py). Debian 13
# ships PostgreSQL 17, the server's major version, which pg_dump must match.
# The day (PACKAGES_DAY, set by CI) is part of this layer, so a cached build
# still fetches the fixes published since.
ARG PACKAGES_DAY=unset
RUN echo "packages refreshed: $PACKAGES_DAY" && apt-get update \
&& apt-get upgrade -y \
&& apt-get install -y --no-install-recommends postgresql-client-17 age \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app

View File

@@ -14,15 +14,20 @@ ENV NGINX_TEMPLATE=/build/deploy/nginx.conf.template
RUN python infra/compile_web.py
FROM ${NGINX_BASE_IMAGE}
# Same reason as the API image: a pinned base freezes its packages.
RUN apk upgrade --no-cache
# Same reason as the API image: a pinned base freezes its packages. The day
# (PACKAGES_DAY, set by CI) is part of this layer, so a cached build still
# fetches the fixes published since: brotli-libs 1.2.1 on 2026-10-29 was
# missed by a cached upgrade layer and blocked the release gate.
ARG PACKAGES_DAY=unset
RUN echo "packages refreshed: $PACKAGES_DAY" && apk upgrade --no-cache
ARG VCS_REF=unknown
LABEL org.opencontainers.image.title="DTF Site and Kanban" \
org.opencontainers.image.revision="$VCS_REF" \
org.opencontainers.image.source="DTF System repository"
ENV WEB_INDEX=index.html PUBLIC_HOST=invalid.example S3_PUBLIC_ENDPOINT=https://invalid.example
COPY --from=policy /build/default.conf.template /etc/nginx/templates/default.conf.template
COPY web/ /usr/share/nginx/html/
# The HTML from the policy stage, with every asset address versioned.
COPY --from=policy /build/web/ /usr/share/nginx/html/
# The official entrypoint renders the server configuration at startup and Nginx
# writes its PID/cache files. Keep the service non-root while granting it

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