Compare commits

..

101 Commits

Author SHA1 Message Date
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
139 changed files with 9338 additions and 1456 deletions

View File

@@ -42,10 +42,17 @@ TINY_ADAPTER=fake
# JADLOG_CNPJ=... # the "Usuário" Jadlog issued, the CNPJ that contracts freight # JADLOG_CNPJ=... # the "Usuário" Jadlog issued, the CNPJ that contracts freight
# JADLOG_CONTA=... # conta corrente # JADLOG_CONTA=... # conta corrente
# JADLOG_CONTRATO= # only if Jadlog issued a contract number # JADLOG_CONTRATO= # only if Jadlog issued a contract number
WHATSAPP_ADAPTER=fake # 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 STORAGE_ADAPTER=s3-local
MOCK_FREIGHT_CENTS=1500 MOCK_FREIGHT_CENTS=1500
MAX_UPLOAD_BYTES=5368709120 MAX_UPLOAD_BYTES=4294967296
UPLOAD_PART_BYTES=8388608 UPLOAD_PART_BYTES=8388608
STORAGE_QUOTA_BYTES=53687091200 STORAGE_QUOTA_BYTES=53687091200
OWNER_UPLOAD_QUOTA_BYTES=10737418240 OWNER_UPLOAD_QUOTA_BYTES=10737418240

View File

@@ -73,7 +73,7 @@ jobs:
# one a developer exercises on localhost. # one a developer exercises on localhost.
- name: API and workflow regressions - name: API and workflow regressions
run: | run: |
for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test thumbnail_backfill_test launch_reset_test; do for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test mail_test thumbnail_backfill_test launch_reset_test; do
echo "--- $suite" echo "--- $suite"
$COMPOSE exec -T \ $COMPOSE exec -T \
-e SITE_BASE_URL=http://site \ -e SITE_BASE_URL=http://site \
@@ -86,7 +86,7 @@ jobs:
# the generator's geometry. The provider suites use a fake transport: they # the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration. # prove the documented contract, not the integration.
- name: Print-file geometry and provider adapters - name: Print-file geometry and provider adapters
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_quote_review tests.test_large_files tests.test_grade_check -v run: $COMPOSE exec -T api python -m unittest tests.test_printfile 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 -v
- name: Runtime and retention regressions - name: Runtime and retention regressions
run: | run: |
@@ -189,7 +189,7 @@ jobs:
set -- set --
[ -n "$PYTHON_BASE_IMAGE" ] && set -- --build-arg PYTHON_BASE_IMAGE="$PYTHON_BASE_IMAGE" [ -n "$PYTHON_BASE_IMAGE" ] && set -- --build-arg PYTHON_BASE_IMAGE="$PYTHON_BASE_IMAGE"
docker build --file deploy/Dockerfile.api "$@" \ 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 }}" . --tag "$image:latest" --tag "$image:${{ gitea.sha }}" .
- name: Build web - name: Build web
run: | run: |
@@ -198,7 +198,7 @@ jobs:
[ -n "$PYTHON_BASE_IMAGE" ] && set -- --build-arg PYTHON_BASE_IMAGE="$PYTHON_BASE_IMAGE" [ -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" [ -n "$NGINX_BASE_IMAGE" ] && set -- "$@" --build-arg NGINX_BASE_IMAGE="$NGINX_BASE_IMAGE"
docker build --file deploy/Dockerfile.web "$@" \ 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 }}" . --tag "$image:latest" --tag "$image:${{ gitea.sha }}" .
# CRITICAL blocks, HIGH is reported. Both images carry zero CRITICAL after # CRITICAL blocks, HIGH is reported. Both images carry zero CRITICAL after
# the base pinning and OS upgrades, so this gate holds the line already # the base pinning and OS upgrades, so this gate holds the line already

View File

@@ -12,13 +12,10 @@ from botocore.exceptions import ClientError
def require_runtime(): def require_runtime():
"""Validate the supported local and R2-backed deployment modes. """Validate the supported local and R2-backed deployment modes.
Real payment, freight, ERP, and WhatsApp providers are deliberately not Each provider is fake until its settings are complete; a real one refuses
enabled yet. A non-local deployment keeps those adapters fake and disables to start without them.
checkout until their audited implementations are added.
""" """
environment = os.environ.get('APP_ENV', 'local') environment = os.environ.get('APP_ENV', 'local')
if os.environ.get('WHATSAPP_ADAPTER') != 'fake':
raise RuntimeError('WHATSAPP must use the currently supported fake adapter')
freight = os.environ.get('FREIGHT_ADAPTER') freight = os.environ.get('FREIGHT_ADAPTER')
if freight == 'jadlog': if freight == 'jadlog':
from .jadlog import required_settings as jadlog_settings from .jadlog import required_settings as jadlog_settings
@@ -27,6 +24,13 @@ def require_runtime():
raise RuntimeError(f'{name} is required for the Jadlog adapter') raise RuntimeError(f'{name} is required for the Jadlog adapter')
elif freight != 'fake': elif freight != 'fake':
raise RuntimeError('FREIGHT must use the fake or jadlog adapter') 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') tiny = os.environ.get('TINY_ADAPTER')
if tiny == 'tiny': if tiny == 'tiny':
from .tiny import required_settings from .tiny import required_settings
@@ -44,6 +48,16 @@ def require_runtime():
raise RuntimeError(f'{name} is required for the Mercado Pago adapter') raise RuntimeError(f'{name} is required for the Mercado Pago adapter')
elif payment != 'fake': elif payment != 'fake':
raise RuntimeError('PAYMENT must use the fake or mercadopago adapter') 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 environment == 'local':
if os.environ.get('STORAGE_ADAPTER') != 's3-local': if os.environ.get('STORAGE_ADAPTER') != 's3-local':
raise RuntimeError('Local runtime requires local S3 storage') raise RuntimeError('Local runtime requires local S3 storage')
@@ -159,6 +173,7 @@ class FreightAdapter(Protocol):
class FakeFreight: class FakeFreight:
name = 'fake' name = 'fake'
services = {'mock-standard': 'Entrega simulada'}
def quote(self, service: str, postal_code: str, metres=None, declared_cents: int = 0) -> dict: def quote(self, service: str, postal_code: str, metres=None, declared_cents: int = 0) -> dict:
if service == 'pickup': if service == 'pickup':
@@ -169,7 +184,7 @@ class FakeFreight:
if cents < 0: if cents < 0:
raise ValueError('Invalid mock freight configuration') raise ValueError('Invalid mock freight configuration')
return {'provider': 'fake', 'service': service, 'postal_code': postal_code, 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): class EventAdapter(Protocol):
def deliver(self, event_key: str, payload: dict) -> dict: ... def deliver(self, event_key: str, payload: dict) -> dict: ...
@@ -179,11 +194,6 @@ class FakeTiny:
return {'provider': 'fake-tiny', 'reference': f"LOCAL-{payload['number']}", return {'provider': 'fake-tiny', 'reference': f"LOCAL-{payload['number']}",
'event_key': event_key, 'status': 'recorded-locally'} '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'}
class ObjectStorage(Protocol): class ObjectStorage(Protocol):
def begin(self, key: str) -> str: ... def begin(self, key: str) -> str: ...
def parts(self, key: str, upload_id: str) -> list: ... def parts(self, key: str, upload_id: str) -> list: ...

View File

@@ -21,23 +21,25 @@ def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
with db.connect() as c: with db.connect() as c:
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone() row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
if not row: raise HTTPException(404, 'Order not found') 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['state'] not in ('rec','cor'): raise HTTPException(409, 'Order is not in artwork review')
return begin_upload(body, session_id=operator_identity(user)) return begin_upload(body, session_id=operator_identity(user))
@router.get('/api/operator/uploads/{uid}') @router.get('/api/operator/uploads/{uid}')
def final_status(uid: UUID, user=Depends(operator)): def final_status(uid: UUID, user=Depends(operator)):
return upload_status(uid,session_id=operator_identity(user)) 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}') @router.post('/api/operator/uploads/{uid}/parts/{number}')
def final_part(uid: UUID, number: int, user=Depends(can('produce'))): def final_part(uid: UUID, number: int, user=Depends(can('deliver'))):
return part_url(uid,number,session_id=operator_identity(user)) return part_url(uid,number,session_id=operator_identity(user))
@router.post('/api/operator/uploads/{uid}/complete') @router.post('/api/operator/uploads/{uid}/complete')
def final_complete(uid: UUID, user=Depends(can('produce'))): def final_complete(uid: UUID, user=Depends(can('deliver'))):
return complete_upload(uid,session_id=operator_identity(user)) return complete_upload(uid,session_id=operator_identity(user))
@router.delete('/api/operator/uploads/{uid}') @router.delete('/api/operator/uploads/{uid}')
def final_cancel(uid: UUID, user=Depends(can('produce'))): def final_cancel(uid: UUID, user=Depends(can('deliver'))):
return cancel_upload(uid,session_id=operator_identity(user)) return cancel_upload(uid,session_id=operator_identity(user))
@router.get('/api/operator/orders/{oid}/files') @router.get('/api/operator/orders/{oid}/files')

View File

@@ -1,4 +1,6 @@
"""Customer accounts, their orders, and the corrections they submit.""" """Customer accounts, their orders, and the corrections they submit."""
import hashlib
import secrets
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from uuid import UUID, uuid4 from uuid import UUID, uuid4
@@ -10,10 +12,12 @@ from psycopg.types.json import Jsonb
from ..core import db from ..core import db
from ..artwork import submit_files from ..artwork import submit_files
from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner, from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner, login_failed, password_hash,
login_failed, password_hash, password_matches, session_row, throttle, transfer_guest) password_matches, rate_limit, session_row, throttle, transfer_guest)
from ..core.models import ArtworkSubmission, EmailChange, Login, PasswordChange, ProfileUpdate, Register from ..core.models import (ArtworkSubmission, EmailChange, EmailCode, EmailResend, ForgotPassword, Login,
from ..runtime import STATES, file_rows, order_code, owned_order, storage 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 from ..scanning import require_clean
router = APIRouter() router = APIRouter()
@@ -24,6 +28,87 @@ def current(request):
except HTTPException: return None 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))
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') @router.post('/api/account/register')
def register(body: Register, request: Request, response: Response): def register(body: Register, request: Request, response: Response):
email = body.customer.mail.strip().lower() email = body.customer.mail.strip().lower()
@@ -31,22 +116,109 @@ def register(body: Register, request: Request, response: Response):
# Registration attempts keep counting against the email, as before. # Registration attempts keep counting against the email, as before.
login_failed(email) login_failed(email)
previous = current(request) previous = current(request)
encoded = password_hash(body.password)
identity = uuid4()
profile = body.customer.model_dump() profile = body.customer.model_dump()
profile['mail'] = email 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))
return len(orders)
def create_account(profile, password, previous, response, verified=False):
identity = uuid4()
try: try:
with db.connect() as c: with db.connect() as c:
if previous and c.execute('SELECT id FROM dtf_local.accounts WHERE id=%s', (previous['owner'],)).fetchone(): c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile,email_verified) VALUES(%s,%s,%s,%s,%s)',
raise HTTPException(409, 'Saia da conta atual antes de criar outra.') (identity, profile['mail'], password, Jsonb(profile), verified))
c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile) VALUES(%s,%s,%s,%s)', (identity,email,encoded,Jsonb(profile)))
if previous: transfer_guest(c, previous, identity) if previous: transfer_guest(c, previous, identity)
if verified: claim_orders(c, identity, profile)
new_session(c, response, identity) new_session(c, response, identity)
except UniqueViolation: except UniqueViolation:
raise HTTPException(409, 'Já existe uma conta com este e-mail. Entre com a sua senha.') raise HTTPException(409, 'Já existe uma conta com este e-mail. Entre com a sua senha.')
audit('account_registered', account=str(identity)) audit('account_registered', account=str(identity))
return {'customer': profile} 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') @router.post('/api/account/login')
def login(body: Login, request: Request, response: Response): def login(body: Login, request: Request, response: Response):
email = body.email.strip().lower() email = body.email.strip().lower()
@@ -67,6 +239,9 @@ def login(body: Login, request: Request, response: Response):
if previous: if previous:
transfer_guest(c, previous, account['id']) transfer_guest(c, previous, account['id'])
c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['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']) new_session(c, response, account['id'])
audit('customer_login_success', account=str(account['id'])) audit('customer_login_success', account=str(account['id']))
return {'customer': account['profile']} return {'customer': account['profile']}
@@ -96,12 +271,14 @@ def account_row(c, identity, lock=False):
@router.post('/api/account/profile') @router.post('/api/account/profile')
def update_profile(body: ProfileUpdate, identity=Depends(owner)): def update_profile(body: ProfileUpdate, identity=Depends(owner)):
"""WhatsApp and the saved delivery address. The CNPJ is the account's and """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.""" does not change; the e-mail is the login and changes on its own route."""
with db.connect() as c: with db.connect() as c:
row = account_row(c, identity, lock=True) row = account_row(c, identity, lock=True)
profile = {**row['profile'], 'zap': body.zap, profile = {**row['profile'], 'zap': body.zap,
'address': body.address.model_dump() if body.address else None} '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)) c.execute('UPDATE dtf_local.accounts SET profile=%s WHERE id=%s', (Jsonb(profile), identity))
audit('account_profile_updated', account=str(identity)) audit('account_profile_updated', account=str(identity))
return {'customer': profile} return {'customer': profile}
@@ -114,15 +291,71 @@ def change_email(body: EmailChange, request: Request, identity=Depends(owner)):
if not password_matches(body.password, row['password_hash']): if not password_matches(body.password, row['password_hash']):
login_failed(row['email']) login_failed(row['email'])
raise HTTPException(401, 'Senha incorreta.') raise HTTPException(401, 'Senha incorreta.')
profile = {**row['profile'], 'mail': body.email} 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: try:
with db.connect() as c: with db.connect() as c:
c.execute('UPDATE dtf_local.accounts SET email=%s, profile=%s WHERE id=%s', (body.email, Jsonb(profile), identity)) 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: except UniqueViolation:
raise HTTPException(409, 'Este e-mail já é de outra conta.') raise HTTPException(409, 'Este e-mail já é de outra conta.')
audit('account_email_changed', account=str(identity)) audit('account_email_changed', account=str(identity))
return {'customer': profile} 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') @router.post('/api/account/password')
def change_password(body: PasswordChange, request: Request, identity=Depends(owner)): def change_password(body: PasswordChange, request: Request, identity=Depends(owner)):
with db.connect() as c: with db.connect() as c:
@@ -139,6 +372,67 @@ def change_password(body: PasswordChange, request: Request, identity=Depends(own
audit('account_password_changed', account=str(identity)) audit('account_password_changed', account=str(identity))
return {'ok': True} 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. # The order list's groups, as the customer filters them.
GROUPS = {'pay': 'Aguardando pagamento', 'prod': 'Em produção', 'cor': 'Correção', 'fin': 'Finalizados'} GROUPS = {'pay': 'Aguardando pagamento', 'prod': 'Em produção', 'cor': 'Correção', 'fin': 'Finalizados'}
ENTRIES = '''WITH live_quote AS ( ENTRIES = '''WITH live_quote AS (

View File

@@ -6,10 +6,12 @@ import httpx
from fastapi import APIRouter, HTTPException, Request, Response from fastapi import APIRouter, HTTPException, Request, Response
from ..core import db from ..core import db
from .. import mail
from ..core.auth import client_ip, owner, new_session, rate_limit from ..core.auth import client_ip, owner, new_session, rate_limit
from ..core.limits import upload_limit_bytes from ..core.limits import upload_limit_bytes
from ..core.models import FreightEstimate from ..core.pricing import manual_extra_cents
from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, freight, payment, from ..core.models import FreightAsk, FreightEstimate
from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, delivery_services, freight, payment,
require_delivery_available, storage) require_delivery_available, storage)
router = APIRouter() router = APIRouter()
@@ -38,10 +40,13 @@ def session(request: Request, response: Response):
session_id = new_session(c, response) session_id = new_session(c, response)
return {'environment': ENVIRONMENT, 'cart_scope': str(session_id), 'part_bytes': PART_BYTES, return {'environment': ENVIRONMENT, 'cart_scope': str(session_id), 'part_bytes': PART_BYTES,
'max_upload_bytes': upload_limit_bytes(), 'payment_provider': payment.name, '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(),
# Public by design: Mercado Pago's card form needs it in the browser. # 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 service the cart quotes, or none: pickup only. # The delivery options the cart quotes, or none: pickup only.
'freight_service': 'jadlog' if freight.name == 'jadlog' else 'mock-standard' if ENVIRONMENT == 'local' else None} 'freight_services': delivery_services()}
@router.post('/api/freight') @router.post('/api/freight')
def quote_freight(body: FreightEstimate): def quote_freight(body: FreightEstimate):
@@ -51,6 +56,19 @@ def quote_freight(body: FreightEstimate):
except ValueError as exc: except ValueError as exc:
raise HTTPException(422, str(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 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. # the browser, which keeps the Site's CSP to its own origin.
VIACEP = 'https://viacep.com.br/ws/{}/json/' VIACEP = 'https://viacep.com.br/ws/{}/json/'

File diff suppressed because it is too large Load Diff

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 # The charge happens inside the transaction that persists the order, so a
# failure to record it cannot leave a customer charged without an order. # failure to record it cannot leave a customer charged without an order.
receipt = payment.pay(str(body.quote_id), quote['approved']['total_cents']) 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 return order

View File

@@ -43,10 +43,14 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
row = upload_row(c, uid, session_id) row = upload_row(c, uid, session_id)
if not row['complete']: if not row['complete']:
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar antes de continuar.') 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) require_clean(row)
rows[str(uid)] = row rows[str(uid)] = row
# The grade sets the price and came from the browser: before a cart is # The grade came from the browser and is shown with the order (it no
# approved at checkout, the server works it out from the files. # longer sets the price): before a cart is approved at checkout, the
# server works it out from the files.
note = mismatch(Files(storage), draft['items'], rows) if reason is None else None note = mismatch(Files(storage), draft['items'], rows) if reason is None else None
reason = reason or note reason = reason or note
uid = uuid4() uid = uuid4()

View File

@@ -1,21 +1,24 @@
"""Kanban users and print machines, managed by the administrators. """Kanban users and print machines, managed by the administrators.
There is no e-mail yet, so an administrator creates each account with a An administrator creates each account with a first password and the person
first password and the person changes it in "Minha senha". The superadmin is changes it in "Minha senha". The superadmin is the system's own account, set from the console (python -m app.operators);
the system's own account, set from the console (python -m app.operators);
administrators manage everyone else. Nobody can remove, disable or demote administrators manage everyone else. Nobody can remove, disable or demote
themselves, so the last administrator cannot lock the team out by accident. themselves, so the last administrator cannot lock the team out by accident.
""" """
import re import re
from decimal import Decimal
from typing import Literal from typing import Literal
from uuid import UUID, uuid4 from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException, Request from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import Field, field_validator from pydantic import Field, field_validator
from .. import machines, mail
from ..core import db from ..core import db
from ..core.auth import CAPABILITIES, audit, can, password_hash, password_matches, signed_in from ..core.auth import (CAPABILITIES, MACHINE_QUESTION, audit, can, may_move, may_reorder, password_hash,
password_matches, signed_in)
from ..core.models import StrictModel from ..core.models import StrictModel
from ..runtime import BACK, STATES, TRANSITIONS
router = APIRouter() router = APIRouter()
@@ -23,9 +26,11 @@ class UserIn(StrictModel):
# The profiles an administrator may give; superadmin only comes from the console. # The profiles an administrator may give; superadmin only comes from the console.
name: str = Field(min_length=1, max_length=80) name: str = Field(min_length=1, max_length=80)
email: str = Field(min_length=3, max_length=254) email: str = Field(min_length=3, max_length=254)
role: Literal['admin', 'gestao', 'operador', 'vendedor'] role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro']
password: str | None = Field(default=None, min_length=12, max_length=128) password: str | None = Field(default=None, min_length=8, max_length=128)
active: bool = True 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) machines: list[UUID] = Field(default_factory=list, max_length=50)
@field_validator('email') @field_validator('email')
@@ -41,20 +46,72 @@ class MachineIn(StrictModel):
name: str = Field(min_length=1, max_length=60) name: str = Field(min_length=1, max_length=60)
products: list[Literal['textil', 'uv']] = Field(default_factory=list, max_length=2) products: list[Literal['textil', 'uv']] = Field(default_factory=list, max_length=2)
active: bool = True 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)
# 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 PasswordChange(StrictModel): class PasswordChange(StrictModel):
current: str = Field(min_length=1, max_length=128) current: str = Field(min_length=1, max_length=128)
new: str = Field(min_length=12, max_length=128) new: str = Field(min_length=8, max_length=128)
@router.get('/api/operator/me') @router.get('/api/operator/me')
def me(request: Request): def me(request: Request):
"""Who is signed in, and what the Kanban should offer them.""" """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) account = signed_in(request)
return {'email': account['email'], 'name': account['name'], 'role': account['role'], role = account['role']
'machines': account['machines'], moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(role, a, b)]
'can': sorted(cap for cap, roles in CAPABILITIES.items() if account['role'] in roles)} moves += [[a, b] for a, b in BACK.items() if may_move(role, a, b, back=True)]
return {'email': account['email'], 'name': account['name'], 'role': role,
# The machine this session is on, and whether to ask (item 12).
'machine': account['machine'], 'machine_question': MACHINE_QUESTION.get(role),
'machine_answered': account['machine_answered'],
'can': sorted(cap for cap, roles in CAPABILITIES.items() if role in roles),
'moves': moves, 'reorder': [state for state in STATES if may_reorder(role, state)]}
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.get(account['role'])
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') @router.post('/api/operator/me/password')
@@ -70,9 +127,11 @@ def change_password(body: PasswordChange, request: Request):
def user_rows(c): def user_rows(c):
"""Every account, with the machines its open sessions are on now (item 12)."""
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at, rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at,
COALESCE(array_agg(m.machine_id) FILTER (WHERE m.machine_id IS NOT NULL), '{}') AS machines COALESCE(array_agg(DISTINCT s.machine_id) FILTER (WHERE s.machine_id IS NOT NULL), '{}') AS machines
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_machines m ON m.operator_id=o.id 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() GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()
for row in rows: for row in rows:
row['machines'] = [str(m) for m in row['machines']] row['machines'] = [str(m) for m in row['machines']]
@@ -82,7 +141,7 @@ def user_rows(c):
@router.get('/api/operator/users') @router.get('/api/operator/users')
def list_users(user=Depends(can('users'))): def list_users(user=Depends(can('users'))):
with db.connect() as c: with db.connect() as c:
return {'users': user_rows(c), 'machines': machine_rows(c)} return {'users': user_rows(c), 'machines': machines.rows(c, with_operators=True)}
def target(c, uid, request): def target(c, uid, request):
@@ -95,20 +154,10 @@ def target(c, uid, request):
return row return row
def set_machines(c, uid, machines):
known = {str(r['id']) for r in c.execute('SELECT id FROM dtf_local.machines WHERE id=ANY(%s)',
([str(m) for m in machines],)).fetchall()}
if len(known) != len(set(map(str, machines))):
raise HTTPException(422, 'Uma das máquinas escolhidas não existe mais.')
c.execute('DELETE FROM dtf_local.operator_machines WHERE operator_id=%s', (uid,))
for machine in known:
c.execute('INSERT INTO dtf_local.operator_machines(operator_id,machine_id) VALUES(%s,%s)', (uid, machine))
@router.post('/api/operator/users') @router.post('/api/operator/users')
def create_user(body: UserIn, request: Request, user=Depends(can('users'))): def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
if not body.password: if not body.password:
raise HTTPException(422, 'Defina uma senha inicial com 12 caracteres ou mais.') raise HTTPException(422, 'Defina uma senha inicial com 8 caracteres ou mais.')
uid = uuid4() uid = uuid4()
with db.connect() as c: with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.operators WHERE email=%s', (body.email,)).fetchone(): if c.execute('SELECT 1 FROM dtf_local.operators WHERE email=%s', (body.email,)).fetchone():
@@ -116,7 +165,6 @@ def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active) c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active)
VALUES(%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password), VALUES(%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
body.role, body.active)) body.role, body.active))
set_machines(c, uid, body.machines)
audit('operator_created', operator=user, account=body.email, role=body.role) audit('operator_created', operator=user, account=body.email, role=body.role)
return {'id': str(uid)} return {'id': str(uid)}
@@ -142,7 +190,6 @@ def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('use
if not body.active or body.password: if not body.active or body.password:
# Disabled, or given a new password: whoever was signed in signs in again. # 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,)) c.execute('DELETE FROM dtf_local.operator_sessions WHERE username=%s', (body.email,))
set_machines(c, uid, body.machines)
audit('operator_updated', operator=user, account=body.email, role=role, active=body.active, audit('operator_updated', operator=user, account=body.email, role=role, active=body.active,
password_reset=bool(body.password)) password_reset=bool(body.password))
return {'ok': True} return {'ok': True}
@@ -161,17 +208,16 @@ def delete_user(uid: UUID, request: Request, user=Depends(can('users'))):
return {'ok': True} return {'ok': True}
def machine_rows(c): def release_sessions(c, mid):
rows = c.execute('SELECT id,name,products,active FROM dtf_local.machines ORDER BY active DESC, name').fetchall() """Whoever was on a machine switched off or deleted is asked again."""
for row in rows: c.execute('''UPDATE dtf_local.operator_sessions SET machine_id=NULL, machine_at=NULL, machine_answered=false
row['id'] = str(row['id']) WHERE machine_id=%s''', (mid,))
return rows
@router.get('/api/operator/machines') @router.get('/api/operator/machines')
def list_machines(user=Depends(can('view'))): def list_machines(user=Depends(can('view'))):
with db.connect() as c: with db.connect() as c:
return {'machines': machine_rows(c)} return {'machines': machines.rows(c, with_operators=True)}
@router.post('/api/operator/machines') @router.post('/api/operator/machines')
@@ -180,8 +226,9 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
with db.connect() as c: with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s)', (body.name.strip(),)).fetchone(): 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.') raise HTTPException(409, 'Já existe uma máquina com este nome.')
c.execute('INSERT INTO dtf_local.machines(id,name,products,active) VALUES(%s,%s,%s,%s)', c.execute('INSERT INTO dtf_local.machines(id,name,products,active,limit_metres) VALUES(%s,%s,%s,%s,%s)',
(mid, body.name.strip(), sorted(set(body.products)), body.active)) (mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres))
machines.route(c)
audit('machine_created', operator=user, machine=body.name) audit('machine_created', operator=user, machine=body.name)
return {'id': str(mid)} return {'id': str(mid)}
@@ -192,9 +239,13 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s', if c.execute('SELECT 1 FROM dtf_local.machines WHERE lower(name)=lower(%s) AND id<>%s',
(body.name.strip(), mid)).fetchone(): (body.name.strip(), mid)).fetchone():
raise HTTPException(409, 'Já existe uma máquina com este nome.') 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 WHERE id=%s RETURNING id', if not c.execute('''UPDATE dtf_local.machines SET name=%s,products=%s,active=%s,limit_metres=%s
(body.name.strip(), sorted(set(body.products)), body.active, mid)).fetchone(): WHERE id=%s RETURNING id''', (body.name.strip(), sorted(set(body.products)), body.active,
body.limit_metres, mid)).fetchone():
raise HTTPException(404, 'Máquina não encontrada.') raise HTTPException(404, 'Máquina não encontrada.')
if not body.active:
release_sessions(c, mid)
machines.route(c)
audit('machine_updated', operator=user, machine=body.name) audit('machine_updated', operator=user, machine=body.name)
return {'ok': True} return {'ok': True}
@@ -203,8 +254,22 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
def delete_machine(mid: UUID, user=Depends(can('users'))): def delete_machine(mid: UUID, user=Depends(can('users'))):
"""Its orders go back to the automatic choice; its operators lose it.""" """Its orders go back to the automatic choice; its operators lose it."""
with db.connect() as c: with db.connect() as c:
release_sessions(c, mid)
row = c.execute('DELETE FROM dtf_local.machines WHERE id=%s RETURNING name', (mid,)).fetchone() row = c.execute('DELETE FROM dtf_local.machines WHERE id=%s RETURNING name', (mid,)).fetchone()
if not row: if not row:
raise HTTPException(404, 'Máquina não encontrada.') raise HTTPException(404, 'Máquina não encontrada.')
machines.route(c)
audit('machine_deleted', operator=user, machine=row['name']) audit('machine_deleted', operator=user, machine=row['name'])
return {'ok': True} 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

@@ -50,8 +50,9 @@ def correction_owner(c, order, ref, kind):
def submit_files(c, order, body, identity, kind, actor): def submit_files(c, order, body, identity, kind, actor):
if order['version'] != body.version: if order['version'] != body.version:
raise HTTPException(409, 'O pedido mudou. Atualize a página e envie de novo.') raise HTTPException(409, 'O pedido mudou. Atualize a página e envie de novo.')
if kind == 'final' and order['state'] not in ('rec','tra','cor'): # Arte conferida is the print queue (2026-10-23): what is in it keeps its finals.
raise HTTPException(409, 'O arquivo final só pode mudar antes da fila de impressão.') 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': if kind == 'correction' and order['state'] != 'cor':
raise HTTPException(409, 'Este pedido não está esperando correção.') raise HTTPException(409, 'Este pedido não está esperando correção.')
if len({f.upload_id for f in body.files}) != len(body.files): if len({f.upload_id for f in body.files}) != len(body.files):
@@ -66,7 +67,18 @@ def submit_files(c, order, body, identity, kind, actor):
expiry = first + timedelta(days=30) expiry = first + timedelta(days=30)
if expiry <= datetime.now(timezone.utc): if expiry <= datetime.now(timezone.utc):
raise HTTPException(410, 'Os arquivos deste pedido expiraram (30 dias).') 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.')
for ref in body.files: for ref in body.files:
if ref.upload_id in kept:
continue
corrected = correction_owner(c, order, ref, kind) corrected = correction_owner(c, order, ref, kind)
upload = upload_row(c, ref.upload_id, corrected or generated_owner(c, order, ref, kind) or identity, lock=True) upload = upload_row(c, ref.upload_id, corrected or generated_owner(c, order, ref, kind) or identity, lock=True)
if not upload['complete']: if not upload['complete']:
@@ -83,6 +95,10 @@ def submit_files(c, order, body, identity, kind, actor):
else: else:
c.execute('UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind=%s', (order['id'],kind)) c.execute('UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind=%s', (order['id'],kind))
for ref in body.files: for ref in body.files:
if ref.upload_id in kept:
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)', 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)) (uuid4(),order['id'],ref.upload_id,ref.item_index,kind,body.note,actor))
# The order's window, whatever the upload's own hold was. # The order's window, whatever the upload's own hold was.

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

View File

@@ -46,6 +46,11 @@ def main():
c.execute(sql.SQL('GRANT USAGE ON SCHEMA dtf_local TO {}').format(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 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))) c.execute(sql.SQL('GRANT USAGE,SELECT ON ALL SEQUENCES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
# ops.launch_reset starts the order numbers again at #1 (setval), once
# the test orders are gone; nothing else may change a sequence.
numbers = c.execute("SELECT pg_get_serial_sequence('dtf_local.orders','number')").fetchone()[0]
c.execute(sql.SQL('GRANT UPDATE ON SEQUENCE {} TO {}').format(
sql.Identifier(*numbers.split('.', 1)), sql.Identifier(role)))
# Turn the configured credential into a real account so an existing # Turn the configured credential into a real account so an existing
# deployment keeps logging in exactly as before. Inserts only when that # deployment keeps logging in exactly as before. Inserts only when that
# email is absent, so a password changed with local.operators is never # email is absent, so a password changed with local.operators is never

View File

@@ -87,6 +87,8 @@ def company(cnpj, connect=None, transport=None):
if connect is None: if connect is None:
from .core.db import connect from .core.db import connect
cnpj = digits(cnpj) cnpj = digits(cnpj)
if len(cnpj) != 14: # a CPF: a person, not in the company registry
return None
with connect() as c: with connect() as c:
known = names(c, [cnpj]).get(cnpj) known = names(c, [cnpj]).get(cnpj)
if known: if known:

View File

@@ -115,16 +115,80 @@ def login_failed(email):
rate_limit('auth-account', email, 1_000_000) rate_limit('auth-account', email, 1_000_000)
# What each Kanban profile may do. "view" is reading; "produce" moves cards and # What each Kanban profile may do. "view" is reading; "produce" moves cards and
# handles artwork; "manage" covers quotes, cancellations, payments and the # handles artwork; "print" is the print room's side of it (the machine, the
# integrations; "users" is the Usuários page. # queue's order, its files and folder); "manage" covers quotes, cancellations
ROLES = ('superadmin', 'admin', 'gestao', 'operador', 'vendedor') # 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')
CAPABILITIES = { CAPABILITIES = {
'view': set(ROLES), 'view': set(ROLES),
'produce': {'superadmin', 'admin', 'gestao', 'operador'}, 'produce': {'superadmin', 'admin', 'gestao', 'designer', 'operador'},
'print': {'superadmin', 'admin', 'gestao', 'operador'},
'manage': {'superadmin', 'admin', 'gestao'}, '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'}, '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'},
# "Retirado" at the counter (Dropstar's third round, item 14): everyone
# but the seller, who only views (D-30). It includes everyone who produces,
# so an operator upload (artwork.py) takes it for its parts.
'deliver': {'superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor'},
} }
# 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 may_move(role, from_state, to_state, back=False):
"""Whether this profile may move a card; `back` is the step back that
undoes the move to_state -> from_state."""
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 role in MANAGERS or any(a == state and b != 'cor' for a, b in MOVES.get(role, ()))
def signed_in(request: Request): def signed_in(request: Request):
"""The operator behind this session, active, with the profile read now: a """The operator behind this session, active, with the profile read now: a
@@ -134,14 +198,17 @@ def signed_in(request: Request):
raise HTTPException(401, 'Entre no Kanban.') raise HTTPException(401, 'Entre no Kanban.')
digest = hashlib.sha256(token.encode()).hexdigest() digest = hashlib.sha256(token.encode()).hexdigest()
with connect() as c: with connect() as c:
row = c.execute('''SELECT o.id,o.email,o.name,o.role FROM dtf_local.operator_sessions s row = c.execute('''SELECT o.id,o.email,o.name,o.role,s.machine_answered,m.id AS machine_id,m.name AS machine_name
FROM dtf_local.operator_sessions s
JOIN dtf_local.operators o ON o.email=s.username AND o.active 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() WHERE s.token_hash=%s AND s.expires_at>now()''', (digest,)).fetchone()
if row:
row['machines'] = [str(r['machine_id']) for r in c.execute(
'SELECT machine_id FROM dtf_local.operator_machines WHERE operator_id=%s', (row['id'],)).fetchall()]
if not row: if not row:
raise HTTPException(401, 'Sua sessão expirou. Entre de novo.') 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 request.state.operator = row
return row return row

View File

@@ -10,4 +10,4 @@ def scan_limit_bytes():
def upload_limit_bytes(): def upload_limit_bytes():
return int(os.environ.get('MAX_UPLOAD_BYTES', '5368709120')) return int(os.environ.get('MAX_UPLOAD_BYTES', str(4 * 1024 ** 3)))

View File

@@ -7,22 +7,48 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
class StrictModel(BaseModel): class StrictModel(BaseModel):
model_config = ConfigDict(extra='forbid', allow_inf_nan=False) 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): 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 cnpj: str
zap: str zap: str
mail: str = Field(max_length=254) 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') @field_validator('cnpj')
@classmethod @classmethod
def cnpj_valid(cls, value): def document_valid(cls, value):
digits = re.sub(r'\D', '', value) digits = re.sub(r'\D', '', value)
if len(digits) != 14 or len(set(digits)) == 1 or not digits.isascii(): if not digits.isascii() or not (cpf_ok(digits) or cnpj_ok(digits)):
raise ValueError('Invalid CNPJ') raise ValueError('Invalid CPF or 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')
return digits return digits
@field_validator('zap') @field_validator('zap')
@@ -41,7 +67,7 @@ class Customer(StrictModel):
return value.strip() return value.strip()
class Freight(StrictModel): class Freight(StrictModel):
service: Literal['pickup','mock-standard','jadlog'] = 'pickup' service: Literal['pickup','mock-standard','jadlog','pac','sedex'] = 'pickup'
postal_code: str = Field(default='', max_length=8) postal_code: str = Field(default='', max_length=8)
class FreightEstimate(Freight): class FreightEstimate(Freight):
@@ -50,6 +76,12 @@ class FreightEstimate(Freight):
metres: Decimal | None = Field(default=None, gt=0, le=12000) metres: Decimal | None = Field(default=None, gt=0, le=12000)
declared_cents: int = Field(default=0, ge=0, le=100_000_000, strict=True) 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', 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'] 'PR','PE','PI','RJ','RN','RS','RO','RR','SC','SP','SE','TO']
@@ -105,8 +137,14 @@ class ProductionPlacement(StrictModel):
rotation_degrees: Literal[0, 90, 180, 270] rotation_degrees: Literal[0, 90, 180, 270]
mirrored: bool 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): class ProductionSpec(StrictModel):
version: Literal[2] version: Literal[2, 3]
film_width_cm: Decimal film_width_cm: Decimal
height_cm: Decimal = Field(gt=0, le=1200000) 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=20)
@@ -120,13 +158,17 @@ class Item(StrictModel):
production: ProductionSpec production: ProductionSpec
quality_status: Literal['ok', 'warning', 'unverified'] quality_status: Literal['ok', 'warning', 'unverified']
quality_acknowledged: bool 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)
@model_validator(mode='after') @model_validator(mode='after')
def production_matches_uploads(self): def production_matches_uploads(self):
if [source.upload_id for source in self.production.sources] != self.uploads: if [source.upload_id for source in self.production.sources] != self.uploads:
raise ValueError('Production sources must match uploaded files in order') raise ValueError('Production sources must match uploaded files in order')
is_sheet = self.mode in ('file', 'uvfile') is_sheet = self.mode in ('file', 'uvfile')
film_width = Decimal('28.5') if self.mode in ('uvfile', 'uv') else Decimal('57') # 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: if self.production.film_width_cm != film_width:
raise ValueError('Production film width does not match the product') raise ValueError('Production film width does not match the product')
for source in self.production.sources: for source in self.production.sources:
@@ -134,6 +176,9 @@ class Item(StrictModel):
raise ValueError('Production source does not fit the selected product') raise ValueError('Production source does not fit the selected product')
if is_sheet and (source.rotation_degrees or source.mirrored): if is_sheet and (source.rotation_degrees or source.mirrored):
raise ValueError('Finished sheets cannot be rotated or mirrored by the layout') raise ValueError('Finished sheets cannot be rotated or mirrored by the layout')
# 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) expected={(index,copy) for index,source in enumerate(self.production.sources)
for copy in range(source.copies)} for copy in range(source.copies)}
placed=set() placed=set()
@@ -166,6 +211,8 @@ class QuoteRequest(StrictModel):
items: list[Item] = Field(min_length=1, max_length=30) items: list[Item] = Field(min_length=1, max_length=30)
freight: Freight freight: Freight
destination: Destination | None = None destination: Destination | None = None
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
proof: bool = False
@model_validator(mode='after') @model_validator(mode='after')
def destination_matches_freight(self): def destination_matches_freight(self):
@@ -214,7 +261,7 @@ class PaymentIntent(StrictModel):
method: PaymentMethod method: PaymentMethod
class Move(StrictModel): class Move(StrictModel):
state: Literal['rec','tra','fil','imp','cor','fin'] state: Literal['rec','tra','imp','cor','rev','fin']
version: int = Field(ge=0) version: int = Field(ge=0)
reason: str = Field(default='', max_length=1000) reason: str = Field(default='', max_length=1000)
@@ -223,12 +270,18 @@ class Resolution(StrictModel):
class Register(StrictModel): class Register(StrictModel):
customer: Customer customer: Customer
password: str = Field(min_length=12, max_length=128) password: str = Field(min_length=8, max_length=128)
class ProfileUpdate(StrictModel): class ProfileUpdate(StrictModel):
"""What a customer may change about their account; the CNPJ is not among it.""" """What a customer may change about their account; the CPF/CNPJ is not among it."""
zap: str zap: str
address: Destination | None = None 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') @field_validator('zap')
@classmethod @classmethod
@@ -252,7 +305,28 @@ class EmailChange(StrictModel):
class PasswordChange(StrictModel): class PasswordChange(StrictModel):
current: str = Field(min_length=1, max_length=128) current: str = Field(min_length=1, max_length=128)
new: str = Field(min_length=12, 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): class Login(StrictModel):
email: str = Field(min_length=3, max_length=254) email: str = Field(min_length=3, max_length=254)

View File

@@ -1,27 +1,52 @@
"""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. One price per product (Dropstar, 2026-10-23). The grade is still recorded with
This module does not inspect artwork or perform pre-flight. 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 from decimal import Decimal, ROUND_CEILING
TIERS = { PRICES = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990}
'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)],
}
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 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) -> dict:
"""The item's charge. The grade is validated and kept with the item; the
price does not depend on it."""
length = Decimal(str(metres)) 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') raise ValueError('Invalid product or length')
if isinstance(grade, bool) or not isinstance(grade, int) or not 0 <= grade <= 100: if isinstance(grade, bool) or not isinstance(grade, int) or not 0 <= grade <= 100:
raise ValueError('Grade must be an integer between 0 and 100') raise ValueError('Grade must be an integer between 0 and 100')
billed = max(Decimal('1'), (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10) 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) if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
return {'mode': mode, 'metres': str(length), 'grade': grade, raise ValueError('Invalid extra charge')
'billed_metres': str(billed), 'unit_cents': unit, unit = PRICES[mode] + extra_cents
'total_cents': int(billed * unit), priced = {'mode': mode, 'metres': str(length), 'grade': grade,
'discount_cents': int(billed * (TIERS[mode][-1][1] - unit))} 'billed_metres': str(billed), 'unit_cents': unit,
'total_cents': int(billed * unit)}
if extra_cents:
priced['manual_extra_cents'] = extra_cents
return priced

View File

@@ -27,7 +27,8 @@ SECRET_FILE_SETTINGS = (
'PAYMENT_TOKEN', 'PAYMENT_TOKEN',
'PAYMENT_WEBHOOK_SECRET', 'PAYMENT_WEBHOOK_SECRET',
'TINY_TOKEN', 'TINY_TOKEN',
'WHATSAPP_TOKEN', 'SMTP_PASSWORD',
'CORREIOS_CODIGO_ACESSO',
) )
SUFFIX = '_FILE' 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())

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}

View File

@@ -1,9 +1,11 @@
"""The grade (the resolution discount) recomputed from the uploaded files. """The grade recomputed from the uploaded files.
The Site grades the art in the customer's browser and sends the grade with the The Site grades the art in the customer's browser and sends the grade with the
cart, and the price depends on it. A customer who edits the page could claim a cart. The price no longer depends on it (one price per product, 2026-10-23),
better grade, so before a cart is approved at checkout the server reads the but the grade is shown with the order on the Kanban and in Tiny. A customer
files it already has and works the grade out again, by the Site's own rules: 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 - 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); item's grade comes from the worst sheet (web/site-quality.js);
@@ -180,7 +182,7 @@ def mismatch(files, items, rows):
"""Why a cart's grades cannot be approved at checkout, or None.""" """Why a cart's grades cannot be approved at checkout, or None."""
for item in items: for item in items:
if item['grade'] == 0: if item['grade'] == 0:
continue # full price: nothing to verify continue # no grade claimed: nothing to verify
verified = item_grade(files, item, rows) verified = item_grade(files, item, rows)
if verified is None: if verified is None:
return 'Nota não conferida no servidor' return 'Nota não conferida no servidor'

View File

@@ -7,38 +7,19 @@ 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), 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 home delivery. Jadlog prices by weight in kg and expects the larger of the
real and the cubed weight. The package weight comes from the client (a base real and the cubed weight, both from the order's package (app/package.py).
plus a weight per billed metre) and has no default: FREIGHT_ADAPTER=jadlog
refuses to start without it, so a guessed weight never prices a customer's
freight. The cubed weight is the box's volume times the contract's factor
(JADLOG_CAIXA_CM, JADLOG_CUBAGEM_KG_M3); set both or neither, and with neither
only the real weight is sent. A box holds JADLOG_METROS_POR_CAIXA metres of
film; a longer order ships in as many boxes as it needs, each with its own
packaging weight and volume.
""" """
import math
import os import os
import re
from decimal import ROUND_HALF_UP, Decimal from decimal import ROUND_HALF_UP, Decimal
import httpx import httpx
from .package import WEIGHT_SETTINGS, Package
QUOTE_URL = 'https://www.jadlog.com.br/embarcador/api/frete/valor' QUOTE_URL = 'https://www.jadlog.com.br/embarcador/api/frete/valor'
PACKAGE = 3 PACKAGE = 3
ORIGIN = '14402310' ORIGIN = '14402310'
SERVICE = 'jadlog' SERVICE = 'jadlog'
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 JadlogError(Exception): class JadlogError(Exception):
pass pass
@@ -99,53 +80,14 @@ def required_settings():
return ('JADLOG_TOKEN', 'JADLOG_CNPJ') + WEIGHT_SETTINGS return ('JADLOG_TOKEN', 'JADLOG_CNPJ') + WEIGHT_SETTINGS
class JadlogFreight: class JadlogFreight(Package):
"""The Site's delivery option: Jadlog's price for the order's package.""" """The Site's Jadlog option: Jadlog's price for the order's package."""
name = 'jadlog' name = 'jadlog'
services = {SERVICE: 'Jadlog'}
def __init__(self, quotes=None): def __init__(self, quotes=None):
super().__init__()
self.quotes = quotes or JadlogQuotes() self.quotes = quotes or JadlogQuotes()
self.base_kg = Decimal(os.environ['JADLOG_PESO_BASE_KG'])
self.per_metre_kg = Decimal(os.environ['JADLOG_PESO_POR_METRO_KG'])
# Jadlog'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('Jadlog 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 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 quote(self, service, postal_code, metres=None, declared_cents=0): def quote(self, service, postal_code, metres=None, declared_cents=0):
if service == 'pickup': if service == 'pickup':
@@ -164,4 +106,4 @@ class JadlogFreight:
'total_cents': result['total_cents'], 'weight_kg': str(weight), 'real_kg': str(real), 'total_cents': result['total_cents'], 'weight_kg': str(weight), 'real_kg': str(real),
'boxes': self.boxes(metres), 'boxes': self.boxes(metres),
'days': None if days is None else int(days) + self.production_days, 'days': None if days is None else int(days) + self.production_days,
'description': 'Jadlog .PACKAGE'} 'description': self.services[SERVICE]}

137
app/machines.py Normal file
View File

@@ -0,0 +1,137 @@
"""The print machines: which one each order goes to, and how loaded each is.
An order gets its machine once, and keeps it: someone's choice in the order
panel, or else the active machine that prints its product with the fewest
metres still open, among those below their limit (or, all of them full, the
least loaded anyway; the machine then shows it is over its limit). A machine
switched off, deleted or no longer printing the product gives its automatic
orders back to that choice, unless they are already printing.
"""
from decimal import Decimal
# Not finished: the work still ahead of a machine.
OPEN = ('rec', 'tra', 'imp', 'cor')
# Stages an automatic order may still move from: not once it is printing.
MOVABLE = ('rec', 'tra', 'cor')
# One routing at a time, so two at once cannot both pick the same "least loaded".
LOCK = 7_041_901
# Two orders at most in Imprimindo per machine (Dropstar, 2026-10-29): one
# printing, the next being ripped by FlexiPRINT meanwhile. A third would
# make the RIP choke; two mean the next sheet is ready when one ends.
PRINTING_CAP = 2
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 pick(machines, load, order):
"""The machine for one order, or None when none prints its product."""
family, metres = product_family(order), order_metres(order)
able = [m for m in machines if m['active'] and family in m['products']]
if not able:
return None
used = lambda m: load.get(str(m['id']), Decimal(0))
room = [m for m in able if m['limit_metres'] is None or used(m) + metres <= m['limit_metres']]
# min() keeps the first of equals: the machine registered first.
return min(room or able, key=used)
def route(c):
"""Give every open order without a machine its automatic one."""
# A choice whose machine was deleted is no choice any more.
c.execute('UPDATE dtf_local.orders SET machine_chosen=false WHERE machine_id IS NULL AND machine_chosen')
# Automatic orders on a machine that can no longer take them, before printing.
c.execute('''UPDATE dtf_local.orders o SET machine_id=NULL FROM dtf_local.machines m
WHERE o.machine_id=m.id AND NOT o.machine_chosen AND o.state=ANY(%s) AND o.cancelled_at IS NULL
AND (NOT m.active OR NOT ((CASE WHEN o.snapshot->'items'->0->>'mode' IN ('uv','uvfile')
THEN 'uv' ELSE 'textil' END)=ANY(m.products)))''', (list(MOVABLE),))
waiting = c.execute('''SELECT id, snapshot FROM dtf_local.orders
WHERE machine_id IS NULL AND cancelled_at IS NULL AND state=ANY(%s)
ORDER BY created_at, number''', (list(OPEN),)).fetchall()
if not waiting:
return 0
c.execute('SELECT pg_advisory_xact_lock(%s)', (LOCK,))
machines = c.execute('''SELECT id, products, active, limit_metres FROM dtf_local.machines
ORDER BY created_at, name''').fetchall()
load = {k: v['metres'] for k, v in loads(c).items()}
routed = 0
for order in waiting:
machine = pick(machines, load, order)
if machine is None:
continue
if c.execute('''UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=false
WHERE id=%s AND machine_id IS NULL RETURNING id''', (machine['id'], order['id'])).fetchone():
key = str(machine['id'])
load[key] = load.get(key, Decimal(0)) + order_metres(order)
routed += 1
return routed
def rows(c, with_operators=False):
"""Every machine with its load, for the Kanban."""
machines = c.execute('''SELECT id, name, products, active, limit_metres FROM dtf_local.machines
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,
'open_metres': float(used['metres']), 'open_orders': used['orders'], 'states': used['states']}
if with_operators:
row['operators'] = operators.get(key, [])
result.append(row)
return result
def full(c, machine_id, order_id):
"""The machine's name when it already has PRINTING_CAP other orders in
Imprimindo, so this one cannot join them; None when it has room. The
machine's row is locked, so two pulls at once cannot both take the last
place."""
if machine_id is None:
return None
machine = c.execute('SELECT name FROM dtf_local.machines WHERE id=%s FOR UPDATE', (machine_id,)).fetchone()
printing = c.execute('''SELECT count(*) AS n FROM dtf_local.orders WHERE machine_id=%s AND state='imp'
AND cancelled_at IS NULL AND id<>%s''', (machine_id, order_id)).fetchone()['n']
return machine['name'] if machine and printing >= PRINTING_CAP else None
def printing_slots(c):
"""Per order in Imprimindo: 'imprimindo' for the first to enter it on its
machine (ripped, running), 'ripando' for the one after it."""
return {row['id']: 'imprimindo' if row['place'] == 1 else 'ripando' for row in c.execute('''
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()}

185
app/mail.py Normal file
View File

@@ -0,0 +1,185 @@
"""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
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'))} · "
f"{str(i.get('billed_metres') or i.get('metres')).replace('.', ',')} m"
for i in snapshot.get('items', []))),
('Entrega', delivery),
('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'}
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

@@ -77,7 +77,8 @@ class MercadoPagoPayment:
'description': f'DTF - cotação {quote_id[:8]}', 'description': f'DTF - cotação {quote_id[:8]}',
'external_reference': quote_id, 'external_reference': quote_id,
'payer': {'email': customer['mail'], 'payer': {'email': customer['mail'],
'identification': {'type': 'CNPJ', 'number': customer['cnpj']}}} 'identification': {'type': 'CPF' if len(customer['cnpj']) == 11 else 'CNPJ',
'number': customer['cnpj']}}}
if self.notification_url: if self.notification_url:
body['notification_url'] = self.notification_url body['notification_url'] = self.notification_url
expires_at = None expires_at = None

View File

@@ -28,7 +28,7 @@ from uuid import uuid4
from .core.auth import ROLES, password_hash from .core.auth import ROLES, password_hash
from .core.db import connect from .core.db import connect
MIN_PASSWORD = 12 MIN_PASSWORD = 8
def seed_from_environment(cursor): def seed_from_environment(cursor):

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}

View File

@@ -16,9 +16,11 @@ from uuid import UUID, uuid4
from psycopg.types.json import Jsonb from psycopg.types.json import Jsonb
from . import machines, mail, proof
from .core.auth import audit from .core.auth import audit
from .core.models import PRODUCTION_VERSIONS
from .printjobs import queue as queue_print_files 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 from .scanning import require_clean
QUOTE_VALID_HOURS = 24 QUOTE_VALID_HOURS = 24
@@ -38,7 +40,7 @@ def approved_quote(c, quote_id, owner=None):
raise PaymentRefused('quote was never reviewed') raise PaymentRefused('quote was never reviewed')
if row.get('discarded_at'): if row.get('discarded_at'):
raise PaymentRefused('quote was discarded') raise PaymentRefused('quote was discarded')
if any(item.get('production', {}).get('version') != 2 for item in row['approved']['items']): if any(item.get('production', {}).get('version') not in PRODUCTION_VERSIONS for item in row['approved']['items']):
raise PaymentRefused('quote uses an obsolete production layout; request a new quote') raise PaymentRefused('quote uses an obsolete production layout; request a new quote')
if row['approved_at'] < datetime.now(timezone.utc) - timedelta(hours=QUOTE_VALID_HOURS): if row['approved_at'] < datetime.now(timezone.utc) - timedelta(hours=QUOTE_VALID_HOURS):
raise PaymentRefused('quote expired before payment') raise PaymentRefused('quote expired before payment')
@@ -53,6 +55,19 @@ def is_test(order):
return (order.get('payment') or {}).get('provider') == TEST_PROVIDER 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')
def in_tiny(order):
"""Whether the order goes to Tiny: every order but a test. A Dropflow
order goes in its own revenue category (app/tiny.py, CATEGORIES)."""
return not is_test(order)
# How long a file is kept while nothing has been paid for it. A cart's files # How long a file is kept while nothing has been paid for it. A cart's files
# are uploaded before payment, so the price and the security check are done on # are uploaded before payment, so the price and the security check are done on
# the file itself; a cart that is never paid must not keep them for 30 days. # the file itself; a cart that is never paid must not keep them for 30 days.
@@ -73,8 +88,9 @@ def hold_uploads(c, upload_ids, interval):
WHERE id=ANY(%s) AND purged_at IS NULL''', (interval, [str(u) for u in upload_ids])) WHERE id=ANY(%s) AND purged_at IS NULL''', (interval, [str(u) for u in upload_ids]))
def create_order(c, quote, payment): def create_order(c, quote, payment, origin):
"""Create the order for a reviewed quote, or return the one already there. """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; Returns (order, created). The caller decides what to do about a duplicate;
the important part is that asking twice cannot produce two orders, because the important part is that asking twice cannot produce two orders, because
@@ -90,18 +106,34 @@ def create_order(c, quote, payment):
require_clean(upload_row(c, UUID(upload_id), quote['owner'])) require_clean(upload_row(c, UUID(upload_id), quote['owner']))
order = c.execute( order = c.execute(
'INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s) RETURNING *', '''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
(uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment))).fetchone() 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. # 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) 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))) WHERE id=ANY(%s) AND purged_at IS NULL''', (ORDER_RETENTION, quote_uploads(approved)))
queue_print_files(c, order['id'], len(approved['items'])) queue_print_files(c, order['id'], len(approved['items']))
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'],))
machines.route(c)
if is_test(order): if is_test(order):
return order, True return order, True
for provider in ('tiny', 'whatsapp'): mail.order_paid(c, order, PUBLIC_ORIGIN)
enqueue(c, f"{order['id']}:paid:{provider}", provider, if not in_tiny(order):
{'order_id': str(order['id']), 'number': order['number'], return order, True
'event': 'payment_approved', 'order': approved}) # 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 return order, True
@@ -158,7 +190,7 @@ def apply(c, event):
expected_cents=expected, paid_cents=event.amount_cents) expected_cents=expected, paid_cents=event.amount_cents)
return f'refused: paid {event.amount_cents} but quote total is {expected}' return f'refused: paid {event.amount_cents} but quote total is {expected}'
order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw}) 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)') return f"order {order['number']}" + ('' if created else ' (already existed)')

View File

@@ -26,10 +26,23 @@ from decimal import Decimal
from PIL import Image, ImageOps from PIL import Image, ImageOps
from .core.models import PRODUCTION_VERSIONS
PT_PER_CM = 72 / 2.54 PT_PER_CM = 72 / 2.54
# Acrobat's page limit. Longer layouts scale user space with /UserUnit (PDF 1.6) # Acrobat's page limit, 200 inches (5,08 m). A longer sheet is written at its
# rather than cutting the film into pages a RIP might print with gaps. # 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 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 # 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. # is refused: rounding in the Site keeps real files well inside this.
ASPECT_TOLERANCE = 0.01 ASPECT_TOLERANCE = 0.01
@@ -394,10 +407,78 @@ def check_layout(item, sizes, vector=()):
return lowest 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. """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. 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 Raster sources are written by the streaming writer above. PDF sources are
@@ -405,7 +486,7 @@ def render(item, files, out, title):
exported as PDF keeps its vectors, fonts and transparency. exported as PDF keeps its vectors, fonts and transparency.
""" """
production = item['production'] production = item['production']
if production.get('version') != 2: if production.get('version') not in PRODUCTION_VERSIONS:
raise Unsupported('o item usa uma montagem antiga') raise Unsupported('o item usa uma montagem antiga')
sources = [] sources = []
try: try:
@@ -416,12 +497,13 @@ def render(item, files, out, title):
lowest_dpi = check_layout(item, [source.size for source in sources], vector) lowest_dpi = check_layout(item, [source.size for source in sources], vector)
width_pt = float(production['film_width_cm']) * PT_PER_CM width_pt = float(production['film_width_cm']) * PT_PER_CM
height_pt = float(production['height_cm']) * PT_PER_CM page_cm = Decimal(str(production['height_cm'])) + (FOOTER_CM if footer else 0)
unit = max(1, math.ceil(max(width_pt, height_pt) / MAX_PAGE_PT)) height_pt = float(page_cm) * PT_PER_CM
unit = page_unit(width_pt, height_pt)
first = tempfile.TemporaryFile() if vector else out first = tempfile.TemporaryFile() if vector else out
try: 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: if vector:
first.seek(0) first.seek(0)
add_vector_pages(production, sources, first, out, height_pt) add_vector_pages(production, sources, first, out, height_pt)
@@ -433,6 +515,8 @@ def render(item, files, out, title):
source.close() source.close()
return {'film_width_cm': str(production['film_width_cm']), return {'film_width_cm': str(production['film_width_cm']),
'height_cm': str(production['height_cm']), 'height_cm': str(production['height_cm']),
'page_height_cm': str(page_cm),
'footer': footer,
'billed_metres': str(item['billed_metres']), 'billed_metres': str(item['billed_metres']),
'placements': len(production['placements']), 'placements': len(production['placements']),
'sources': len(sources), 'sources': len(sources),
@@ -441,7 +525,7 @@ def render(item, files, out, title):
'user_unit': unit} '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) pdf = PdfWriter(out)
images = {index: source.embed(pdf) for index, source in enumerate(sources) images = {index: source.embed(pdf) for index, source in enumerate(sources)
if isinstance(source, SourceImage)} if isinstance(source, SourceImage)}
@@ -454,12 +538,20 @@ def write_rasters(production, sources, out, title, width_pt, height_pt, unit):
matrix = placement_matrix(placement, height_pt) matrix = placement_matrix(placement, height_pt)
commands.append(b'q ' + b' '.join(serialize(v) for v in matrix) + commands.append(b'q ' + b' '.join(serialize(v) for v in matrix) +
b' cm /Im%d Do Q\n' % placement['source_index']) 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)) content = pdf.stream({'Filter': Name('FlateDecode')}, deflate(commands))
pages = pdf.alloc() pages = pdf.alloc()
page_box = [0, 0, width_pt / unit, height_pt / unit] page_box = [0, 0, width_pt / unit, height_pt / unit]
page = {'Type': Name('Page'), 'Parent': pages, 'MediaBox': page_box, 'TrimBox': page_box, page = {'Type': Name('Page'), 'Parent': pages, 'MediaBox': page_box, 'TrimBox': page_box,
'Resources': {'XObject': {f'Im{index}': ref for index, ref in images.items()}}, 'Resources': resources, 'Contents': content}
'Contents': content}
if unit > 1: if unit > 1:
page['UserUnit'] = unit page['UserUnit'] = unit
page_ref = pdf.obj(page) page_ref = pdf.obj(page)

View File

@@ -21,6 +21,8 @@ import os
import tempfile import tempfile
import time import time
from datetime import timedelta from datetime import timedelta
from decimal import Decimal
from zoneinfo import ZoneInfo
from uuid import NAMESPACE_URL, UUID, uuid4, uuid5 from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
from psycopg.types.json import Jsonb from psycopg.types.json import Jsonb
@@ -28,6 +30,9 @@ from psycopg.types.json import Jsonb
from .core.auth import audit from .core.auth import audit
from .core.db import connect from .core.db import connect
from .printfile import Unsupported, render from .printfile import Unsupported, render
from .tiny import purchase_order
LOCAL = ZoneInfo('America/Sao_Paulo')
CLAIM_TIMEOUT = timedelta(minutes=15) CLAIM_TIMEOUT = timedelta(minutes=15)
MAX_ATTEMPTS = 3 MAX_ATTEMPTS = 3
@@ -55,7 +60,7 @@ def queue(c, order_id, items, only_missing=False):
def claim(c): 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.created_at AS ordered_at FROM dtf_local.print_files p
JOIN dtf_local.orders o ON o.id=p.order_id JOIN dtf_local.orders o ON o.id=p.order_id
WHERE p.status='pending' OR (p.status='rendering' AND p.claimed_at < now()-%s) WHERE p.status='pending' OR (p.status='rendering' AND p.claimed_at < now()-%s)
ORDER BY p.created_at FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone() ORDER BY p.created_at FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
@@ -137,6 +142,29 @@ def whole_sheet(item, uploads):
return row return row
def file_prefix(number, item_index):
"""How an order's files are named: DTF-23-item-1, the code the Kanban
copies, the footer prints and Tiny keeps (Dropstar, 2026-10-23)."""
return f'DTF-{number}-item-{item_index + 1}'
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('.', ',')
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 produce(storage, job, item, uploads): 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 (pdf path, name, size, evidence)."""
for upload_id in item['uploads']: for upload_id in item['uploads']:
@@ -146,7 +174,7 @@ def produce(storage, job, item, uploads):
if row['purged_at'] or row['expired']: if row['purged_at'] or row['expired']:
raise Unsupported('um arquivo original passou do prazo de guarda') raise Unsupported('um arquivo original passou do prazo de guarda')
number = job['number'] number = job['number']
name = f'pedido-{number}-item-{job["item_index"] + 1}.pdf' name = f'{file_prefix(number, job["item_index"])}.pdf'
with tempfile.TemporaryDirectory(prefix='print-') as scratch: with tempfile.TemporaryDirectory(prefix='print-') as scratch:
files = {} files = {}
for index, upload_id in enumerate(item['uploads']): for index, upload_id in enumerate(item['uploads']):
@@ -156,7 +184,8 @@ def produce(storage, job, item, uploads):
handle, output = tempfile.mkstemp(prefix='print-', suffix='.pdf') handle, output = tempfile.mkstemp(prefix='print-', suffix='.pdf')
try: try:
with os.fdopen(handle, 'wb') as out: with os.fdopen(handle, 'wb') as out:
detail = render(item, files, out, f'Pedido {number} - item {job["item_index"] + 1}') detail = render(item, files, out, f'Pedido {number} - item {job["item_index"] + 1}',
footer=footer(job, item))
except BaseException: except BaseException:
os.unlink(output) os.unlink(output)
raise raise

26
app/proof.py Normal file
View File

@@ -0,0 +1,26 @@
"""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 rule (2026-10-23): up to 30 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
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

View File

@@ -1,16 +1,17 @@
"""Quote approval: automatic at checkout, by an operator for the exceptions. """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 ladders, 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 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 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 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). person must look at before charging wait for the Kanban (review_reason).
The grade (and so the discount) is worked out in the customer's browser and Each product has one price (Dropstar, 2026-10-23): the grade no longer changes
checked against the files before an automatic approval (app/grade_check.py); what is charged. It is still worked out in the customer's browser and shown
a grade the files do not support waits for review. The layout is still the with the order, so it is checked against the files before an automatic
browser's (roadmap 3.9): the API checks its geometry. Operators see every approval (app/grade_check.py); a grade the files do not support waits for
order's grade and artwork at Arte recebida. 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 import os
from decimal import Decimal from decimal import Decimal
@@ -19,7 +20,9 @@ from fastapi import HTTPException
from psycopg.types.json import Jsonb from psycopg.types.json import Jsonb
from . import payments from . import payments
from .core.pricing import price from .proof import PROOF_ABOVE_METRES
from .core.models import PRODUCTION_VERSIONS
from .core.pricing import is_manual, manual_extra_cents, price
from .runtime import freight, upload_row from .runtime import freight, upload_row
from .scanning import require_clean from .scanning import require_clean
@@ -42,12 +45,8 @@ def review_reason(draft):
if total > max_auto_metres(): if total > max_auto_metres():
return f'Pedido acima de {max_auto_metres():g} m' return f'Pedido acima de {max_auto_metres():g} m'
for item in draft['items']: for item in draft['items']:
if item.get('production', {}).get('version') != 2: if item.get('production', {}).get('version') not in PRODUCTION_VERSIONS:
return 'Montagem antiga' return 'Montagem antiga'
# The Site grades only the art it could analyse; anything else is
# priced at the full rate. A discount on it did not come from the Site.
if item['quality_status'] == 'unverified' and item['grade'] != 0:
return 'Nota informada sem análise da arte'
return None return None
@@ -57,7 +56,7 @@ def approve(c, row, items, reviewer):
draft = row['draft'] draft = row['draft']
if row['approved']: if row['approved']:
raise HTTPException(409, 'Esta cotação já foi aprovada e não pode mudar.') raise HTTPException(409, 'Esta cotação já foi aprovada e não pode mudar.')
if any(item.get('production', {}).get('version') != 2 for item in draft['items']): 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.') raise HTTPException(409, 'A cotação usa uma montagem antiga: o cliente precisa montar o pedido de novo.')
if len(items) != len(draft['items']): if len(items) != len(draft['items']):
raise HTTPException(422, 'Confira todos os itens da cotação.') raise HTTPException(422, 'Confira todos os itens da cotação.')
@@ -65,14 +64,19 @@ def approve(c, row, items, reviewer):
for item, original in zip(items, draft['items']): for item, original in zip(items, draft['items']):
if item.mode != original['mode'] or list(map(str, item.uploads)) != original['uploads']: 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.') 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']: 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):
raise HTTPException(422, 'A montagem e a confirmação do cliente não podem mudar na revisão.') raise HTTPException(422, 'A montagem e a confirmação do cliente não podem mudar na revisão.')
names = {}
for upload_id in item.uploads: for upload_id in item.uploads:
require_clean(upload_row(c, upload_id, row['owner'])) upload = upload_row(c, upload_id, row['owner'])
priced.append({**price(item.mode, str(item.metres), item.grade), require_clean(upload)
names[str(upload_id)] = upload['name']
extra = manual_extra_cents() if is_manual(original, names) else 0
priced.append({**price(item.mode, str(item.metres), item.grade, extra),
'uploads': original['uploads'], 'production': original['production'], 'uploads': original['uploads'], 'production': original['production'],
'quality_status': original['quality_status'], 'quality_status': original['quality_status'],
'quality_acknowledged': original['quality_acknowledged']}) 'quality_acknowledged': original['quality_acknowledged'],
'residue_accepted': original.get('residue_accepted', 0)})
metres = sum(Decimal(i['billed_metres']) for i in priced) metres = sum(Decimal(i['billed_metres']) for i in priced)
try: try:
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''), quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
@@ -81,6 +85,8 @@ def approve(c, row, items, reviewer):
raise HTTPException(422, str(exc)) raise HTTPException(422, str(exc))
approved = {'customer': draft['customer'], 'items': priced, 'freight': quoted_freight, approved = {'customer': draft['customer'], 'items': priced, 'freight': quoted_freight,
'destination': draft.get('destination'), '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 {}),
'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents']} 'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents']}
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s', c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
(Jsonb(approved), reviewer, row['id'])) (Jsonb(approved), reviewer, row['id']))

137
app/receipt.py Normal file
View File

@@ -0,0 +1,137 @@
"""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 .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'}
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'))} — {metres} m", 9.5)]
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'

View File

@@ -13,6 +13,7 @@ from fastapi import HTTPException
from psycopg.types.json import Jsonb from psycopg.types.json import Jsonb
from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime
from .freight import FreightOptions
from .core.secrets import load as load_secret_files from .core.secrets import load as load_secret_files
# Secret files must resolve before any configuration below is read. # Secret files must resolve before any configuration below is read.
@@ -25,11 +26,15 @@ if os.environ.get('PAYMENT_ADAPTER') == 'mercadopago':
payment = MercadoPagoPayment() payment = MercadoPagoPayment()
else: else:
payment = FakePayment() payment = FakePayment()
# Every carrier configured; the simulated one only where there is none.
_carriers = []
if os.environ.get('FREIGHT_ADAPTER') == 'jadlog': if os.environ.get('FREIGHT_ADAPTER') == 'jadlog':
from .jadlog import JadlogFreight from .jadlog import JadlogFreight
freight = JadlogFreight() _carriers.append(JadlogFreight())
else: from . import correios as _correios
freight = FakeFreight() if _correios.configured():
_carriers.append(_correios.CorreiosFreight())
freight = FreightOptions(_carriers or [FakeFreight()])
ENVIRONMENT = os.environ.get('APP_ENV', 'local') ENVIRONMENT = os.environ.get('APP_ENV', 'local')
PUBLIC_ORIGIN = os.environ.get('PUBLIC_ORIGIN', 'http://localhost') 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] ALLOWED_HOSTS = [host for host in os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',') if host]
@@ -46,19 +51,37 @@ BOARD_QUOTE_LIMIT = int(os.environ.get('BOARD_QUOTE_LIMIT', '100'))
PART_BYTES = int(os.environ.get('UPLOAD_PART_BYTES', '8388608')) PART_BYTES = int(os.environ.get('UPLOAD_PART_BYTES', '8388608'))
if not 5242880 <= PART_BYTES <= 67108864: if not 5242880 <= PART_BYTES <= 67108864:
raise RuntimeError('UPLOAD_PART_BYTES must be between 5 and 64 MiB') raise RuntimeError('UPLOAD_PART_BYTES must be between 5 and 64 MiB')
STATES = {'rec': 'Arte recebida', 'tra': 'Arte tratada', 'fil': 'Fila de impressão', # Dropstar's flow of 2026-10-23: Arte conferida is the print queue (Fila de
'imp': 'Imprimindo', 'cor': 'Correção', 'fin': 'Finalizado'} # impressão, 'fil', left the board), and Revisão checks the printed sheet
TRANSITIONS = {'rec': ['tra','cor'], 'tra': ['fil','cor'], 'fil': ['imp','cor'], # before Finalizado. After a correction the new art goes back through Arte
'imp': ['fin','cor'], 'cor': ['rec','tra'], 'fin': []} # 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 # 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. # is not a correction: the customer is not told and approved finals stay.
BACK = {'tra': 'rec', 'fil': 'tra', 'imp': 'fil', 'fin': 'imp'} 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): def require_delivery_available(service):
"""Outside the local stack, a simulated freight price must never reach a """Outside the local stack, a simulated freight price must never reach a
customer: until a real freight provider exists, only pickup is offered.""" customer: until a real freight provider exists, only pickup is offered."""
if service != 'pickup' and ENVIRONMENT != 'local' and getattr(freight, 'name', '') == 'fake': 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.') raise HTTPException(503, 'A entrega ainda não está disponível. Escolha a retirada em Franca.')

View File

@@ -1,8 +1,9 @@
"""Releasing artwork: ClamAV up to its size limit, a format check above it. """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 Unknown or error results NEVER release artwork. ClamAV scans files up to
scan_limit_bytes() (2 GB). Sheets of several GB are the normal order and scan_limit_bytes() (at most 2 GB). Since 2026-10-21 a file is at most 1 GB and
ClamAV cannot take them, so a larger file is released only if its first bytes 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 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 program renamed .png). That is the check the client chose for large files; it
does not look for malware inside a valid file. does not look for malware inside a valid file.
@@ -74,6 +75,37 @@ RIFF_FORMS = {'cdr': re.compile(rb'^RIFF....CDR', re.S), 'webp': re.compile(rb'^
HEAD_BYTES = 64 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): def format_matches(name, head):
"""Whether a file's first bytes are those of the format its name claims.""" """Whether a file's first bytes are those of the format its name claims."""
ext = name.rsplit('.', 1)[-1].lower() if '.' in name else '' ext = name.rsplit('.', 1)[-1].lower() if '.' in name else ''
@@ -82,11 +114,10 @@ def format_matches(name, head):
return any(head.startswith(sig) for sig in SIGNATURES.get(ext, ())) return any(head.startswith(sig) for sig in SIGNATURES.get(ext, ()))
def check_large(storage, row): def check_large(head, row):
"""Release decision for a file above the antivirus limit.""" """Release decision for a file above the antivirus limit."""
head = storage.client.get_object(Bucket=storage.bucket, Key=row['object_key'], # The content decides (D-13): a ".cdr" that is a PDF is still a PDF.
Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read() if format_matches(row['name'], head) or detected_format(head):
if format_matches(row['name'], head):
return 'clean', 'Acima do limite do antivírus; formato do arquivo conferido' 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' return 'rejected', 'O conteúdo do arquivo não corresponde ao formato do nome'
@@ -98,19 +129,25 @@ def scan_one(storage, scanner=None):
AND expires_at>now() AND scan_state IN ('pending','error') AND scan_after<=now() 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() ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1''').fetchone()
if not row:return False if not row:return False
name=row['name']
try: try:
# Every later decision reads the stored name (the manual charge,
# the JPG refusal, the grade, the print file, the folders), so the
# name is made to say what the file is (D-13).
head=head_of(storage,row)
name=real_name(name,head)
if row['size'] > scan_limit_bytes(): if row['size'] > scan_limit_bytes():
state,reason=check_large(storage,row) state,reason=check_large(head,row)
else: else:
stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body'] stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body']
try:state,reason=scanner.scan(stream,row['size']) try:state,reason=scanner.scan(stream,row['size'])
finally:stream.close() finally:stream.close()
except Exception: except Exception:
state,reason='error','Malware scanner unavailable; file remains blocked' 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(), c.execute("""UPDATE dtf_local.uploads SET name=%s,scan_state=%s,scan_reason=%s,scanned_at=now(),
scan_after=now()+interval '1 minute', scan_after=now()+interval '1 minute',
expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at 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'])) WHERE id=%s""",(name,state,reason,state,row['id']))
audit('artwork_scan', upload=str(row['id']), result=state) audit('artwork_scan', upload=str(row['id']), result=state)
return True return True

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, 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() 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 ( CREATE TABLE IF NOT EXISTS dtf_local.sessions (
id uuid PRIMARY KEY, owner uuid NOT NULL, id uuid PRIMARY KEY, owner uuid NOT NULL,
expires_at timestamptz NOT NULL DEFAULT now() + interval '7 days' expires_at timestamptz NOT NULL DEFAULT now() + interval '7 days'
@@ -141,6 +144,11 @@ CREATE TABLE IF NOT EXISTS dtf_local.backups (
status text NOT NULL CHECK(status IN ('ok','failed')), object_key text, bytes bigint, detail text 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); 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 -- 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. -- the server recomputed) and cannot be worked out again from the draft alone.
@@ -165,6 +173,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. -- 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) CREATE INDEX IF NOT EXISTS outbox_pending ON dtf_local.outbox(available_at, id)
WHERE delivered_at IS NULL; 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. -- 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 -- now() cannot appear in a partial index predicate, so the time comparisons stay
@@ -236,19 +247,32 @@ CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names (
-- Who may do what on the Kanban. superadmin is the system's own account (set -- 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 -- from the console); administrators manage users and machines; gestão runs
-- the business; operadores produce; vendedores only read. -- 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.
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin'; ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin';
DO $$ BEGIN ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
CHECK (role IN ('superadmin','admin','gestao','operador','vendedor')); CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro'));
EXCEPTION WHEN duplicate_object THEN NULL; END $$; -- The print machines, and which products each prints. An order keeps the
-- The print machines, and which products each prints. An order goes to the -- machine someone chose (machine_chosen) or the one given automatically: the
-- first active machine that prints its product unless someone chooses one. -- active machine of its product with the fewest metres open (app/machines.py).
-- limit_metres: the metres open a machine takes before the next order goes to
-- another one; NULL is no limit.
CREATE TABLE IF NOT EXISTS dtf_local.machines ( CREATE TABLE IF NOT EXISTS dtf_local.machines (
id uuid PRIMARY KEY, name text UNIQUE NOT NULL, products text[] NOT NULL DEFAULT '{}', 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() 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_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 $$;
-- The machines an operator works on; none means every machine. -- The machines an operator works on; none means every machine.
CREATE TABLE IF NOT EXISTS dtf_local.operator_machines ( CREATE TABLE IF NOT EXISTS dtf_local.operator_machines (
operator_id uuid NOT NULL REFERENCES dtf_local.operators(id) ON DELETE CASCADE, operator_id uuid NOT NULL REFERENCES dtf_local.operators(id) ON DELETE CASCADE,
@@ -256,3 +280,149 @@ CREATE TABLE IF NOT EXISTS dtf_local.operator_machines (
PRIMARY KEY (operator_id, machine_id) 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.
-- Defined once, here: the schema runs on every start, and an earlier, narrower
-- copy would refuse the rows of the kinds added after it.
ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check;
ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
CHECK(kind IN ('reset','code','account','notice','order','alert','test'));
-- 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;
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'));
-- 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 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;

View File

@@ -20,14 +20,27 @@ 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 Idempotency: the outbox may deliver the same event more than once. Every order
carries numeroOrdemCompra = "DTF-<order number>", and before creating one the carries numeroOrdemCompra = "DTF-<order number>", and before creating one the
customer's recent orders are searched for that number, so a second delivery 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 already sends WhatsApp messages from Tiny's Customer notices: the client sends WhatsApp messages from Tiny's order
order situação (Tiny webhook -> their middleware -> n8n). With situação (Tiny webhook -> their middleware -> n8n), on Aprovado, Pronto para
TINY_STATUS_UPDATES on, a paid order is set to "Aprovada" and a finished envio, Enviado and Entregue. With TINY_STATUS_UPDATES on, the Kanban moves
pickup order to "Pronto para envio", so those notices reach Site customers the Tiny order along with it (Dropstar's flow, 2026-10-23: two changes of
from the same number and templates; the system's own WhatsApp sender stays situação, none for Imprimindo, Correção or Revisão):
off. Pickup orders carry the client's "retirar pessoalmente" forma de envio.
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 os import os
import secrets import secrets
@@ -55,26 +68,73 @@ STEP_SETTINGS = {'file': 'TINY_SKU10_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU10_TEXTIL
'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA'} 'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA'}
METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_METRO_TEXTIL_AVULSA', METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_METRO_TEXTIL_AVULSA',
'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA'} 'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA'}
# 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'}
STEP_DEFAULTS = {'uvfile': 'DTFIMP.UV.010CM', 'uv': 'DTFIMP.UV.010CM'}
METRE_DEFAULTS = {'uvfile': 'DTFIMP.UV.1MT', 'uv': 'DTFIMP.UV.1MT'}
PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada', PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada',
'avulsa': 'DTF Têxtil 57 cm · artes avulsas', 'avulsa': 'DTF Têxtil 57 cm · artes avulsas',
'uvfile': 'DTF UV 28,5 cm · folha montada', 'uvfile': 'DTF UV 27 cm · folha montada',
'uv': 'DTF UV 28,5 cm · artes avulsas'} 'uv': 'DTF UV 27 cm · artes avulsas'}
# How far back to look for an order a previous delivery may already have made. # How far back to look for an order a previous delivery may already have made.
SEARCH_DAYS = 7 SEARCH_DAYS = 7
# A "ready" event can come after corrections; it normally knows the Tiny id. # A "ready" event can come after corrections; it normally knows the Tiny id.
READY_SEARCH_DAYS = 45 READY_SEARCH_DAYS = 45
# Tiny v3 order situações (PUT /pedidos/{id}/situacao). # 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 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', 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'} 5: 'Enviada', 6: 'Entregue', 2: 'Cancelada', 8: 'Dados incompletos', 9: 'Não entregue'}
# The client's customer notices (Tiny webhook -> middleware -> n8n -> WhatsApp) # The client's customer notices (Tiny webhook -> middleware -> n8n -> WhatsApp)
# react to these situações. Off until go-live: while n8n still sends the # 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 # designer message for DTFIMP products on "Aprovado", setting it would reach
# Site customers. # 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 {}
how = f"pago fora do site ({OUTSIDE_NOTES.get(paid.get('method'), paid.get('method'))})" if paid.get('outside') else 'pago'
return f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}"
STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES' STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES'
# The id of the client's custom "retirar pessoalmente" forma de envio (v2 code # The client's custom "retirar pessoalmente" forma de envio (v2 code X), which
# X), which the pickup notice is keyed on. Find it with the console tool. # 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_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 and, for the customer's
# credit, Dropstar's own "CORREÇÃO DTF" were sent by Marcus on 2026-10-27, for
# the orders the team registers as paid outside the site (D-35).
RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 977493654}
PICKUP_CARRIER = 761565838
# Dropstar's answers: the financial category "DTF SITE" (RECEITAS, id sent on
# 2026-10-26; it goes in pagamento.categoria, and replaced the store's
# "DUPLICADO DROP", 965775137), no seller (Tiny sets it from the contact,
# 2026-10-23), and the marcador SITE DTF, added after the order is created:
# 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'
# 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 STATE_MINUTES = 10
# Renewal runs about every four hours against a one-day refresh token, so # Renewal runs about every four hours against a one-day refresh token, so
# less than this left means renewals have been failing for hours. # less than this left means renewals have been failing for hours.
@@ -110,17 +170,25 @@ def required_settings():
setting for mode, setting in PRODUCT_SETTINGS.items() if not (sku_prefix(mode) or step_sku(mode))] 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): def sku_prefix(mode):
return os.environ.get(SKU_SETTINGS[mode], '').strip() return setting(SKU_SETTINGS[mode]) or ('' if setting(STEP_SETTINGS[mode]) else SKU_DEFAULTS.get(mode, ''))
def step_sku(mode): def step_sku(mode):
return os.environ.get(STEP_SETTINGS[mode], '').strip() return setting(STEP_SETTINGS[mode]) or ('' if setting(SKU_SETTINGS[mode]) else STEP_DEFAULTS.get(mode, ''))
def metre_sku(mode): def metre_sku(mode):
"""The metre SKU paired with a 10 cm SKU, or '' when the 10 cm one goes alone.""" """The metre SKU paired with a 10 cm SKU, or '' when the 10 cm one goes alone."""
return os.environ.get(METRE_SETTINGS[mode], '').strip() if step_sku(mode) else '' if not step_sku(mode):
return ''
return setting(METRE_SETTINGS[mode]) or ('' if setting(STEP_SETTINGS[mode]) else METRE_DEFAULTS.get(mode, ''))
def mode_codes(mode): def mode_codes(mode):
@@ -340,14 +408,35 @@ def money(cents):
return float(Decimal(cents) / 100) return float(Decimal(cents) / 100)
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 contact_payload(order, company=None): def contact_payload(order, company=None):
"""A new contact, named after the company's razão social when the """A new contact, named after the company's razão social when the
registry gave it (app/cnpj.py), else the recipient or the e-mail.""" 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'] customer = order['customer']
destination = order.get('destination') destination = order.get('destination')
company = company or {} company = company or {}
contact = {'nome': company.get('legal') or (destination or {}).get('recipient') or customer['mail'], contact = {'nome': (company.get('legal') or customer.get('name') or (destination or {}).get('recipient')
'tipoPessoa': 'J', 'cpfCnpj': customer['cnpj'], 'email': customer['mail'], or customer['mail']),
'tipoPessoa': 'F' if len(customer['cnpj']) == 11 else 'J', 'cpfCnpj': punctuated(customer['cnpj']), 'email': customer['mail'],
'celular': customer['zap'], 'situacao': 'A'} 'celular': customer['zap'], 'situacao': 'A'}
if company.get('trade'): if company.get('trade'):
contact['fantasia'] = company['trade'] contact['fantasia'] = company['trade']
@@ -363,9 +452,20 @@ def address(destination):
'uf': destination['state'], 'pais': 'Brasil'} 'uf': destination['state'], 'pais': 'Brasil'}
def order_payload(payload, contact_id, today=None, product_id=None): def business_days_after(day, days):
"""The v3 'pedido' for a paid order's approved snapshot. product_id finds a """The day `days` working days (Monday to Friday) after `day`."""
SKU's product id by its code, for the modes sold by SKU.""" 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):
"""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'] order = payload['order']
items = [] items = []
for item in order['items']: for item in order['items']:
@@ -390,25 +490,41 @@ def order_payload(payload, contact_id, today=None, product_id=None):
'valorUnitario': money(item['unit_cents']), 'valorUnitario': money(item['unit_cents']),
'infoAdicional': note}) 'infoAdicional': note})
freight = order['freight'] freight = order['freight']
pickup = freight.get('service') == 'pickup' service = freight.get('service')
pedido = {'data': (today or local_today()).isoformat(), pickup = service == 'pickup'
day = today or local_today()
pedido = {'data': day.isoformat(),
'idContato': contact_id, 'idContato': contact_id,
'numeroOrdemCompra': purchase_order(payload['number']), 'numeroOrdemCompra': purchase_order(payload['number']),
'itens': items, 'itens': items,
'valorFrete': money(freight['total_cents']), 'valorFrete': money(freight['total_cents']),
'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''), 'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''),
'observacoesInternas': f"Site DTF · pago · {payload['order_id']}"} 'observacoesInternas': internal_note(payload)}
pickup_method = os.environ.get(PICKUP_SETTING, '') carrier = shipping(service) if shipping else None
if pickup and pickup_method.isdigit(): if carrier:
pedido['transportador'] = {'formaEnvio': {'id': int(pickup_method)}} 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:
pedido['dataPrevista'] = business_days_after(day, int(days)).isoformat()
# Paid at once, in full, as the store's orders: one parcel on the day.
pedido['pagamento'] = {'categoria': {'id': CATEGORIES.get(payload.get('origin'), CATEGORY)}}
received = RECEIPT_METHODS.get((payload.get('payment') or {}).get('method'))
if received:
total = money(order['total_cents'])
pedido['pagamento'].update({'formaRecebimento': {'id': received},
'parcelas': [{'dias': 0, 'data': day.isoformat(), 'valor': total,
'formaRecebimento': {'id': received}}]})
destination = order.get('destination') destination = order.get('destination')
if destination: if destination:
pedido['enderecoEntrega'] = {**address(destination), 'enderecoNro': destination['number'], pedido['enderecoEntrega'] = {**address(destination), 'enderecoNro': destination['number'],
'nomeDestinatario': destination['recipient']} 'nomeDestinatario': destination['recipient']}
del pedido['enderecoEntrega']['numero'] 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', '') ecommerce = os.environ.get('TINY_ECOMMERCE_ID', '')
if ecommerce.isdigit(): if ecommerce.isdigit():
pedido['ecommerce'] = {'id': int(ecommerce), 'numeroPedidoEcommerce': purchase_order(payload['number'])} pedido['ecommerce']['id'] = int(ecommerce)
return pedido return pedido
@@ -435,26 +551,83 @@ def configured_skus(orders, mode):
return 'ok' if not missing else 'SKU não encontrado entre os produtos ativos: ' + ', '.join(missing) return 'ok' if not missing else 'SKU não encontrado entre os produtos ativos: ' + ', '.join(missing)
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): def configured_pickup(orders):
"""The forma de envio the pickup setting points at, or why it cannot be used.""" """The forma de envio used for pickup orders, or why there is none."""
value = os.environ.get(PICKUP_SETTING, '') value = os.environ.get(PICKUP_SETTING, '')
if not value.isdigit(): if value.isdigit():
return None, f'{PICKUP_SETTING} sem id' return orders.request('GET', f'/formas-envio/{value}'), 'ok'
return orders.request('GET', f'/formas-envio/{value}'), 'ok' return find_pickup(orders)
def check(auth=None, transport=None, orders=None): def check(auth=None, transport=None, orders=None):
"""Read-only proof that the connection and permissions work: one order and """Read-only proof that the connection and permissions work: one order and
one contact listed, each configured product found active and the pickup one contact listed, each product's SKUs found active and the pickup
forma de envio found, nothing created. Raises TinyNotConnected when there is no usable connection; forma de envio found, nothing created. Raises TinyNotConnected when there is no usable connection;
otherwise reports each read separately.""" otherwise reports each read separately."""
orders = orders or TinyOrders(auth=auth or TinyAuth(), transport=transport) orders = orders or TinyOrders(auth=auth or TinyAuth(), transport=transport)
def listed(path): def listed(path, **filters):
orders.request('GET', path, params={'limit': 1}) orders.request('GET', path, params={'limit': 1, **filters})
return 'ok' return 'ok'
reads = [('pedidos', lambda: listed('/pedidos')), ('contatos', lambda: listed('/contatos'))] # 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) 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] else configured_product(orders, mode)[1]) for mode in PRODUCT_SETTINGS]
reads.append(('forma de envio de retirada', lambda: configured_pickup(orders)[1])) reads.append(('forma de envio de retirada', lambda: configured_pickup(orders)[1]))
@@ -480,6 +653,7 @@ class TinyOrders:
self.http = httpx.Client(base_url=API, transport=transport, timeout=30) self.http = httpx.Client(base_url=API, transport=transport, timeout=30)
self.today = today self.today = today
self.skus = {} self.skus = {}
self.carriers = {}
# The company's names by CNPJ, for new contacts (app.cnpj.company). # The company's names by CNPJ, for new contacts (app.cnpj.company).
self.names = names self.names = names
@@ -492,6 +666,12 @@ class TinyOrders:
raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}') raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}')
return response.json() if response.content else {} return response.json() if response.content else {}
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 product_id(self, code): def product_id(self, code):
"""The id of the active product with this SKU code, remembered once found.""" """The id of the active product with this SKU code, remembered once found."""
if code not in self.skus: if code not in self.skus:
@@ -505,14 +685,22 @@ class TinyOrders:
self.skus[code] = int(match[0]['id']) self.skus[code] = int(match[0]['id'])
return self.skus[code] 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): def contact(self, order):
cnpj = order['customer']['cnpj'] cnpj = order['customer']['cnpj']
found = self.request('GET', '/contatos', params={'cpfCnpj': cnpj, 'limit': 5}) known = self.find_contact(cnpj)
for entry in found.get('itens') or []: if known:
if ''.join(ch for ch in str(entry.get('cpfCnpj') or '') if ch.isdigit()) == cnpj: return known
return entry['id']
company = None company = None
if self.names: if self.names and len(cnpj) == 14:
try: try:
company = self.names(cnpj) company = self.names(cnpj)
except Exception: # a name is a nicety; the order must still go except Exception: # a name is a nicety; the order must still go
@@ -523,14 +711,28 @@ class TinyOrders:
"""An order a previous delivery already created, or None.""" """An order a previous delivery already created, or None."""
wanted = purchase_order(payload['number']) wanted = purchase_order(payload['number'])
since = ((self.today or local_today()) - timedelta(days=days)).isoformat() since = ((self.today or local_today()) - timedelta(days=days)).isoformat()
found = self.request('GET', '/pedidos', params={'cpfCnpj': payload['order']['customer']['cnpj'], seen = set()
'dataInicial': since, 'limit': 100}) for form in search_forms(payload['order']['customer']['cnpj']):
for entry in found.get('itens') or []: found = self.request('GET', '/pedidos', params={'cpfCnpj': form, 'dataInicial': since, 'limit': 100})
detail = self.request('GET', f"/pedidos/{entry['id']}") for entry in found.get('itens') or []:
if detail.get('numeroOrdemCompra') == wanted: if entry['id'] in seen:
return detail continue
seen.add(entry['id'])
detail = self.request('GET', f"/pedidos/{entry['id']}")
if detail.get('numeroOrdemCompra') == wanted:
return detail
return None return None
def tag(self, tiny_id, known=False):
"""The SITE DTF marcador on the order, once. A retry that finds the
order already created checks first, since POST adds another."""
if known:
have = self.request('GET', f'/pedidos/{tiny_id}/marcadores')
have = have if isinstance(have, list) else have.get('itens') or []
if any(str(m.get('descricao', '')).strip().upper() == TAG for m in have):
return
self.request('POST', f'/pedidos/{tiny_id}/marcadores', json=[{'descricao': TAG}])
def set_situacao(self, tiny_id, situacao): def set_situacao(self, tiny_id, situacao):
self.request('PUT', f'/pedidos/{tiny_id}/situacao', json={'situacao': situacao}) self.request('PUT', f'/pedidos/{tiny_id}/situacao', json={'situacao': situacao})
@@ -540,6 +742,11 @@ class TinyOrders:
return self.sale(event_key, payload) return self.sale(event_key, payload)
if event == 'ready' and status_updates(): if event == 'ready' and status_updates():
return self.ready(event_key, payload) 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. # Other production events have no Tiny situação and are not written.
return {'provider': 'tiny', 'event_key': event_key, 'status': 'not-applicable', 'event': event} return {'provider': 'tiny', 'event_key': event_key, 'status': 'not-applicable', 'event': event}
@@ -556,31 +763,37 @@ class TinyOrders:
tiny_id, situacao = existing.get('id'), existing.get('situacao') tiny_id, situacao = existing.get('id'), existing.get('situacao')
else: else:
contact_id = self.contact(payload['order']) contact_id = self.contact(payload['order'])
created = self.request('POST', '/pedidos', json=order_payload(payload, contact_id, self.today, created = self.request('POST', '/pedidos', json=order_payload(
product_id=self.product_id)) payload, contact_id, self.today, product_id=self.product_id, shipping=self.shipping))
receipt = {'provider': 'tiny', 'event_key': event_key, 'status': 'created', receipt = {'provider': 'tiny', 'event_key': event_key, 'status': 'created',
'tiny_id': str(created.get('id')), 'tiny_number': str(created.get('numeroPedido'))} 'tiny_id': str(created.get('id')), 'tiny_number': str(created.get('numeroPedido'))}
tiny_id, situacao = created.get('id'), ABERTA tiny_id, situacao = created.get('id'), ABERTA
# Tagged before it is approved, so a failure here is retried while the order is still open.
if situacao == ABERTA:
self.tag(tiny_id, known=bool(existing))
receipt['marcador'] = TAG
if status_updates() and situacao == ABERTA: if status_updates() and situacao == ABERTA:
self.set_situacao(tiny_id, APROVADA) self.set_situacao(tiny_id, APROVADA)
receipt['situacao'] = SITUACOES[APROVADA] receipt['situacao'] = SITUACOES[APROVADA]
return receipt return receipt
def ready(self, event_key, payload): def ready(self, event_key, payload):
"""A pickup order became ready: "Pronto para envio", which the client's """The order reached Finalizado: "Pronto para envio", for pickup and
notices turn into the pickup message. Shipped orders get "Enviada" delivery alike (Dropstar, 2026-10-23). From there the team ships it in
once freight exists (1.2).""" 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} base = {'provider': 'tiny', 'event_key': event_key}
order = payload.get('order') or {}
if (order.get('freight') or {}).get('service') != 'pickup':
return {**base, 'status': 'not-applicable', 'event': 'ready'}
tiny_id = payload.get('tiny_id') tiny_id = payload.get('tiny_id')
detail = self.request('GET', f'/pedidos/{tiny_id}') if tiny_id else self.find(payload, READY_SEARCH_DAYS) detail = self.request('GET', f'/pedidos/{tiny_id}') if tiny_id else self.find(payload, READY_SEARCH_DAYS)
if not detail: if not detail:
raise TinyError(f"{purchase_order(payload['number'])} is not in Tiny yet; the outbox will retry") 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'))) base.update(tiny_id=str(detail.get('id')), tiny_number=str(detail.get('numeroPedido')))
situacao = detail.get('situacao') situacao = detail.get('situacao')
if situacao in (PRONTO_ENVIO, ENVIADA, ENTREGUE, CANCELADA, NAO_ENTREGUE): if situacao not in from_situacoes:
return {**base, 'status': 'status-unchanged', 'situacao': SITUACOES.get(situacao, str(situacao))} return {**base, 'status': 'status-unchanged', 'situacao': SITUACOES.get(situacao, str(situacao))}
self.set_situacao(detail['id'], PRONTO_ENVIO) self.set_situacao(detail['id'], target)
return {**base, 'status': 'status-updated', 'situacao': SITUACOES[PRONTO_ENVIO]} return {**base, 'status': 'status-updated', 'situacao': SITUACOES[target]}

View File

@@ -5,24 +5,37 @@ 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 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 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 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] python -m app.tiny_probe pedido --cnpj ... --email ... --celular ... [--modo file] [--metros 1.3]
show the test order; --confirmar creates it 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 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 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, 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 which must return the existing order. If the search cannot find the order, the
second delivery is not attempted: it would create a duplicate. Cancel the test second delivery is not attempted: it would create a duplicate. Either way the
order in Olist afterwards. 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 argparse
import base64
import json import json
import sys import sys
import time import time
from datetime import datetime from datetime import datetime
from decimal import Decimal, InvalidOperation from decimal import Decimal, InvalidOperation
from .core.pricing import TIERS from .core.pricing import PRICES
from .core.secrets import load as load_secret_files from .core.secrets import load as load_secret_files
from . import tiny from . import tiny
@@ -32,7 +45,7 @@ FIND_WAIT_SECONDS = 5
def test_order(cnpj, email, celular, mode, now=None, metres='1'): 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') number = 'TESTE-' + (now or datetime.now(tiny.BRASILIA)).strftime('%Y%m%d%H%M')
unit = TIERS[mode][0][1] unit = PRICES[mode]
total = int(Decimal(metres) * unit) total = int(Decimal(metres) * unit)
return {'order_id': 'teste-integracao', 'number': number, 'event': 'payment_approved', return {'order_id': 'teste-integracao', 'number': number, 'event': 'payment_approved',
'order': {'customer': {'cnpj': cnpj, 'mail': email, 'zap': celular}, 'order': {'customer': {'cnpj': cnpj, 'mail': email, 'zap': celular},
@@ -64,6 +77,70 @@ def formas_envio(orders, termo, out):
'. A retirada é a do tipo 6 (Customizado) que a equipe usa para retirar pessoalmente.') '. 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): def conferir(orders, out):
ok = True ok = True
for mode, setting in tiny.PRODUCT_SETTINGS.items(): for mode, setting in tiny.PRODUCT_SETTINGS.items():
@@ -99,34 +176,142 @@ def conferir(orders, out):
def pedido(orders, payload, confirm, out, wait=time.sleep): def pedido(orders, payload, confirm, out, wait=time.sleep):
cnpj = payload['order']['customer']['cnpj'] cnpj = payload['order']['customer']['cnpj']
contacts = orders.request('GET', '/contatos', params={'cpfCnpj': cnpj, 'limit': 5}).get('itens') or [] known = orders.find_contact(cnpj)
known = [c for c in contacts if ''.join(ch for ch in str(c.get('cpfCnpj') or '') if ch.isdigit()) == cnpj] if known:
out(f"Contato {cnpj}: " + (f"já existe no Tiny (id {known[0]['id']})" if known out(f"Contato {tiny.punctuated(cnpj)}: já existe no Tiny (id {known})")
else 'não existe; será criado com o e-mail como nome')) 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('Pedido que será enviado:')
out(json.dumps(tiny.order_payload(payload, known[0]['id'] if known else 0, product_id=orders.product_id), out(json.dumps(tiny.order_payload(payload, known or 0, product_id=orders.product_id,
shipping=orders.shipping),
ensure_ascii=False, indent=2)) ensure_ascii=False, indent=2))
out(f'Marcador: {tiny.TAG} (incluído logo depois de criar o pedido)')
if not confirm: if not confirm:
out('Nada foi criado. Repita com --confirmar para criar este pedido no Tiny.') out('Nada foi criado. Repita com --confirmar para criar este pedido no Tiny.')
return None return None
first = orders.deliver('teste-integracao', payload) first = orders.deliver('teste-integracao', payload)
out(f"1º envio: {first['status']} · Tiny id {first['tiny_id']} · nº {first['tiny_number']}") out(f"1º envio: {first['status']} · Tiny id {first['tiny_id']} · nº {first['tiny_number']}")
for attempt in range(FIND_ATTEMPTS): try:
found = orders.find(payload) for attempt in range(FIND_ATTEMPTS):
if found: found = orders.find(payload)
break if found:
if attempt < FIND_ATTEMPTS - 1: break
wait(FIND_WAIT_SECONDS) if attempt < FIND_ATTEMPTS - 1:
else: wait(FIND_WAIT_SECONDS)
out(f'FALHA: a busca por {tiny.purchase_order(payload["number"])} não encontrou o pedido. ' else:
'Um reenvio criaria um duplicado; o 2º envio não foi feito. Cancele o pedido no Olist.') 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 return False
second = orders.deliver('teste-integracao', payload) out(f'Contato {tiny.punctuated(cnpj)}: já existe no Tiny (id {known})')
out(f"2º envio: {second['status']} · Tiny id {second['tiny_id']}") full = tiny.order_payload(payload, known, product_id=orders.product_id, shipping=orders.shipping)
passed = second['status'] == 'already-created' and second['tiny_id'] == first['tiny_id'] without = lambda key: {k: v for k, v in full.items() if k != key}
out(('OK: o reenvio encontrou o mesmo pedido.' if passed else 'FALHA: o reenvio não devolveu o mesmo pedido.') versions = [('completo', full)] + [(f'sem {key}', without(key)) for key in
+ f" Cancele o pedido nº {first['tiny_number']} no Olist.") ('ecommerce', 'pagamento', 'transportador', 'dataPrevista')
return passed 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): def main(argv=None, orders=None, out=print):
@@ -137,17 +322,29 @@ def main(argv=None, orders=None, out=print):
methods = commands.add_parser('formas-envio') methods = commands.add_parser('formas-envio')
methods.add_argument('termo', nargs='?', default='') methods.add_argument('termo', nargs='?', default='')
commands.add_parser('conferir') 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 = commands.add_parser('pedido')
order.add_argument('--cnpj', required=True) order.add_argument('--cnpj', '--cpf', dest='cnpj', required=True, help='CNPJ ou CPF do cliente')
order.add_argument('--email', required=True) order.add_argument('--email', required=True)
order.add_argument('--celular', required=True) order.add_argument('--celular', required=True)
order.add_argument('--modo', choices=sorted(tiny.PRODUCT_SETTINGS), default='file') 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('--metros', default='1', help='metragem cobrada, em passos de 10 cm (ex.: 1.3)')
order.add_argument('--confirmar', action='store_true') 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) args = parser.parse_args(argv)
if orders is None: if orders is None:
load_secret_files() load_secret_files()
orders = tiny.TinyOrders(auth=tiny.TinyAuth()) 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: try:
if args.command == 'produtos': if args.command == 'produtos':
produtos(orders, args.termo, out) produtos(orders, args.termo, out)
@@ -157,10 +354,20 @@ def main(argv=None, orders=None, out=print):
return 0 return 0
if args.command == 'conferir': if args.command == 'conferir':
return 0 if conferir(orders, out) else 1 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()) cnpj = ''.join(ch for ch in args.cnpj if ch.isdigit())
if len(cnpj) != 14: if len(cnpj) not in (11, 14):
out('Informe um CNPJ com 14 dígitos.') out('Informe um CPF (11 dígitos) ou um CNPJ (14 dígitos).')
return 2 return 2
if args.command == 'diagnostico':
return 0 if diagnostico(orders, test_order(cnpj, args.email, args.celular, 'file'), out) else 1
try: try:
metres = Decimal(args.metros.replace(',', '.')) metres = Decimal(args.metros.replace(',', '.'))
except InvalidOperation: except InvalidOperation:

View File

@@ -6,7 +6,8 @@ import threading
import time import time
from http.server import BaseHTTPRequestHandler, HTTPServer from http.server import BaseHTTPRequestHandler, HTTPServer
from psycopg.types.json import Jsonb from psycopg.types.json import Jsonb
from .adapters import FakeTiny, FakeWhatsApp, LocalS3Storage, require_runtime from . import mail
from .adapters import FakeTiny, LocalS3Storage, require_runtime
from .core.secrets import load as load_secret_files from .core.secrets import load as load_secret_files
from .core.db import connect from .core.db import connect
from .printjobs import render_loop from .printjobs import render_loop
@@ -14,7 +15,7 @@ from .scanning import ClamAV, scan_loop
load_secret_files() load_secret_files()
require_runtime() require_runtime()
adapters = {'tiny': FakeTiny(), 'whatsapp': FakeWhatsApp()} adapters = {'tiny': FakeTiny()}
# Not yet confirmed against the client's account; see app/tiny.py. # Not yet confirmed against the client's account; see app/tiny.py.
if os.environ.get('TINY_ADAPTER') == 'tiny': if os.environ.get('TINY_ADAPTER') == 'tiny':
from .tiny import TinyOrders from .tiny import TinyOrders
@@ -41,6 +42,9 @@ def cleanup():
c.execute('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s', (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.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.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.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.login_attempts WHERE started_at<now()-interval '1 day'")
c.execute("DELETE FROM dtf_local.security_events WHERE created_at<now()-interval '30 days'") c.execute("DELETE FROM dtf_local.security_events WHERE created_at<now()-interval '30 days'")
@@ -115,6 +119,7 @@ def loop():
if time.monotonic()-last_cleanup > 60: if time.monotonic()-last_cleanup > 60:
cleanup() cleanup()
last_cleanup = time.monotonic() last_cleanup = time.monotonic()
mail.send_pending(connect)
tiny_keepalive() tiny_keepalive()
reconcile_payments() reconcile_payments()
resolve_names() resolve_names()

View File

@@ -47,9 +47,17 @@ x-app: &app
JADLOG_CUBAGEM_KG_M3: ${JADLOG_CUBAGEM_KG_M3:-} JADLOG_CUBAGEM_KG_M3: ${JADLOG_CUBAGEM_KG_M3:-}
JADLOG_METROS_POR_CAIXA: ${JADLOG_METROS_POR_CAIXA:-} JADLOG_METROS_POR_CAIXA: ${JADLOG_METROS_POR_CAIXA:-}
FREIGHT_PRODUCTION_DAYS: ${FREIGHT_PRODUCTION_DAYS:-0} 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. # Carts the Site priced are approved at checkout; larger ones wait for review.
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true} QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50} QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-0}
TINY_ADAPTER: ${TINY_ADAPTER:-fake} TINY_ADAPTER: ${TINY_ADAPTER:-fake}
TINY_CLIENT_ID: ${TINY_CLIENT_ID:-} TINY_CLIENT_ID: ${TINY_CLIENT_ID:-}
TINY_CLIENT_SECRET: ${TINY_CLIENT_SECRET:-} TINY_CLIENT_SECRET: ${TINY_CLIENT_SECRET:-}
@@ -71,10 +79,19 @@ x-app: &app
TINY_SKU_METRO_UV_FOLHA: ${TINY_SKU_METRO_UV_FOLHA:-} TINY_SKU_METRO_UV_FOLHA: ${TINY_SKU_METRO_UV_FOLHA:-}
TINY_SKU_METRO_UV_AVULSA: ${TINY_SKU_METRO_UV_AVULSA:-} TINY_SKU_METRO_UV_AVULSA: ${TINY_SKU_METRO_UV_AVULSA:-}
TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-} 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 STORAGE_ADAPTER: s3-local
MOCK_FREIGHT_CENTS: ${MOCK_FREIGHT_CENTS:-1500} 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} UPLOAD_PART_BYTES: ${UPLOAD_PART_BYTES:-8388608}
STORAGE_QUOTA_BYTES: ${STORAGE_QUOTA_BYTES:-53687091200} STORAGE_QUOTA_BYTES: ${STORAGE_QUOTA_BYTES:-53687091200}
OWNER_UPLOAD_QUOTA_BYTES: ${OWNER_UPLOAD_QUOTA_BYTES:-10737418240} OWNER_UPLOAD_QUOTA_BYTES: ${OWNER_UPLOAD_QUOTA_BYTES:-10737418240}

View File

@@ -15,7 +15,10 @@ LABEL org.opencontainers.image.title="DTF Portal/API" \
# is what the production image was doing while the local one already did this. # is what the production image was doing while the local one already did this.
# pg_dump and age are for the database backup (ops/db_backup.py). Debian 13 # 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. # ships PostgreSQL 17, the server's major version, which pg_dump must match.
RUN apt-get update \ # 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 upgrade -y \
&& apt-get install -y --no-install-recommends postgresql-client-17 age \ && apt-get install -y --no-install-recommends postgresql-client-17 age \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*

View File

@@ -14,8 +14,12 @@ ENV NGINX_TEMPLATE=/build/deploy/nginx.conf.template
RUN python infra/compile_web.py RUN python infra/compile_web.py
FROM ${NGINX_BASE_IMAGE} FROM ${NGINX_BASE_IMAGE}
# Same reason as the API image: a pinned base freezes its packages. # Same reason as the API image: a pinned base freezes its packages. The day
RUN apk upgrade --no-cache # (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 ARG VCS_REF=unknown
LABEL org.opencontainers.image.title="DTF Site and Kanban" \ LABEL org.opencontainers.image.title="DTF Site and Kanban" \
org.opencontainers.image.revision="$VCS_REF" \ org.opencontainers.image.revision="$VCS_REF" \

View File

@@ -6,7 +6,7 @@ substitute for `production_preflight.py`, CI, staging acceptance, or change appr
## Application and external contracts ## Application and external contracts
- [ ] `docs/PRODUCTION_INPUTS.md` has owners, decisions, and evidence for every item. - [ ] `docs/PRODUCTION_INPUTS.md` has owners, decisions, and evidence for every item.
- [ ] Production R2, freight, Mercado Pago, Tiny/Olist, and WhatsApp adapters have - [ ] Production R2, freight, Mercado Pago, and Tiny/Olist adapters have
sandbox contract tests and least-privilege credentials. sandbox contract tests and least-privilege credentials.
- [ ] Payment webhook authenticity, replay handling, and idempotency are tested. - [ ] Payment webhook authenticity, replay handling, and idempotency are tested.
- [ ] Docker secret `*_FILE` loading is implemented and tested without logging values. - [ ] Docker secret `*_FILE` loading is implemented and tested without logging values.

View File

@@ -54,10 +54,15 @@ server {
try_files /index.html =404; try_files /index.html =404;
} }
# The customer's area: one page, which shows the right part for each address. # The customer's area: one page, which shows the right part for each address.
location ~ ^/conta(/(entrar|pedidos|dados))?/?$ { location ~ ^/conta(/(entrar|pedidos|dados|redefinir))?/?$ {
expires -1; expires -1;
try_files /portal.html =404; try_files /portal.html =404;
} }
# The DTF's own terms: exchanges, file keeping and privacy.
location ~ ^/termos/?$ {
expires -1;
try_files /termos.html =404;
}
location / { location / {
expires -1; expires -1;
try_files $uri $uri/ =404; try_files $uri $uri/ =404;

View File

@@ -44,11 +44,19 @@ TINY_PRODUCT_UV_AVULSA=TBD
TINY_FORMA_ENVIO_RETIRADA=TBD TINY_FORMA_ENVIO_RETIRADA=TBD
# true only at go-live, after the n8n DTFIMP designer branch is removed. # true only at go-live, after the n8n DTFIMP designer branch is removed.
TINY_STATUS_UPDATES=false TINY_STATUS_UPDATES=false
WHATSAPP_ADAPTER=TBD # E-mail (password recovery and team alerts). off until the SMTP account exists.
MAIL_ADAPTER=off
MAIL_FROM=DTF Dropstar <nao-responda@SITE_DOMAIN>
MAIL_REPLY_TO=
SMTP_HOST=TBD
SMTP_PORT=587
SMTP_SECURITY=starttls
SMTP_USER=TBD
SMTP_PASSWORD=TBD
STORAGE_QUOTA_BYTES=TBD STORAGE_QUOTA_BYTES=TBD
OWNER_UPLOAD_QUOTA_BYTES=TBD OWNER_UPLOAD_QUOTA_BYTES=TBD
MAX_PENDING_UPLOADS=10 MAX_PENDING_UPLOADS=10
MAX_UPLOAD_BYTES=5368709120 MAX_UPLOAD_BYTES=4294967296
UPLOAD_PART_BYTES=8388608 UPLOAD_PART_BYTES=8388608
SCAN_MAX_BYTES=134217728 SCAN_MAX_BYTES=134217728
# Daily encrypted database backup to its own bucket (docs/BACKUP.md). # Daily encrypted database backup to its own bucket (docs/BACKUP.md).
@@ -70,4 +78,3 @@ OPERATOR_PASSWORD_SECRET=TBD
PAYMENT_TOKEN_SECRET=TBD PAYMENT_TOKEN_SECRET=TBD
PAYMENT_WEBHOOK_SECRET=TBD PAYMENT_WEBHOOK_SECRET=TBD
TINY_TOKEN_SECRET=TBD TINY_TOKEN_SECRET=TBD
WHATSAPP_TOKEN_SECRET=TBD

View File

@@ -20,12 +20,12 @@ REQUIRED = (
'POSTGRES_DB', 'POSTGRES_USER', 'APP_DB_USER', 'POSTGRES_VOLUME', 'OPERATOR_EMAIL', 'POSTGRES_DB', 'POSTGRES_USER', 'APP_DB_USER', 'POSTGRES_VOLUME', 'OPERATOR_EMAIL',
'STORAGE_QUOTA_BYTES', 'OWNER_UPLOAD_QUOTA_BYTES', 'MAX_UPLOAD_BYTES', 'STORAGE_QUOTA_BYTES', 'OWNER_UPLOAD_QUOTA_BYTES', 'MAX_UPLOAD_BYTES',
'UPLOAD_PART_BYTES', 'MAX_PENDING_UPLOADS', 'SCAN_MAX_BYTES', 'UPLOAD_PART_BYTES', 'MAX_PENDING_UPLOADS', 'SCAN_MAX_BYTES',
'PAYMENT_ADAPTER', 'FREIGHT_ADAPTER', 'TINY_ADAPTER', 'WHATSAPP_ADAPTER', 'PAYMENT_ADAPTER', 'FREIGHT_ADAPTER', 'TINY_ADAPTER',
'DATABASE_URL_SECRET', 'DATABASE_ADMIN_URL_SECRET', 'DATABASE_URL_SECRET', 'DATABASE_ADMIN_URL_SECRET',
'DB_ADMIN_PASSWORD_SECRET', 'APP_DB_PASSWORD_SECRET', 'DB_ADMIN_PASSWORD_SECRET', 'APP_DB_PASSWORD_SECRET',
'R2_ACCESS_KEY_ID_SECRET', 'R2_SECRET_ACCESS_KEY_SECRET', 'R2_ACCESS_KEY_ID_SECRET', 'R2_SECRET_ACCESS_KEY_SECRET',
'OPERATOR_PASSWORD_SECRET', 'PAYMENT_TOKEN_SECRET', 'OPERATOR_PASSWORD_SECRET', 'PAYMENT_TOKEN_SECRET',
'PAYMENT_WEBHOOK_SECRET', 'TINY_TOKEN_SECRET', 'WHATSAPP_TOKEN_SECRET', 'PAYMENT_WEBHOOK_SECRET', 'TINY_TOKEN_SECRET',
) )
IMMUTABLE_IMAGE = re.compile(r'^[a-z0-9][a-z0-9._:/-]*@sha256:([0-9a-f]{64})$') IMMUTABLE_IMAGE = re.compile(r'^[a-z0-9][a-z0-9._:/-]*@sha256:([0-9a-f]{64})$')
IMAGE_REPOSITORY = re.compile( IMAGE_REPOSITORY = re.compile(
@@ -42,7 +42,7 @@ SOURCE_BLOCKERS = {
'payment = FakePayment()', 'payment = FakePayment()',
), ),
'app/worker.py': ( 'app/worker.py': (
"adapters = {'tiny': FakeTiny(), 'whatsapp': FakeWhatsApp()}", "adapters = {'tiny': FakeTiny()}",
), ),
} }
@@ -148,7 +148,7 @@ def config_errors(values):
bucket = values.get('R2_BUCKET', '') bucket = values.get('R2_BUCKET', '')
if bucket and not re.fullmatch(r'[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]', bucket): if bucket and not re.fullmatch(r'[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]', bucket):
errors.append('R2_BUCKET must be a valid S3 bucket name') errors.append('R2_BUCKET must be a valid S3 bucket name')
for name in ('PAYMENT_ADAPTER', 'FREIGHT_ADAPTER', 'TINY_ADAPTER', 'WHATSAPP_ADAPTER'): for name in ('PAYMENT_ADAPTER', 'FREIGHT_ADAPTER', 'TINY_ADAPTER'):
if values.get(name, '').lower() in {'', 'fake', 'mock', 'local'}: if values.get(name, '').lower() in {'', 'fake', 'mock', 'local'}:
errors.append(f'{name} must select an approved non-fake implementation') errors.append(f'{name} must select an approved non-fake implementation')
for name in REQUIRED: for name in REQUIRED:

View File

@@ -59,14 +59,13 @@ def valid_config():
'PAYMENT_ADAPTER': 'mercado-pago', 'PAYMENT_ADAPTER': 'mercado-pago',
'FREIGHT_ADAPTER': 'approved-freight', 'FREIGHT_ADAPTER': 'approved-freight',
'TINY_ADAPTER': 'tiny-olist', 'TINY_ADAPTER': 'tiny-olist',
'WHATSAPP_ADAPTER': 'approved-whatsapp',
} }
for name in ( for name in (
'DATABASE_URL_SECRET', 'DATABASE_ADMIN_URL_SECRET', 'DATABASE_URL_SECRET', 'DATABASE_ADMIN_URL_SECRET',
'DB_ADMIN_PASSWORD_SECRET', 'APP_DB_PASSWORD_SECRET', 'DB_ADMIN_PASSWORD_SECRET', 'APP_DB_PASSWORD_SECRET',
'R2_ACCESS_KEY_ID_SECRET', 'R2_SECRET_ACCESS_KEY_SECRET', 'R2_ACCESS_KEY_ID_SECRET', 'R2_SECRET_ACCESS_KEY_SECRET',
'OPERATOR_PASSWORD_SECRET', 'PAYMENT_TOKEN_SECRET', 'OPERATOR_PASSWORD_SECRET', 'PAYMENT_TOKEN_SECRET',
'PAYMENT_WEBHOOK_SECRET', 'TINY_TOKEN_SECRET', 'WHATSAPP_TOKEN_SECRET', 'PAYMENT_WEBHOOK_SECRET', 'TINY_TOKEN_SECRET',
): ):
values[name] = 'dtf_prod_' + name.lower() values[name] = 'dtf_prod_' + name.lower()
return values return values

View File

@@ -55,19 +55,43 @@ x-app-environment: &app-environment
JADLOG_METROS_POR_CAIXA: ${JADLOG_METROS_POR_CAIXA:-} JADLOG_METROS_POR_CAIXA: ${JADLOG_METROS_POR_CAIXA:-}
# Working days of production added to Jadlog's delivery time. # Working days of production added to Jadlog's delivery time.
FREIGHT_PRODUCTION_DAYS: ${FREIGHT_PRODUCTION_DAYS:-0} FREIGHT_PRODUCTION_DAYS: ${FREIGHT_PRODUCTION_DAYS:-0}
# Correios PAC and SEDEX, on when CORREIOS_CODIGO_ACESSO (the CWS access
# code, a secret: set it in the stack) is set. They price the package above
# (weights and JADLOG_CAIXA_CM). The rest is Dropstar's contract, not secret.
CORREIOS_CODIGO_ACESSO: ${CORREIOS_CODIGO_ACESSO:-}
CORREIOS_USUARIO: ${CORREIOS_USUARIO:-8825364223}
CORREIOS_CARTAO: ${CORREIOS_CARTAO:-0076691373}
CORREIOS_CONTRATO: ${CORREIOS_CONTRATO:-9912551407}
# Only if the contract's codes differ from 03298 (PAC) and 03220 (SEDEX);
# python -m app.correios_probe shows whether they price.
CORREIOS_COD_PAC: ${CORREIOS_COD_PAC:-}
CORREIOS_COD_SEDEX: ${CORREIOS_COD_SEDEX:-}
# A cart the Site priced is approved at checkout and can be paid at once; # A cart the Site priced is approved at checkout and can be paid at once;
# orders above QUOTE_AUTO_MAX_METRES, or with a grade the Site did not # orders above QUOTE_AUTO_MAX_METRES, or with a grade the Site did not
# compute, wait for an operator on the Kanban (app/quote_review.py). # compute, wait for an operator on the Kanban (app/quote_review.py).
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true} QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50} QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}
# Cents added to each metre of a finished sheet someone has to open by hand
# (CDR, AI, PSD, TIFF, or a length the customer typed). Dropstar set R$ 2,00
# a metro on 2026-10-23; 0 adds nothing. The Site shows it before payment.
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-200}
# Print files longer than 5,08 m are written at their real size, which Corel
# reads (2026-10-28). true goes back to PDF's /UserUnit scale, for a RIP that
# refuses pages over 5,08 m.
PRINT_PAGE_SCALE: ${PRINT_PAGE_SCALE:-false}
# Order creation in Tiny stays off until it has been tested against the # Order creation in Tiny stays off until it has been tested against the
# client's account (Tiny has no sandbox). The application credentials can be # client's account (Tiny has no sandbox). The application credentials can be
# set now: they let an operator connect Tiny from the Kanban, and the worker # set now: they let an operator connect Tiny from the Kanban, and the worker
# keeps that connection alive. Callback: https://<KANBAN_DOMAIN>/api/operator/tiny/callback # keeps that connection alive. Callback: https://<KANBAN_DOMAIN>/api/operator/tiny/callback
TINY_ADAPTER: fake # fake until the supervised test order (python -m app.tiny_probe pedido) has
# passed on the client's account; then tiny, set in the stack.
TINY_ADAPTER: ${TINY_ADAPTER:-fake}
TINY_CLIENT_ID: ${TINY_CLIENT_ID:-} TINY_CLIENT_ID: ${TINY_CLIENT_ID:-}
TINY_CLIENT_SECRET: ${TINY_CLIENT_SECRET:-} TINY_CLIENT_SECRET: ${TINY_CLIENT_SECRET:-}
TINY_REDIRECT_URI: ${TINY_REDIRECT_URI:-} TINY_REDIRECT_URI: ${TINY_REDIRECT_URI:-}
# Products, SKUs and the pickup forma de envio need no settings: the SKUs are
# Dropstar's catalogue (DTFIMP.TX…, DTFIMP.UV.1MT, DTFIMP.UV.010CM) and the
# pickup is found in Tiny by its name. These only override them.
TINY_PRODUCT_TEXTIL_FOLHA: ${TINY_PRODUCT_TEXTIL_FOLHA:-} TINY_PRODUCT_TEXTIL_FOLHA: ${TINY_PRODUCT_TEXTIL_FOLHA:-}
TINY_PRODUCT_TEXTIL_AVULSA: ${TINY_PRODUCT_TEXTIL_AVULSA:-} TINY_PRODUCT_TEXTIL_AVULSA: ${TINY_PRODUCT_TEXTIL_AVULSA:-}
TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-} TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-}
@@ -86,26 +110,42 @@ x-app-environment: &app-environment
TINY_SKU_METRO_UV_AVULSA: ${TINY_SKU_METRO_UV_AVULSA:-} TINY_SKU_METRO_UV_AVULSA: ${TINY_SKU_METRO_UV_AVULSA:-}
# The client's "retirar pessoalmente" forma de envio id, on pickup orders. # The client's "retirar pessoalmente" forma de envio id, on pickup orders.
TINY_FORMA_ENVIO_RETIRADA: ${TINY_FORMA_ENVIO_RETIRADA:-} TINY_FORMA_ENVIO_RETIRADA: ${TINY_FORMA_ENVIO_RETIRADA:-}
# Optional e-commerce channel id for Site orders. Without it the order still
# carries DTF-<n> as numeroPedidoEcommerce, with no channel.
TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-}
# Sets "Aprovada" on paid orders and "Pronto para envio" on finished pickup # Sets "Aprovada" on paid orders and "Pronto para envio" on finished pickup
# orders, which the client's Tiny -> n8n notices send to customers. Turn on # orders, which the client's Tiny -> n8n notices send to customers. Turn on
# only together with TINY_ADAPTER=tiny and after n8n stops sending the # only together with TINY_ADAPTER=tiny and after n8n stops sending the
# designer message for DTFIMP products. # designer message for DTFIMP products.
TINY_STATUS_UPDATES: ${TINY_STATUS_UPDATES:-false} TINY_STATUS_UPDATES: ${TINY_STATUS_UPDATES:-false}
WHATSAPP_ADAPTER: fake # E-mail: customers' password recovery and the team's alerts (app/mail.py).
# off until the client's SMTP account exists; then smtp with the settings
# below, or the API and worker refuse to start. SMTP_SECURITY is starttls
# (port 587), ssl (465) or none.
MAIL_ADAPTER: ${MAIL_ADAPTER:-off}
MAIL_FROM: ${MAIL_FROM:-}
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-r2 STORAGE_ADAPTER: s3-r2
PUBLIC_ORIGIN: https://${SITE_DOMAIN:?set SITE_DOMAIN} PUBLIC_ORIGIN: https://${SITE_DOMAIN:?set SITE_DOMAIN}
PUBLIC_HOST: ${SITE_DOMAIN:?set SITE_DOMAIN} PUBLIC_HOST: ${SITE_DOMAIN:?set SITE_DOMAIN}
ALLOWED_HOSTS: ${SITE_DOMAIN:?set SITE_DOMAIN},${KANBAN_DOMAIN:?set KANBAN_DOMAIN} ALLOWED_HOSTS: ${SITE_DOMAIN:?set SITE_DOMAIN},${KANBAN_DOMAIN:?set KANBAN_DOMAIN}
ALLOWED_ORIGINS: https://${SITE_DOMAIN:?set SITE_DOMAIN},https://${KANBAN_DOMAIN:?set KANBAN_DOMAIN} ALLOWED_ORIGINS: https://${SITE_DOMAIN:?set SITE_DOMAIN},https://${KANBAN_DOMAIN:?set KANBAN_DOMAIN}
COOKIE_SECURE: "true" COOKIE_SECURE: "true"
MAX_UPLOAD_BYTES: "5368709120" # 4 GB per file (Dropstar, 2026-10-28; it was 5 GB, then 1 GB from 2026-10-21).
MAX_UPLOAD_BYTES: "4294967296"
UPLOAD_PART_BYTES: "8388608" UPLOAD_PART_BYTES: "8388608"
# Sheets of several GB are the normal order, so room for many of them. # Sheets of several GB are the normal order, so room for many of them.
STORAGE_QUOTA_BYTES: "${STORAGE_QUOTA_BYTES:-536870912000}" STORAGE_QUOTA_BYTES: "${STORAGE_QUOTA_BYTES:-536870912000}"
OWNER_UPLOAD_QUOTA_BYTES: "${OWNER_UPLOAD_QUOTA_BYTES:-53687091200}" OWNER_UPLOAD_QUOTA_BYTES: "${OWNER_UPLOAD_QUOTA_BYTES:-53687091200}"
MAX_PENDING_UPLOADS: "10" MAX_PENDING_UPLOADS: "10"
# ClamAV scans up to this; larger files (up to MAX_UPLOAD_BYTES) are released # ClamAV scans up to its own limit, 2000 MiB (infra/clamd.conf); a larger
# after a file-format check instead (app/scanning.py). # file, up to the 4 GB above, is released after the file-format check
# (app/scanning.py, check_large).
SCAN_MAX_BYTES: "2097152000" SCAN_MAX_BYTES: "2097152000"
services: services:
@@ -173,7 +213,10 @@ services:
environment: *app-environment environment: *app-environment
networks: [backend, egress] networks: [backend, egress]
read_only: true read_only: true
tmpfs: [/tmp] # Swarm ignores the short `tmpfs:` key: a read-only container then has no
# writable /tmp at all. The long volume syntax is what a stack honours.
volumes:
- {type: tmpfs, target: /tmp, tmpfs: {size: 268435456}}
healthcheck: healthcheck:
test: [CMD-SHELL, 'python -c "import os,urllib.request; r=urllib.request.Request(\"http://localhost:8000/health\",headers={\"Host\":os.environ[\"PUBLIC_HOST\"]}); urllib.request.urlopen(r,timeout=3)"'] test: [CMD-SHELL, 'python -c "import os,urllib.request; r=urllib.request.Request(\"http://localhost:8000/health\",headers={\"Host\":os.environ[\"PUBLIC_HOST\"]}); urllib.request.urlopen(r,timeout=3)"']
interval: 15s interval: 15s
@@ -190,7 +233,8 @@ services:
environment: *app-environment environment: *app-environment
networks: [backend, egress] networks: [backend, egress]
read_only: true read_only: true
tmpfs: [/tmp] # Print files are rendered here and can be hundreds of MB: on disk, not in memory.
volumes: [worker-tmp:/tmp]
healthcheck: healthcheck:
test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8002/health',timeout=3)"] test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8002/health',timeout=3)"]
interval: 15s interval: 15s
@@ -224,7 +268,9 @@ services:
BACKUP_HOUR: ${BACKUP_HOUR:-3} BACKUP_HOUR: ${BACKUP_HOUR:-3}
networks: [backend, egress] networks: [backend, egress]
read_only: true read_only: true
tmpfs: [/tmp] # In memory: a restore's private key is written here while it runs.
volumes:
- {type: tmpfs, target: /tmp, tmpfs: {size: 1073741824}}
deploy: deploy:
replicas: 1 replicas: 1
restart_policy: {condition: on-failure, delay: 30s} restart_policy: {condition: on-failure, delay: 30s}
@@ -290,6 +336,7 @@ configs:
volumes: volumes:
postgres-data: postgres-data:
worker-tmp:
networks: networks:
backend: backend:

View File

@@ -38,7 +38,9 @@ online system, not factory-machine automation.
- Freight quotation and charging at checkout. - Freight quotation and charging at checkout.
- Idempotent Tiny/Olist order integration and order traceability. - Idempotent Tiny/Olist order integration and order traceability.
- Online Kanban for production status and secure file download. - Online Kanban for production status and secure file download.
- WhatsApp status notifications. - Customer status notices: not sent by this system. The client's own n8n sends
WhatsApp messages from Tiny's status changes (decided 2026-10-16); the Kanban
only offers a one-click WhatsApp link for a correction.
- Private object storage, 30-day file retention, backups, and basic security. - Private object storage, 30-day file retention, backups, and basic security.
- Operator guidance for the factory team. - Operator guidance for the factory team.
@@ -141,16 +143,40 @@ taxes, and payment-provider fees before presenting a commercial quote.
## Commercial rules ## Commercial rules
The existing rules in `web/index.html` are approved as the current source of The rules in `web/index.html` and `app/core/pricing.py` are approved as the
truth. Do **not** redesign, simplify, or change prices, discounts, minimums, current source of truth. Do **not** redesign, simplify, or change prices,
rounding, or product modes without explicit approval. minimums, rounding, or product modes without explicit approval.
The current site contains four product modes, quality-based price tiers, The Site has four product modes, each with one price per metre (Dropstar,
artwork-ready discounts, separate assembly charges for loose artwork, a 2026-10-23, live in the code since 2026-10-26). It replaced the five-band
one-metre minimum, and ten-centimetre billing rounding. ladder by grade, its "a partir de R$ 14,90" and the separate assembly charge
for loose artwork:
| Product | Ready sheet | Loose artwork |
|---|---:|---:|
| DTF textile, 57 cm | R$ 19,90 | R$ 21,90 |
| UV sticker, 27 cm (Dropstar, 2026-10-28; was 28,5) | R$ 79,90 | R$ 89,90 |
The grade (nota) is still computed and shown, to the customer, on the Kanban
and in Tiny's item note: it explains the file and no longer changes the price.
Artwork below 96 DPI is still refused, and a resolution warning must still be
acknowledged. The server still recomputes the grade from the files at checkout
(`app/grade_check.py`) and holds for review a cart whose grade the files do not
support, so the grade shown stays honest; the review reason "Nota informada sem
análise da arte" existed only to stop a discount and was removed. One-metre
minimum and ten-centimetre billing rounding. The prices are `PRECO` in
`web/site-config.js` and `PRICES` in `app/core/pricing.py`, and
`tests/test_pricing.py` checks they agree; every price on the Site's pages (top
chip, home example, product cards, product selector, price table) is filled
from `PRECO` through `data-preco`.
Customers buy with a CPF (a person) or a CNPJ (a company), check digits
validated on both sides. The value keeps the `cnpj` key in orders, quotes and
accounts; Tiny gets a CPF contact as `tipoPessoa` F, Mercado Pago the matching
identification type, and only CNPJs are looked up in the company registry.
The browser may display the calculation, but production payment creation must The browser may display the calculation, but production payment creation must
recalculate and validate all price, quantity, freight, and discount values on recalculate and validate all price, quantity, and freight values on
the server. Client-provided totals are never authoritative. the server. Client-provided totals are never authoritative.
Normal JPG/PNG uploads are individual artwork by default, including when uploaded Normal JPG/PNG uploads are individual artwork by default, including when uploaded
@@ -158,11 +184,45 @@ from the by-metre panel. They use the existing loose-artwork editor, printed
width, quantity, and live packing canvas; packed height determines metres. width, quantity, and live packing canvas; packed height determines metres.
Customers uploading an already assembled film-width image must explicitly select Customers uploading an already assembled film-width image must explicitly select
the ready-sheet option before uploading. PDF and manual-format ready sheets keep the ready-sheet option before uploading. PDF and manual-format ready sheets keep
their existing workflow. These models retain their separate approved price tiers; their existing workflow. These models keep their separate prices;
image dimensions alone must never classify a normal artwork as a finished sheet. image dimensions alone must never classify a normal artwork as a finished sheet.
A finished sheet someone must open by hand (CDR, AI, PSD, TIFF, or a length the
customer typed) pays the product's price plus `MANUAL_FILE_EXTRA_CENTS` per
metre (2026-10-13, asked at the 7 October meeting to steer customers to PNG).
The production stack sets it to 200, R$ 2,00 a metre (Dropstar, 2026-10-23);
a value set in Portainer overrides it, and it is 0 locally and in CI. The
amount is the client's to set. The Site reads it from `/api/session` and shows
it before checkout (product page, help text, price table);
`app/core/pricing.py` charges it.
What a file is comes from its first bytes, never from its name (Dropstar's
rule D-13, 2026-10-26; a third of their ".cdr" files are PDFs). The Site reads
the first bytes when a file is chosen and renames it to its real extension
(`nomeReal` in web/site-upload.js): a ".cdr" that is a PDF becomes ".pdf" and
is measured and checked as a PDF, without the manual charge; a JPG called
".png" is refused as a JPG, naming the file. The server does the same when it
scans an upload (`real_name` in app/scanning.py) and stores the real name, so
every later decision that reads the name (the manual charge, the JPG refusal,
the grade, the original used as its own print file, the folder file names)
follows the content even if the browser was bypassed. A name its content
agrees with stays: an Illustrator ".ai" is a PDF inside but is still handled
by hand, since one saved without PDF content prints a placeholder page. A file
too large for the antivirus passes when its content is any accepted format.
## Freight ## Freight
**Current (2026-10-15):** the cart quotes every carrier configured at once and
lists the options cheapest first, with the delivery time: Jadlog .PACKAGE
(`app/jadlog.py`) and Correios PAC and SEDEX (`app/correios.py`, Dropstar's
contract 9912551407, card 0076691373), plus pickup in Franca. A carrier that
does not answer is left out; the customer's choice is quoted again by the
server at approval. All carriers price the same package (`app/package.py`: a
base weight per box, a weight per metre, the box's sides, metres per box).
Correios is on when `CORREIOS_CODIGO_ACESSO` is set; `python -m
app.correios_probe` checks the contract's token, codes (03298 PAC, 03220
SEDEX by default), prices and times. The history below is kept as recorded.
The original visual freight flow in `web/index.html` was a stub with only pickup The original visual freight flow in `web/index.html` was a stub with only pickup
functional. The localhost bridge now supports pickup and backend fake freight functional. The localhost bridge now supports pickup and backend fake freight
quotes; there is still no real carrier quotation or production checkout. quotes; there is still no real carrier quotation or production checkout.
@@ -187,6 +247,12 @@ amount is final.
### Mercado Pago ### Mercado Pago
Card payments: up to 3 installments **with interest paid by the customer**;
1x has no interest (Wagner, 2026-10-14). Interest is Mercado Pago's: its card
form shows each option with the rate, and the order checks
`transaction_amount` (the price), not the total with interest. Keep "parcelamento
sem juros" off in the Mercado Pago account, or Dropstar pays the interest.
Required before production payment integration, not for the local mock milestone: Required before production payment integration, not for the local mock milestone:
- Production credentials. - Production credentials.
@@ -202,6 +268,26 @@ Tiny/Olist is already available. The implementation must create/update orders
idempotently and use the order number for traceability. Confirm the actual API idempotently and use the order number for traceability. Confirm the actual API
endpoints, marker/tag behaviour, and rate limits before production use. endpoints, marker/tag behaviour, and rate limits before production use.
### E-mail
`app/mail.py` (2026-10-13): customers' password recovery (a one-time link,
valid one hour, sent to `/conta/redefinir#token`; only the token's hash is
stored and the message text is erased once sent). Since 2026-10-20 the team
gets no alert e-mails: the Kanban and Tiny are where orders are followed.
Messages are queued in the transaction that caused them and
sent by the worker with retries. `MAIL_ADAPTER` is `off` in production until
the client's SMTP account exists (recovery then offers WhatsApp), `log` on the
local stack, `smtp` with `SMTP_*` and `MAIL_FROM`.
Signup (2026-10-14): with e-mail on, an account is created only after the
6-digit code e-mailed to the address is entered (15 minutes, 5 wrong attempts,
a new code after 60 s, at most 5). The password is hashed at the first step
and the code stored only as a hash. The answer is the same for an address that
already has an account: it gets a "você já tem conta" notice instead of a code.
Changing the account's e-mail works the same way: the code goes to the new
address, the e-mail changes only once it is entered, and the old address is
told. Production sends through the client's Locaweb SMTP (set in the stack).
### WhatsApp ### WhatsApp
WhatsApp is already available, but the technical provider still needs to be WhatsApp is already available, but the technical provider still needs to be
@@ -245,6 +331,204 @@ supports subsequent corrections or scoped enhancements.
## Known implementation status ## Known implementation status
### Launch status (2026-10-19)
Live on dropstardtf.com.br (Site) and kanban.dropstardtf.com.br (Kanban), with
Mercado Pago in production, Correios PAC/SEDEX and Jadlog, SMTP e-mail and the
daily R2 backup. The system sends no WhatsApp: the client's n8n does, from
Tiny's situação (middleware in the separate api-tiny-n8n project). Tiny orders
are filled in as the store's own (app/tiny.py: payment, carrier, expected
date), with Dropstar's ids where the app may not list them.
Before go-live: Dropstar's category, seller and tag for Site orders in Tiny; a
supervised test order (`python -m app.tiny_probe pedido ... --confirmar`); the
n8n "isDTFIMP" node skipping orders whose numero_ecommerce starts with "DTF-";
then TINY_STATUS_UPDATES=true and TINY_ADAPTER=tiny, a backup,
`ops.launch_reset`, a real Pix and card payment refunded, and the pilot with
5 to 10 customers. The guides' screenshots are reproducible from
docs/guias/telas/.
### Kanban automatic folder (agreed in the 2026-10-07 meeting)
Dropstar's three folders (asked 2026-10-23, agreed 2026-10-26): the Kanban,
open in Chrome or Edge on a factory computer that reaches the server's
folder, signed in with a profile that sees every order (Gestão), keeps the
orders' files in three folders it creates inside the one chosen in
Integrações ("Pastas dos pedidos"), numbered to sort in the flow's order:
"1. Arte recebida" (the file arrives when the order does), "2. Arte
conferida" (the queue; the file moves there with the card and stays while it
prints and is checked in Revisão) and "3. Finalizado" (when the order is
released, kept 30 days there). They are created as soon as the main folder
is chosen. 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; every order paid after
it is, whatever its stage, so a computer that was off catches up when it
comes back (Dropstar's rules, 2026-10-26: the folder must reproduce what
passed, not only what sits in the columns). A file someone took
out is fetched again only when its order moves on (`POST
/api/operator/queue/folder`, which also returns the files of orders the
folders hold once they print). Who opens each folder is set in the server's
folder permissions. Firefox cannot write into folders: it only downloads the
files entering Arte conferida.
Integrações (2026-10-20): only the superadmin (us) has the buttons, the
details and the Tiny log there (`integrations` capability, app/core/auth.py).
Admins and gestão see each integration's state and summary; anyone who
produces also gets the folder's row with its buttons.
Machines (2026-10-20, app/machines.py): each order keeps one machine, either
chosen in the order panel or given on arrival: the active machine of its
product with the fewest metres open (rec, tra, imp, cor), preferring
those below their optional limit in metres, else the least loaded anyway (the
Usuários page shows it over the limit). A machine switched off, deleted or no
longer printing the product hands its automatic orders, not yet printing, to
that choice again. Only operators are linked to machines (from the user or
the machine form); a linked operator sees only those machines' orders.
Dropstar's corrections of 2026-10-21 already done: the home example priced as
a ready sheet; opening hours 7h to 18h with "send your art any time"; uploads
up to 1 GB (MAX_UPLOAD_BYTES; Dropstar moved it to 4 GB on 2026-10-28: ClamAV scans
up to its 2000 MiB, a larger file passes by the format check); a Designer profile
(artwork stages only, every order, no machine, queue or cancelling; MOVES
in app/core/auth.py, the "print" capability for the room's side); Números by date range, per machine (metres finished, metres per hour
in Imprimindo, last finished, now) and orders apart from passages. A machine's
metres are the film printed (item `metres`), never the billed ones, and time
two orders spent in Imprimindo together counts once; a stage's median is per
order, the sum of its passages. Layout version 3 (web/site-packing.js): rows
with exact sizes, 5 mm margins top and bottom and between rows, and across
the width 5 mm or the space left shared out equally (1,5 mm at least); the
shape packing is used only when it saves 1 cm or more. A ready sheet with a
residue (ink under 2 mm on both sides, measured in pixels from the ink map in
web/site-sheet.js) or without transparency (under 1,5 % of transparent
pixels; every JPG) cannot be paid for; the preview circles each dot. PDFs
over 150 MB and CDR/AI/PSD/TIFF are not checked. The generated print PDF ends
in a 1,5 cm footer band below the layout, outside the billed length: "DROPSTAR
· Pedido DTF-<Kanban number> · Item 1/2 · date · billed metres" in black
Helvetica, after Dropstar's logo (app/assets), about 1 cm tall (31 pt, Dropstar
2026-10-28; smaller only when it would not fit the 27 cm UV film). A sheet
longer than 5,08 m (Acrobat's page limit) is written at its real size on one
page since 2026-10-28: with PDF's /UserUnit scale, CorelDRAW, where Dropstar
checks files, showed a 12,8 m sheet as 18,9 x 425 cm. PRINT_PAGE_SCALE=true
in the stack goes back to /UserUnit, for a RIP that refuses pages over 5,08 m. An original used whole as its
own print file (over 300 MB) has no footer. The print proof (app/proof.py):
an order above 10 m, or one whose customer ticked "quero aprovar uma prova" at
checkout (that one arrives marked Aguardando contato; the box shows, and the
server keeps it, only above 10 m since 2026-10-28), cannot reach Finalizado
before the print room marks Prova OK; the proof is not billed (up to 30 cm,
at most 3 per order). Dropstar's answers of 2026-10-23: JPG is refused in every
product; a PDF over 150 MB is flagged before payment; any non-square piece is
tried both ways; a mirrored (UV) order is flagged on the card and in the PDF
footer; files are named DTF-<number>-item-<n>, the code the Kanban copies;
manual files cost R$ 2,00 more a metre. Also settled by Dropstar on
2026-10-23: no seller on Tiny orders (Tiny sets it from the contact; the
marcador SITE DTF separates the channel), the DTF terms page approved, the UV
mirror stays, the designer does not move to the print queue, and Aguardando
contato has no deadline of its own. There is no videocall: open points are
settled in writing.
Done on 2026-10-26: the single price per product Dropstar asked for on
2026-10-23 (see Commercial rules), on the Site and the server.
Dropstar's flow of 2026-10-23, in the code since 2026-10-26 (app/runtime.py,
app/core/auth.py): the board is Arte recebida, Arte conferida, Imprimindo,
Correção, Revisão, Finalizado. Fila de impressão left: Arte conferida is the
queue, entered only with every item's final file approved, kept as approved
there (to change one, the order goes back to Arte recebida), with its card
order as the print order and "Baixar" for the room; orders that were in the
queue were moved to Arte conferida with a line in their history. Who moves
what (MOVES): the Designer Arte recebida to Arte conferida, asks for
corrections and brings the new art back to Arte recebida or Arte conferida;
the Operador Arte conferida to Imprimindo to Revisão; the Revisor Revisão to
Finalizado, so nobody in the room releases their own print, and the
Administrador may release too (the user, 2026-10-28; the superadmin for
support); Gestão, the coordination, only pulls back, always with a reason
(rule D-20 of Dropstar's internal rules, 2026-10-26): Correção from any
stage, or a step back; Admin, Dropstar's own login, every other move,
including Correção straight to Revisão. A step back belongs to whoever makes
the move it undoes, and to Admin and Gestão. Tiny: Arte
conferida sets "Preparando envio" and Finalizado "Pronto para envio", for
delivery orders too; nothing for Imprimindo, Correção or Revisão. Prova OK
still comes before Finalizado. The customer's portal shows the same steps.
Still to do (2026-10-26):
- The DTF number in Tiny's `numeroPedidoEcommerce`: sent since 2026-10-26,
next to the purchase order `numeroOrdemCompra` (which the resend check
searches). Tiny keeps it only with a channel: `TINY_ECOMMERCE_ID=9594`,
Dropstar's "API do ERP" integration (installed 2026-10-27). The store's own
channel (DROPSTAR, 9336) refuses orders sent through the API. Confirmed
with test order 145329.
- Before TINY_STATUS_UPDATES goes on: Finalizado now sets "Pronto para
envio" on delivery orders too, so the client's n8n must not send them the
pickup message it sends on that situação.
- Dropstar creates the Revisor users right after the redeploy that brings the
new flow (the profile exists only from then): until then orders wait in
Revisão, and only the superadmin can release them.
- Done 2026-10-27, from Dropstar's answers on their internal rules: "Arte
tratada", an order whose approved final is not the customer's art (not the
file generated from it, not an original, not a correction they sent), is
flagged on the card and in the order, and Números counts those orders by who
approved the final, for the designer's productivity; a cancelled order's
money stays as the customer's credit in their financial control (D-15, the
Kanban's cancel text says so, nothing on the Site); the Kanban keeps
deleting Finalizado files after 30 days; the footer gets the white spot.
- Every order has an origin (Dropstar's rules D-21 and D-35, 2026-10-26):
`site`, `dropflow` or `atendimento`, in dtf_local.orders.origin, required
and without a default (a default would become the origin of almost
everything, the document says), limited to the three by a check. The Site's
orders are marked `site` where they are created (app/payments.py); the
orders from before the column became `site`. The Kanban shows it on every
card and in the order panel, filters by it (Origem), and Números has a "Por
origem" table: orders, metres, money received and the median time from
payment to Finalizado for each way in, Aguardando contato left out.
- An order paid outside the system is registered from its Site quote (D-35;
the user's answers of 2026-10-27): the team builds the cart on the Site as
a customer would (the art comes in through the Site, D-08), stops at the
payment step, and in the Kanban's Cotações, on the approved quote, picks the
origin and how it was paid (Pix, cartão, dinheiro, crédito do cliente),
neither preselected, with an optional note. The price is the quote's, the
Site's table price. Allowed to Administrador and Gestão (the "enter"
capability); not Vendedor, who only views the board (D-30). The order's payment is `{'provider': 'manual',
'method', 'note', 'operator'}`; it counts in Números like any paid order and
the customer gets the usual paid e-mail. An Atendimento (or Site) order
goes to Tiny like a Site one, its internal note saying "pago fora do site"
and how, each way named as Tiny's forma de recebimento (Pix, cartão, and
from Marcus on 2026-10-27 Dinheiro 919478944 and, for the customer's credit,
their "CORREÇÃO DTF" 977493654; RECEIPT_METHODS in app/tiny.py). A Dropflow
order goes to Tiny too, in its own revenue category "DTF DROPFLOW"
(987032506, CATEGORIES in app/tiny.py), not DTF SITE (D-21).
- Rework register (Dropstar's rules D-02 to D-04; the user's answers of
2026-10-27), dtf_local.reworks. Gestão opens it from the order panel's menu
("Abrir retrabalho") with its cause, the metres redone (the order's printed
metres to start) and a note: falha de impressão, perfil de cor, erro de
tratamento, erro de pedido, or arte aprovada pelo cliente (outside the
goal, D-04). The cause never changes after (D-03: there is no route for it).
An Administrador authorizes it or declines it with a reason, never one they
opened; the reprint is never held up, and only an authorized rework counts.
Who printed it (who last sent the order to Revisão) is kept, as the house's
rework enters the printer's pay. Números, "Retrabalho": per cause, the
metres redone over the film printed in the period (Por máquina), by the day
the rework was opened, against 0,4% per cause and 1,6% for the house; the
house's by who printed it; and the ones waiting for authorization. A card
with a rework carries a "Retrabalho" badge.
- Still open from the internal rules (docs received 2026-10-26): customer
credit as a payment the system keeps track of (today "crédito do cliente"
is only how a registered order was paid). Done 2026-10-27: the folders catch up on what passed while the Kanban
computer was off, time in "Aguardando contato" no longer counts in Números'
time figures (D-38; each wait is kept in dtf_local.contact_waits, from mark
to clear), and a file's type comes from its first bytes (D-13, see the
commercial rules).
- Settled on 2026-10-26: the DTF SITE category (986932924, CATEGORY in app/tiny.py),
the white spot also under the print PDF's footer (nothing to change here),
and the montador's order format (customer, files, product, the batch with
the customer's ERP sale numbers, labels or pickup) with a record of each
batch, both for after launch.
- The three folders, once deployed: Marcus sets the main folder on the
factory computer (Chrome, Integrações > Pastas dos pedidos); check on the
first print whether FlexiPRINT keeps reading the file in Arte conferida
after import (the file only leaves that folder at Finalizado).
- Anchor-customer orders from the montador: after the launch; the team's idea
is that Graphs handles that side and sends the orders to this Kanban.
### Active localhost milestone (2026-09-15) ### Active localhost milestone (2026-09-15)
The current implementation target is localhost before any production connection. The current implementation target is localhost before any production connection.
@@ -258,7 +542,7 @@ as references and are not imported or started by Compose.
jobs provision restricted runtime identities, for nine Compose services total. jobs provision restricted runtime identities, for nine Compose services total.
- MinIO implements the S3 storage boundary with direct multipart browser uploads, - MinIO implements the S3 storage boundary with direct multipart browser uploads,
resumable parts, private objects, and short-lived signed operator downloads. resumable parts, private objects, and short-lived signed operator downloads.
- Payment, freight, Tiny/Olist, and WhatsApp use fake adapters only. No production - Payment, freight, and Tiny/Olist use fake adapters only. No production
credentials or integrations are configured. The API and worker have no external credentials or integrations are configured. The API and worker have no external
network route; only local web/storage gateways publish loopback ports. network route; only local web/storage gateways publish loopback ports.
- The original Site commercial calculation and appearance remain the source of - The original Site commercial calculation and appearance remain the source of
@@ -272,15 +556,17 @@ as references and are not imported or started by Compose.
one-metre minimum, ten-centimetre rounding, freight, and final totals. Immutable one-metre minimum, ten-centimetre rounding, freight, and final totals. Immutable
approved quotes expire after 24 hours. A customer confirms the server total approved quotes expire after 24 hours. A customer confirms the server total
on the Site to create one idempotent local paid order. on the Site to create one idempotent local paid order.
- Paid orders use `rec`, `tra`, `fil`, `imp`, `cor`, `fin`, with allowed transitions, - Paid orders use `rec`, `tra`, `imp`, `cor`, `rev`, `fin` (`fil` until 2026-10-26), with allowed transitions,
operator authentication, concurrency checks, and durable movement history. operator authentication, concurrency checks, and durable movement history.
Local mock integration receipts are visible in the Kanban. Local mock integration receipts are visible in the Kanban.
- The customer portal at `/portal.html` supports local registration/login, - The customer portal at `/portal.html` supports local registration/login,
stronger scrypt password hashing with legacy-hash upgrade, revocable HttpOnly stronger scrypt password hashing with legacy-hash upgrade, revocable HttpOnly
sessions, owned order history/status, secure active sessions, owned order history/status, secure active
file downloads, and correction uploads. Registration/login can claim only the file downloads, and correction uploads. Registration/login claims the current
current guest session's records, never orders found by email or CNPJ. Email guest session's records and, once the account's e-mail is confirmed with a
verification and password recovery are not implemented. code, every guest order placed with the account's CPF/CNPJ and e-mail
together, from any browser; never by CPF/CNPJ alone. Signup and e-mail
changes are confirmed by an e-mailed code; password recovery by a link.
- Unfinished carts (including File blobs) recover from IndexedDB for 24 hours in - Unfinished carts (including File blobs) recover from IndexedDB for 24 hours in
the same browser, scoped to the guest/account identity. Recovered items can be the same browser, scoped to the guest/account identity. Recovered items can be
removed/replaced or joined by new items; in-place reconstruction of the artwork removed/replaced or joined by new items; in-place reconstruction of the artwork
@@ -370,8 +656,9 @@ referenced them; recover from Git history if ever needed.
authentication, purchase history, or real cart persistence. Local order authentication, purchase history, or real cart persistence. Local order
persistence, reviewed quotes, mock freight and fake payment now work through persistence, reviewed quotes, mock freight and fake payment now work through
`web/checkout.js`. The local customer portal now provides accounts and `web/checkout.js`. The local customer portal now provides accounts and
order history; cart recovery is browser-local. Production account verification, order history; cart recovery is browser-local. Password recovery by e-mail
recovery, and cross-device cart editing are still absent. exists (see E-mail) but waits for the client's SMTP account; account e-mail
verification and cross-device cart editing are still absent.
- Without the local bridge, the original freight fallback remains a stub. - Without the local bridge, the original freight fallback remains a stub.
Real freight quotation remains unimplemented in all runtimes. Real freight quotation remains unimplemented in all runtimes.
- The existing the removed prototypes duplicated WhatsApp senders and send - The existing the removed prototypes duplicated WhatsApp senders and send

View File

@@ -71,7 +71,7 @@ operator interfaces.
payment occurs. payment occurs.
7. Click **Atualizar** on the Kanban. The paid order appears in **Arte 7. Click **Atualizar** on the Kanban. The paid order appears in **Arte
recebida** on the **Produção** tab. Click its card to open the order panel, recebida** on the **Produção** tab. Click its card to open the order panel,
then **Mover para Arte tratada** (dragging the card to a column also works). then **Mover para Arte conferida** (dragging the card to a column also works).
In the panel's **Arquivos finais**, select the manually prepared final file In the panel's **Arquivos finais**, select the manually prepared final file
for every item, enter a review note, tick the confirmation and click for every item, enter a review note, tick the confirmation and click
**Aprovar arquivos finais**. Use the harmless fixture again only for this **Aprovar arquivos finais**. Use the harmless fixture again only for this
@@ -80,7 +80,7 @@ operator interfaces.
preselected instead (see "Print files"). Continue with the panel's main preselected instead (see "Print files"). Continue with the panel's main
button through **Fila de impressão → Imprimindo → Finalizado**. **Pedir button through **Fila de impressão → Imprimindo → Finalizado**. **Pedir
correção** asks for the reason the customer will see; from **Correção** the correção** asks for the reason the customer will see; from **Correção** the
order returns to **Arte recebida** or **Arte tratada**. A move made by order returns to **Arte recebida** or **Arte conferida**. A move made by
mistake is undone with **Voltar para …**: one stage back, with an internal mistake is undone with **Voltar para …**: one stage back, with an internal
reason recorded in the history. The customer is not notified, approved reason recorded in the history. The customer is not notified, approved
finals stay, and "produção iniciada"/"pedido pronto" are sent only once per finals stay, and "produção iniciada"/"pedido pronto" are sent only once per
@@ -109,7 +109,7 @@ final files are separately labeled. Never print the local text fixture.
## Customer accounts, corrections, and cart recovery ## Customer accounts, corrections, and cart recovery
Open **Minha conta** on the Site, or `/portal.html`. Create a local account with Open **Minha conta** on the Site, or `/portal.html`. Create a local account with
a test CNPJ, phone, email and password of at least 12 characters. Passwords use a test CNPJ, phone, email and password of at least 8 characters. Passwords use
the current stronger scrypt format; legacy local hashes are verified and upgraded the current stronger scrypt format; legacy local hashes are verified and upgraded
on successful login. Sessions are stored in PostgreSQL, expire after on successful login. Sessions are stored in PostgreSQL, expire after
seven days, and are revoked on logout. Login/registration attempts are limited. seven days, and are revoked on logout. Login/registration attempts are limited.

View File

@@ -190,6 +190,39 @@ It refuses if any payment was made with real money. Order numbers restart at
run in the `db` container's console. Add `--contas` to remove the test run in the `db` container's console. Add `--contas` to remove the test
customer accounts too. customer accounts too.
## 7. E-mail and prices set in the stack
E-mail stays off (`MAIL_ADAPTER=off`) until the client's SMTP account exists.
Then set, in the stack's environment, `MAIL_ADAPTER=smtp`, `MAIL_FROM` (for
example `DTF Dropstar <nao-responda@SITE_DOMAIN>`), `SMTP_HOST`, `SMTP_PORT`,
`SMTP_SECURITY` (`starttls` on 587, `ssl` on 465), `SMTP_USER` and
`SMTP_PASSWORD`, and redeploy; the API and worker refuse to start if a required
one is missing. Check it with **Integrações → E-mail → Enviar teste** on the
Kanban, then switch on "Receber alertas por e-mail" for whoever wants alerts in
Usuários. Use a sending domain with SPF and DKIM, or the messages land in spam.
`MANUAL_FILE_EXTRA_CENTS` is the per-metre charge on finished sheets someone
opens by hand (CDR, AI, PSD, TIFF). The default is 200, R$ 2,00 a metro
(Dropstar, 2026-10-23); a value set in the stack's environment overrides it.
Change it only on the client's instruction; the Site shows the new price after
the redeploy.
## 8. Correios
PAC and SEDEX appear in the cart once `CORREIOS_CODIGO_ACESSO` (the CWS access
code, a secret) is set in the stack and the stack redeployed. The user, posting
card and contract are Dropstar's and already the stack's defaults. Then, from
the worker's console:
```bash
python -m app.correios_probe
```
It shows the token's contract and DR and prices PAC and SEDEX to a few CEPs.
If a service is refused, the contract uses other codes: set `CORREIOS_COD_PAC`
or `CORREIOS_COD_SEDEX`. Correios price by the box, so `JADLOG_CAIXA_CM` and the
package weights must be set (they already are for Jadlog).
## Current blocker ## Current blocker
This is the final deployment shape, but it is not authorized for production This is the final deployment shape, but it is not authorized for production

View File

@@ -847,6 +847,8 @@ print-file evidence still need correction before this item can close.
where a server-side packer (3.2) has to agree, which was the point of splitting. where a server-side packer (3.2) has to agree, which was the point of splitting.
- `[ ]` 5.7 — Commercial rules duplicated between `FAIXAS` (JS) and `TIERS` (Python) - `[ ]` 5.7 — Commercial rules duplicated between `FAIXAS` (JS) and `TIERS` (Python)
`(F26)`. `test_pricing` guards parity; generate one from the other instead. `(F26)`. `test_pricing` guards parity; generate one from the other instead.
2026-10-26: one price per product now, `PRECO` (JS) and `PRICES` (Python);
`test_pricing` still guards parity.
- `[ ]` 5.11 — Nothing tests the schema against an empty database. The 4.1 indexes - `[ ]` 5.11 — Nothing tests the schema against an empty database. The 4.1 indexes
were added next to the existing one, which sits before the tables they name, so were added next to the existing one, which sits before the tables they name, so
`CREATE INDEX ... ON dtf_local.order_files` ran before that table existed. Every `CREATE INDEX ... ON dtf_local.order_files` ran before that table existed. Every

Binary file not shown.

Binary file not shown.

View File

@@ -73,10 +73,10 @@
<p class="lead">Como conferir, produzir e entregar os pedidos que chegam pelo Site DTF.</p> <p class="lead">Como conferir, produzir e entregar os pedidos que chegam pelo Site DTF.</p>
<table> <table>
<tr><th style="width:50%">Acesso</th><th>Quem usa</th></tr> <tr><th style="width:50%">Acesso</th><th>Quem usa</th></tr>
<tr><td>dtf.kanban.agenciacompor.com.br<br>e-mail e senha do operador</td> <tr><td>kanban.dropstardtf.com.br<br>e-mail e senha do operador</td>
<td>Equipe da sala de DTF e atendimento</td></tr> <td>Equipe da sala de DTF e atendimento</td></tr>
</table> </table>
<p class="version">Versão de 5 de outubro de 2026</p> <p class="version">Versão de 19 de outubro de 2026</p>
</div> </div>
</section> </section>
@@ -94,24 +94,29 @@
<td>O Site confere a nota pelos próprios arquivos e aprova na hora. Só vão para a equipe os pedidos acima de <td>O Site confere a nota pelos próprios arquivos e aprova na hora. Só vão para a equipe os pedidos acima de
50 m ou com nota que não confere (aba <b>Cotações</b>).</td></tr> 50 m ou com nota que não confere (aba <b>Cotações</b>).</td></tr>
<tr><td class="n">3</td><td class="k">Cliente paga</td> <tr><td class="n">3</td><td class="k">Cliente paga</td>
<td>Pelo Mercado Pago, com cartão de crédito ou PIX, na própria página do Site.</td></tr> <td>Pelo Mercado Pago, com PIX ou cartão de crédito (à vista ou em até 3 vezes), na própria página do Site.</td></tr>
<tr><td class="n">4</td><td class="k">Pedido entra na produção</td> <tr><td class="n">4</td><td class="k">Pedido entra na produção</td>
<td>Com o pagamento aprovado, o pedido aparece em <b>Arte recebida</b>, com o arquivo de impressão já gerado.</td></tr> <td>Com o pagamento aprovado, o pedido aparece em <b>Arte recebida</b>, com o arquivo de impressão já gerado, e é
lançado no Tiny. O cliente recebe a confirmação por e-mail e por WhatsApp.</td></tr>
<tr><td class="n">5</td><td class="k">Equipe produz</td> <tr><td class="n">5</td><td class="k">Equipe produz</td>
<td>Confere e aprova o arquivo final, baixa, importa no FlexiPRINT e move o card a cada etapa.</td></tr> <td>Confere e aprova o arquivo final, baixa, importa no FlexiPRINT e move o card a cada etapa.</td></tr>
<tr><td class="n">6</td><td class="k">Pedido pronto</td> <tr><td class="n">6</td><td class="k">Pedido pronto</td>
<td>Em <b>Finalizado</b>, o pedido fica pronto para retirada e o cliente é avisado (página 7).</td></tr> <td>Em <b>Finalizado</b>: na retirada, o cliente é avisado; na entrega, a equipe fatura e despacha pelo Tiny, como
nos outros pedidos (página 7).</td></tr>
</table> </table>
<h2>As cinco abas</h2> <h2>As seis abas</h2>
<table> <table>
<tr><th style="width:31mm">Aba</th><th>Para que serve</th></tr> <tr><th style="width:31mm">Aba</th><th>Para que serve</th></tr>
<tr><td class="k">Produção</td><td>O quadro com os pedidos pagos, uma coluna por etapa.</td></tr> <tr><td class="k">Produção</td><td>O quadro com os pedidos pagos, uma coluna por etapa.</td></tr>
<tr><td class="k">Cotações</td><td>Carrinhos que ainda não foram pagos: os que esperam a equipe conferir e os aprovados <tr><td class="k">Cotações</td><td>Carrinhos que ainda não foram pagos: os que esperam a equipe conferir e os aprovados
esperando o pagamento. O número ao lado indica quantos faltam revisar.</td></tr> esperando o pagamento. O número ao lado indica quantos faltam revisar.</td></tr>
<tr><td class="k">Pagamentos</td><td>Pagamentos que o sistema não conseguiu ligar a um pedido. Normalmente fica vazia.</td></tr> <tr><td class="k">Pagamentos</td><td>Pagamentos que o sistema não conseguiu ligar a um pedido. Normalmente fica vazia.</td></tr>
<tr><td class="k">Números</td><td>Pedidos, metros, valores e o tempo de cada etapa no período (página 9).</td></tr> <tr><td class="k">Números</td><td>Pedidos, metros, valores e o tempo de cada etapa no período (página 10).</td></tr>
<tr><td class="k">Integrações</td><td>Situação do Tiny, Mercado Pago, frete, WhatsApp e cópia de segurança, e o registro do que foi enviado ao Tiny.</td></tr> <tr><td class="k">Integrações</td><td>A pasta automática da Fila de impressão (página 9) e a situação do Tiny, Mercado Pago,
frete, e-mail e cópia de segurança (página 12).</td></tr>
<tr><td class="k">Usuários</td><td>Quem entra no Kanban, o perfil de cada um e as máquinas (página 11).</td></tr>
</table> </table>
<p>Cada pessoa vê as abas do seu perfil: o operador, por exemplo, vê <b>Produção</b> e, em <b>Integrações</b>, só a pasta automática.</p>
<div class="note">O quadro se atualiza sozinho, de 30 em 30 segundos. No canto superior direito, ao lado de <div class="note">O quadro se atualiza sozinho, de 30 em 30 segundos. No canto superior direito, ao lado de
<b>Atualizar</b>, dá para escolher outro intervalo (de 10 segundos a 15 minutos) ou desligar. Quando chega um pedido <b>Atualizar</b>, dá para escolher outro intervalo (de 10 segundos a 15 minutos) ou desligar. Quando chega um pedido
novo, aparece o aviso <b>Novo pedido #</b> e o título da aba mostra quantos chegaram.</div> novo, aparece o aviso <b>Novo pedido #</b> e o título da aba mostra quantos chegaram.</div>
@@ -125,9 +130,11 @@
<h1>Entrar e ler o quadro</h1> <h1>Entrar e ler o quadro</h1>
<div class="split"> <div class="split">
<div> <div>
<p>Acesse <b>dtf.kanban.agenciacompor.com.br</b> e entre com seu e-mail e senha. Cada operador tem o próprio <p>Acesse <b>kanban.dropstardtf.com.br</b> e entre com seu e-mail e senha. Cada operador tem o próprio
acesso: é o nome dele que fica registrado em cada movimento do pedido.</p> acesso: é o nome dele que fica registrado em cada movimento do pedido.</p>
<p>Depois de várias senhas erradas seguidas, o acesso fica bloqueado por 15 minutos.</p> <p>Depois de várias senhas erradas seguidas, o acesso fica bloqueado por 15 minutos.</p>
<p>Para trocar a sua senha, clique nas suas iniciais, no canto superior direito, e em <b>Minha senha</b>. Esqueceu?
Peça a um administrador uma senha nova (página 11).</p>
</div> </div>
<div class="side"><img class="shot" src="img/login.png" alt="Tela de entrada do Kanban"></div> <div class="side"><img class="shot" src="img/login.png" alt="Tela de entrada do Kanban"></div>
</div> </div>
@@ -136,15 +143,16 @@
<h2>O que cada card mostra</h2> <h2>O que cada card mostra</h2>
<ul> <ul>
<li>A arte, o <b>#número</b> do pedido e há quanto tempo ele mudou de etapa.</li> <li>A arte, o <b>#número</b> do pedido e há quanto tempo ele mudou de etapa.</li>
<li>O nome da empresa (do cadastro do CNPJ) e o e-mail; a nota da arte, o produto e os metros cobrados.</li> <li>O nome do cliente e o e-mail; a nota da arte, o produto e os metros cobrados.</li>
<li><span class="chip">Retirada em Franca</span> ou a cidade da entrega.</li> <li><span class="chip">Retirada em Franca</span> ou a cidade da entrega, e a máquina que vai imprimir.</li>
<li>O que falta: <span class="chip">Falta aprovar o final</span>, <span class="chip">Correção recebida</span>, <li>O que falta: <span class="chip">Falta aprovar o final</span>, <span class="chip">Correção recebida</span>,
<span class="chip">Preparar à mão</span> ou, quando está tudo certo, <span class="chip">Final aprovado</span>. <span class="chip">Preparar à mão</span> ou, quando está tudo certo, <span class="chip">Final aprovado</span>.
<span class="chip">Parado</span> aparece quando o pedido fica mais de 4 h na mesma etapa.</li> <span class="chip">Parado</span> aparece quando o pedido fica mais de 4 h na mesma etapa, e
<span class="chip">☎ Aguardando contato</span> quando a equipe precisa falar com o cliente antes de imprimir (página 8).</li>
</ul> </ul>
<p>Os filtros mostram só <b>Têxtil</b>, <b>UV</b>, <b>Entrega</b>, <b>Retirada</b>, <b>Parados</b>, <b>Preparar à mão</b> <p>Os filtros mostram só <b>Têxtil</b>, <b>UV</b>, <b>Entrega</b>, <b>Retirada</b>, <b>Parados</b>, <b>Aguardando contato</b>,
ou <b>Cancelados</b>. A busca (atalho <b>/</b>) encontra pedidos e cotações pelo nome da empresa, e-mail, CNPJ, <b>Preparar à mão</b> ou <b>Cancelados</b>. A busca (atalho <b>/</b>) encontra pedidos e cotações pelo nome, e-mail,
WhatsApp, número ou código do pedido.</p> CPF ou CNPJ, WhatsApp, número ou código do pedido.</p>
<div class="folio">Página 3</div> <div class="folio">Página 3</div>
</section> </section>
@@ -184,8 +192,9 @@
<tr><th style="width:27mm">Parte</th><th>O que tem</th></tr> <tr><th style="width:27mm">Parte</th><th>O que tem</th></tr>
<tr><td class="k">Topo</td><td>Número, etapa, código do pedido (o que o cliente vê), valor e data do pagamento, <tr><td class="k">Topo</td><td>Número, etapa, código do pedido (o que o cliente vê), valor e data do pagamento,
o próximo passo e os botões. Em <b>⋯</b> ficam ações raras, como cancelar o pedido.</td></tr> o próximo passo e os botões. Em <b>⋯</b> ficam ações raras, como cancelar o pedido.</td></tr>
<tr><td class="k">Cliente e Entrega</td><td>Empresa, e-mail, CNPJ e <b>Abrir conversa</b> no WhatsApp; <tr><td class="k">Cliente e Entrega</td><td>Nome, e-mail, CPF ou CNPJ e <b>Abrir conversa</b> no WhatsApp;
endereço ou <b>Retirada em Franca</b>.</td></tr> endereço, transportadora e valor do frete, ou <b>Retirada em Franca</b>.</td></tr>
<tr><td class="k">Máquina</td><td>A máquina que vai imprimir, escolhida pelo produto. Dá para trocar por outra.</td></tr>
<tr><td class="k">Item</td><td>A arte e a montagem no filme, folha, peças e preço do metro. <b>PDF</b> ou <tr><td class="k">Item</td><td>A arte e a montagem no filme, folha, peças e preço do metro. <b>PDF</b> ou
<b>Original</b> baixam os arquivos; <b>Manifesto</b> lista as peças e suas posições.</td></tr> <b>Original</b> baixam os arquivos; <b>Manifesto</b> lista as peças e suas posições.</td></tr>
<tr><td class="k">Arquivos finais</td><td>As versões do arquivo que vai ser impresso, com quem aprovou e quando.</td></tr> <tr><td class="k">Arquivos finais</td><td>As versões do arquivo que vai ser impresso, com quem aprovou e quando.</td></tr>
@@ -202,8 +211,8 @@
<div class="running">DTF Dropstar - guia do operador</div> <div class="running">DTF Dropstar - guia do operador</div>
<p class="kicker">PRODUÇÃO</p> <p class="kicker">PRODUÇÃO</p>
<h1>Aprovar o arquivo final</h1> <h1>Aprovar o arquivo final</h1>
<p>Antes de ir para a <b>Fila de impressão</b>, cada item precisa de um arquivo final aprovado. Enquanto falta, o topo <p>Antes de ir para a <b>Fila de impressão</b>, cada item precisa de um arquivo final aprovado. Em <b>Arte conferida</b>,
do pedido mostra <b>Próximo passo: aprovar o arquivo final</b>, com o arquivo que vai ser impresso.</p> enquanto falta, o topo do pedido mostra <b>Próximo passo: aprovar o arquivo final</b>, com o arquivo que vai ser impresso.</p>
<img class="shot narrow" src="img/arquivo-final.png" alt="Próximo passo: aprovar o arquivo final"> <img class="shot narrow" src="img/arquivo-final.png" alt="Próximo passo: aprovar o arquivo final">
<ol> <ol>
<li>Clique em <b>Baixar</b> e confira o arquivo.</li> <li>Clique em <b>Baixar</b> e confira o arquivo.</li>
@@ -218,7 +227,8 @@
<tr><td><span class="chip">Gerando arquivo…</span></td><td>Aguarde alguns segundos: o quadro se atualiza sozinho.</td></tr> <tr><td><span class="chip">Gerando arquivo…</span></td><td>Aguarde alguns segundos: o quadro se atualiza sozinho.</td></tr>
<tr><td><span class="chip">Preparar à mão</span></td><td>O cliente enviou um formato que o gerador não lê (CDR, AI, PSD) <tr><td><span class="chip">Preparar à mão</span></td><td>O cliente enviou um formato que o gerador não lê (CDR, AI, PSD)
ou um arquivo muito grande para montar. O botão laranja vira <b>Enviar arquivo final</b>: baixe o <b>Original</b>, ou um arquivo muito grande para montar. O botão laranja vira <b>Enviar arquivo final</b>: baixe o <b>Original</b>,
prepare o arquivo no seu programa e envie por ali.</td></tr> prepare o arquivo no seu programa e envie por ali. Quando a Dropstar cobra a abertura manual, o <b>Metro</b> do item
mostra o valor (ex.: <span class="chip">R$ 24,90 (com R$ 5,00 de arquivo manual)</span>).</td></tr>
<tr><td><span class="chip">Falhou ao gerar</span></td><td>Clique em <b>Gerar de novo</b>. Se falhar de novo, prepare à mão.</td></tr> <tr><td><span class="chip">Falhou ao gerar</span></td><td>Clique em <b>Gerar de novo</b>. Se falhar de novo, prepare à mão.</td></tr>
</table> </table>
<div class="folio">Página 6</div> <div class="folio">Página 6</div>
@@ -232,22 +242,24 @@
<p>Use o botão laranja <b>Mover para…</b> no topo do painel ou arraste o card para a coluna seguinte. Dentro da <p>Use o botão laranja <b>Mover para…</b> no topo do painel ou arraste o card para a coluna seguinte. Dentro da
mesma coluna, arraste o card para cima ou para baixo para mudar a prioridade na fila.</p> mesma coluna, arraste o card para cima ou para baixo para mudar a prioridade na fila.</p>
<table> <table>
<tr><th style="width:27mm">Etapa</th><th>Significa</th><th style="width:43mm">Aviso ao cliente</th></tr> <tr><th style="width:27mm">Etapa</th><th>Significa</th><th style="width:30mm">No Tiny</th><th style="width:40mm">Aviso ao cliente</th></tr>
<tr><td class="k">Arte recebida</td><td>Pedido pago, arquivo gerado. Ainda não conferido.</td><td>Pedido aprovado (automático)</td></tr> <tr><td class="k">Arte recebida</td><td>Pedido pago, arquivo gerado. Ainda não conferido.</td><td>Aprovado</td><td>E-mail e WhatsApp de pedido aprovado</td></tr>
<tr><td class="k">Arte tratada</td><td>Arquivo conferido e ajustado, se preciso.</td><td>—</td></tr> <tr><td class="k">Arte conferida</td><td>Arquivo conferido e ajustado, se preciso.</td><td>—</td><td>—</td></tr>
<tr><td class="k">Fila de impressão</td><td>Pronto para imprimir. Exige o arquivo final aprovado.</td><td>—</td></tr> <tr><td class="k">Fila de impressão</td><td>Pronto para imprimir. Exige o arquivo final aprovado.</td><td>—</td><td>—</td></tr>
<tr><td class="k">Imprimindo</td><td>Na máquina.</td><td>—</td></tr> <tr><td class="k">Imprimindo</td><td>Na máquina.</td><td>Preparando envio</td><td>—</td></tr>
<tr><td class="k">Finalizado</td><td>Impresso e pronto para retirada ou envio.</td><td>Pedido pronto para retirada</td></tr> <tr><td class="k">Finalizado</td><td>Impresso. Retirada: pronto para buscar. Entrega: a equipe fatura e despacha no Tiny.</td>
<tr><td class="k">Correção</td><td>Algo no arquivo precisa ser resolvido pelo cliente.</td><td>Pela equipe, no WhatsApp (página 8)</td></tr> <td>Retirada: Pronto para envio</td><td>Retirada: pronto para retirar. Entrega: ao ser enviado e entregue</td></tr>
<tr><td class="k">Correção</td><td>Algo no arquivo precisa ser resolvido pelo cliente.</td><td>—</td><td>Pela equipe, no WhatsApp (página 8)</td></tr>
</table> </table>
<div class="note">Os avisos por WhatsApp saem pelo número e pelas mensagens que a Dropstar já usa, a partir da situação <div class="note">Os avisos por WhatsApp saem pelo número e pelas mensagens que a Dropstar já usa, a partir da situação
do pedido no Tiny. Cada aviso sai <b>uma vez só</b>, mesmo que o pedido volte uma etapa e avance de novo.</div> do pedido no Tiny. Cada aviso sai <b>uma vez só</b>, mesmo que o pedido volte uma etapa e avance de novo. Um pedido
cancelado no Kanban é cancelado também no Tiny, se ainda não foi faturado.</div>
<div class="split"> <div class="split">
<div> <div>
<h2 style="margin-top:2mm">Baixar a fila de uma vez</h2> <h2 style="margin-top:2mm">Baixar a fila de uma vez</h2>
<p>Na coluna <b>Fila de impressão</b>, o botão <b>Baixar</b> baixa o arquivo final de todos os pedidos da fila, na <p>Na coluna <b>Fila de impressão</b>, o botão <b>Baixar</b> baixa o arquivo final de todos os pedidos da fila, na
ordem da fila, com o número do pedido no nome (ex.: <span class="chip">pedido-246-item-1-…</span>). Se o navegador ordem da fila, com o número do pedido no nome (ex.: <span class="chip">pedido-246-item-1-…</span>). Se o navegador
perguntar, permita vários downloads.</p> perguntar, permita vários downloads. Na sala de impressão, a <b>pasta automática</b> faz isso sozinha (página 9).</p>
<h2>Moveu errado? Volte uma etapa</h2> <h2>Moveu errado? Volte uma etapa</h2>
<p>Clique em <b>← Voltar para [etapa anterior]</b>, embaixo dos botões, escreva o motivo (ex.: “movi por engano”) e <p>Clique em <b>← Voltar para [etapa anterior]</b>, embaixo dos botões, escreva o motivo (ex.: “movi por engano”) e
confirme. O retorno fica no histórico; o cliente não vê esse retorno nem o motivo.</p> confirme. O retorno fica no histórico; o cliente não vê esse retorno nem o motivo.</p>
@@ -272,14 +284,64 @@
<img class="shot" src="img/correcao.png" alt="Pedido em correção com Avisar no WhatsApp"> <img class="shot" src="img/correcao.png" alt="Pedido em correção com Avisar no WhatsApp">
<p class="caption">Sem WhatsApp no pedido, use <b>Copiar mensagem</b> e envie por e-mail.</p> <p class="caption">Sem WhatsApp no pedido, use <b>Copiar mensagem</b> e envie por e-mail.</p>
<p>O cliente envia o arquivo corrigido em <b>Minha conta</b>, no Site. O card mostra <p>O cliente envia o arquivo corrigido em <b>Minha conta</b>, no Site. O card mostra
<span class="chip">Correção recebida</span>: mova o pedido para <b>Arte recebida</b> ou <b>Arte tratada</b>, confira a <span class="chip">Correção recebida</span>: mova o pedido para <b>Arte recebida</b> ou <b>Arte conferida</b>, confira a
correção e aprove como arquivo final (página 6).</p> correção e aprove como arquivo final (página 6).</p>
<div class="note">Correção é para problemas que só o cliente resolve (resolução, fundo, arte errada). Ajustes que a equipe <div class="note">Correção é para problemas que só o cliente resolve (resolução, fundo, arte errada). Ajustes que a equipe
faz sozinha não precisam de correção: trate o arquivo em <b>Arte tratada</b>.</div> faz sozinha não precisam de correção: trate o arquivo em <b>Arte conferida</b>.</div>
<h2>Precisa falar com o cliente antes de imprimir?</h2>
<div class="split">
<div><p>No painel do pedido, clique em <b>☎ Aguardando contato</b> e escreva o que precisa ser combinado. O pedido fica na
mesma etapa, com a marca no card e no filtro <b>Aguardando contato</b>. Depois de falar com o cliente, clique em
<b>Contato feito</b>.</p></div>
<div class="side"><img class="shot" src="img/contato.png" alt="Pedido aguardando contato com o cliente"></div>
</div>
<div class="folio">Página 8</div> <div class="folio">Página 8</div>
</section> </section>
<!-- 9 · Cancelar e Números --> <!-- 9 · Pasta automática -->
<section class="page">
<div class="running">DTF Dropstar - guia do operador</div>
<p class="kicker">SALA DE IMPRESSÃO</p>
<h1>Pasta automática da Fila de impressão</h1>
<p>O Kanban salva os arquivos dos pedidos numa pasta do computador: a que o FlexiPRINT lê, ou a pasta da rede do
servidor. Ninguém precisa baixar à mão. Na linha da pasta, escolha <b>quando baixar</b>:</p>
<ul>
<li><b>Baixar ao chegar</b>: o arquivo é baixado assim que o pedido chega, na subpasta <b>Recebidos</b>, e passa para a
pasta principal quando o pedido entra na <b>Fila de impressão</b>. Arquivos grandes já estão no computador na hora de imprimir.</li>
<li><b>Baixar na Fila</b>: o arquivo é baixado quando o pedido entra na <b>Fila de impressão</b>.</li>
</ul>
<h2>Ligar (uma vez, no computador da sala de impressão)</h2>
<ol>
<li>Abra o Kanban no <b>Google Chrome</b> (ou no Microsoft Edge) e entre com o seu acesso.</li>
<li>Abra <b>Integrações</b>. Na linha <b>Pasta da Fila de impressão</b>, clique em <b>Escolher pasta</b>.</li>
<li>Escolha a pasta e permita que o Kanban altere os arquivos dela.</li>
<li>Pronto: a linha mostra <span class="chip">Ligada</span>. Escolha <b>Baixar ao chegar</b> ou <b>Baixar na Fila</b>.</li>
</ol>
<img class="shot" src="img/pasta.png" alt="Pasta da Fila de impressão ligada, com os detalhes abertos">
<p class="caption">Em <b>Detalhes</b>: a pasta, quantos arquivos foram salvos, e os botões <b>Trocar pasta</b> e <b>Desligar</b>.</p>
<ul>
<li>Os arquivos levam o número do pedido no nome (ex.: <span class="chip">pedido-246-item-1-…</span>). Enquanto baixa, o
arquivo termina em <span class="chip">.baixando</span>: o FlexiPRINT só vê o arquivo inteiro.</li>
<li>Pedido cancelado, excluído ou devolvido para correção: o arquivo sai da pasta. Arquivo trocado: a versão antiga sai.
Um arquivo que o FlexiPRINT tirar da pasta não é baixado de novo.</li>
<li>O Kanban precisa ficar <b>aberto</b> nesse computador. Ele confere a fila a cada 30 segundos, mesmo com a
atualização do quadro desligada, e pega também os pedidos movidos em outros computadores.</li>
<li>Um operador ligado a uma máquina recebe só os arquivos dos pedidos dela.</li>
</ul>
<h2>Depois de reiniciar o navegador</h2>
<div class="split">
<div><p>O navegador pede uma confirmação. A aba <b>Integrações</b> mostra um <b>!</b> laranja e a linha fica
<span class="chip">Liberar</span>: clique em <b>Liberar pasta</b> e confirme.</p></div>
<div class="side" style="flex-basis:30mm"><img class="shot" src="img/aba-aviso.png" alt="Aba Integrações com aviso"></div>
</div>
<img class="shot" src="img/pasta-liberar.png" alt="Pasta esperando o clique para liberar">
<div class="note">Use o <b>Chrome</b> na sala de impressão. O <b>Brave</b> vem com o acesso a pastas desligado (a linha
mostra como ligar). O <b>Firefox</b> não salva em pastas: nele, os arquivos da fila só são baixados para a pasta de
downloads, sem <b>Recebidos</b> e sem apagar os de pedidos cancelados.</div>
<div class="folio">Página 9</div>
</section>
<!-- 10 · Cancelar e Números -->
<section class="page"> <section class="page">
<div class="running">DTF Dropstar - guia do operador</div> <div class="running">DTF Dropstar - guia do operador</div>
<p class="kicker">PEDIDOS E NÚMEROS</p> <p class="kicker">PEDIDOS E NÚMEROS</p>
@@ -287,8 +349,9 @@
<div class="split"> <div class="split">
<div> <div>
<p>Em <b>⋯</b>, no topo do pedido, <b>Cancelar pedido</b> pede um motivo. O pedido sai do quadro e fica no filtro <p>Em <b>⋯</b>, no topo do pedido, <b>Cancelar pedido</b> pede um motivo. O pedido sai do quadro e fica no filtro
<b>Cancelados</b>, com o pagamento e o histórico. O estorno, se houver, é feito no Mercado Pago. Um pedido cancelado <b>Cancelados</b>, com o pagamento e o histórico. O estorno, se houver, é feito no Mercado Pago. No Tiny, o pedido é
pode ser excluído de vez em <b>Excluir pedido</b>.</p> cancelado sozinho se ainda não foi faturado; se já foi, cancele a nota no Tiny. Um pedido cancelado pode ser
excluído de vez em <b>Excluir pedido</b>.</p>
<p>Pedidos de teste, criados pela equipe, aparecem com a etiqueta <span class="chip">TESTE</span> e são excluídos em <p>Pedidos de teste, criados pela equipe, aparecem com a etiqueta <span class="chip">TESTE</span> e são excluídos em
<b>⋯ → Excluir pedido de teste</b>.</p> <b>⋯ → Excluir pedido de teste</b>.</p>
</div> </div>
@@ -300,10 +363,43 @@
médio, quantos pedidos precisaram de correção e o tempo do pagamento até <b>Finalizado</b>. O gráfico mostra os metros médio, quantos pedidos precisaram de correção e o tempo do pagamento até <b>Finalizado</b>. O gráfico mostra os metros
de cada dia (passe o mouse para ver os valores), e a tabela, quanto tempo cada etapa segura um pedido e o que está de cada dia (passe o mouse para ver os valores), e a tabela, quanto tempo cada etapa segura um pedido e o que está
esperando agora. Pedidos de teste e cancelados ficam de fora.</p> esperando agora. Pedidos de teste e cancelados ficam de fora.</p>
<div class="folio">Página 9</div> <div class="folio">Página 10</div>
</section> </section>
<!-- 10 · Pagamentos e integrações --> <!-- 11 · Usuários -->
<section class="page">
<div class="running">DTF Dropstar - guia do operador</div>
<p class="kicker">EQUIPE</p>
<h1>Usuários, perfis e máquinas</h1>
<p>A aba <b>Usuários</b> aparece para os administradores. Cada pessoa tem o próprio acesso e um perfil:</p>
<table>
<tr><th style="width:31mm">Perfil</th><th>Pode</th></tr>
<tr><td class="k">Administrador</td><td>Tudo, inclusive usuários e máquinas.</td></tr>
<tr><td class="k">Gestão</td><td>Tudo, menos usuários e máquinas.</td></tr>
<tr><td class="k">Operador</td><td>Move pedidos, aprova arquivos e usa a pasta automática.</td></tr>
<tr><td class="k">Vendedor</td><td>Consulta pedidos, cotações e números. Não muda nada.</td></tr>
</table>
<img class="shot" style="width:68%" src="img/usuarios.png" alt="Aba Usuários">
<div class="split">
<div>
<h2 style="margin-top:2mm">Criar ou editar um usuário</h2>
<p>Clique em <b>Novo usuário</b> e preencha nome, e-mail, perfil e uma senha inicial (8 caracteres ou mais). Passe o
e-mail e a senha para a pessoa; ela troca em <b>Minha senha</b>. Se esquecer, defina uma senha nova em <b>Editar</b>.
<b>Ativo</b> desmarcado bloqueia o acesso na hora.</p>
<h2>Máquinas</h2>
<p>Em <b>Nova máquina</b>, informe o nome e se imprime Têxtil, UV ou os dois. O pedido vai para a primeira máquina
ativa que imprime o produto; no painel do pedido dá para escolher outra. O operador marcado em máquinas vê só os
pedidos delas; sem nenhuma marcada, vê todos.</p>
<h2>Alertas por e-mail</h2>
<p>Marque <b>Receber alertas por e-mail</b> para quem deve saber na hora de um pedido pago, de uma cotação esperando
revisão e de um pagamento com problema. Precisa do e-mail ativo em <b>Integrações</b>.</p>
</div>
<div class="side" style="flex-basis:62mm"><img class="shot" src="img/usuario-editar.png" alt="Editar usuário"></div>
</div>
<div class="folio">Página 11</div>
</section>
<!-- 12 · Pagamentos e integrações -->
<section class="page"> <section class="page">
<div class="running">DTF Dropstar - guia do operador</div> <div class="running">DTF Dropstar - guia do operador</div>
<p class="kicker">PAGAMENTOS E INTEGRAÇÕES</p> <p class="kicker">PAGAMENTOS E INTEGRAÇÕES</p>
@@ -319,19 +415,25 @@
<img class="shot" src="img/pagamentos.png" alt="Aba Pagamentos"> <img class="shot" src="img/pagamentos.png" alt="Aba Pagamentos">
<h2>Integrações</h2> <h2>Integrações</h2>
<img class="shot" src="img/integracoes.png" alt="Aba Integrações"> <img class="shot" src="img/integracoes.png" alt="Aba Integrações">
<p class="caption">Imagem de um ambiente sem integrações ativas. Em produção, cada cartão mostra se a integração está conectada.</p> <p class="caption">Imagem de um ambiente de teste. Cada linha mostra a situação e um resumo; <b>Detalhes</b> abre as datas,
os números e os botões menos usados, embaixo da própria linha.</p>
<ul> <ul>
<li><b>Tiny</b>: o cartão mostra quem conectou, quando a conexão foi renovada e até quando vale; o sistema renova <li><b>Tiny</b>: quem conectou e se o envio de pedidos está ativo; o sistema renova a conexão sozinho. Se aparecer
sozinho. Se aparecer <b>Não conectado</b> ou <b>Verificar</b>, clique em <b>Conectar Tiny</b> ou <b>Reconectar</b> e <b>Não conectado</b> ou <b>Verificar</b>, clique em <b>Conectar Tiny</b> (ou <b>Reconectar</b>, em Detalhes) e entre
entre com o usuário do Tiny indicado pela Dropstar. <b>Testar conexão</b> confere pedidos, contatos, os produtos com o usuário do Tiny indicado pela Dropstar. <b>Testar conexão</b> confere pedidos, contatos, os produtos e a forma
e a forma de envio de retirada, sem criar nada.</li> de envio de retirada, sem criar nada.</li>
<li><b>Registro de envios</b>: tudo o que o sistema mandou ao Tiny, com filtros por destino, situação, evento e <li><b>Mercado Pago</b>: <b>Verificar conta</b> mostra, em Detalhes, a conta, a credencial e os avisos recebidos.</li>
pedido. <b>Com erro</b> indica um envio que falhou; o sistema tenta de novo sozinho, mas o erro precisa de atenção.</li> <li><b>Frete</b>: as opções do carrinho (Jadlog, Correios PAC e SEDEX), a caixa e o peso usados na cotação.</li>
<li><b>E-mail</b>: os e-mails dos clientes e os alertas da equipe. <b>Enviar teste</b> manda um e-mail para você.</li>
<li><b>Backup do banco</b>: uma cópia por dia, às 3h, criptografada e fora do servidor. <b>Fazer backup agora</b> faz
uma cópia na hora (por exemplo, antes de uma mudança grande).</li>
<li><b>Envios ao Tiny</b>: tudo o que o sistema mandou ao Tiny, com filtros por situação, evento e pedido.
<b>Com erro</b> indica um envio que falhou; o sistema tenta de novo sozinho, mas o erro precisa de atenção.</li>
</ul> </ul>
<div class="folio">Página 10</div> <div class="folio">Página 12</div>
</section> </section>
<!-- 11 · Dúvidas --> <!-- 13 · Dúvidas -->
<section class="page"> <section class="page">
<div class="running">DTF Dropstar - guia do operador</div> <div class="running">DTF Dropstar - guia do operador</div>
<p class="kicker">DÚVIDAS FREQUENTES</p> <p class="kicker">DÚVIDAS FREQUENTES</p>
@@ -344,17 +446,20 @@
<tr><td>Card com <b>Correção recebida</b></td><td>O cliente enviou o arquivo corrigido. Mova o pedido e aprove a correção (página 6).</td></tr> <tr><td>Card com <b>Correção recebida</b></td><td>O cliente enviou o arquivo corrigido. Mova o pedido e aprove a correção (página 6).</td></tr>
<tr><td>Arquivo aparece como <b>expirado</b></td><td>Os arquivos ficam guardados por 30 dias. Depois disso, o cliente precisa enviar de novo.</td></tr> <tr><td>Arquivo aparece como <b>expirado</b></td><td>Os arquivos ficam guardados por 30 dias. Depois disso, o cliente precisa enviar de novo.</td></tr>
<tr><td>No topo, <b>Tiny: verificar conexão</b> ou <b>Tiny não conectado</b></td><td>Abra <b>Integrações</b> e siga a mensagem do cartão do Tiny. Se pedir, clique em <b>Reconectar</b>.</td></tr> <tr><td>No topo, <b>Tiny: verificar conexão</b> ou <b>Tiny não conectado</b></td><td>Abra <b>Integrações</b> e siga a mensagem do cartão do Tiny. Se pedir, clique em <b>Reconectar</b>.</td></tr>
<tr><td>O nome da empresa não aparece no card</td><td>O nome vem do cadastro do CNPJ e chega em alguns minutos. Até lá, o card mostra o e-mail.</td></tr> <tr><td>O cliente comprou sem conta e não vê o pedido em Minha conta</td><td>Ele cria a conta (ou entra) com o mesmo CPF ou CNPJ e o mesmo e-mail do pedido: os pedidos aparecem sozinhos.</td></tr>
<tr><td>A internet da fábrica caiu</td><td>O Site continua recebendo pedidos e pagamentos. Quando a conexão voltar, o quadro se atualiza sozinho.</td></tr> <tr><td>A internet da fábrica caiu</td><td>O Site continua recebendo pedidos e pagamentos. Quando a conexão voltar, o quadro se atualiza sozinho.</td></tr>
<tr><td><b>!</b> laranja na aba Integrações</td><td>A pasta automática espera um clique: <b>Liberar pasta</b> (página 9).</td></tr>
<tr><td>Esqueci a senha do Kanban</td><td>Peça a um administrador: <b>Usuários → Editar → Nova senha</b>.</td></tr>
<tr><td>O cliente esqueceu a senha do Site</td><td>Em <b>Minha conta → Esqueci minha senha</b>, ele recebe um link por e-mail que vale 1 hora.</td></tr>
</table> </table>
<h2>Boas práticas</h2> <h2>Boas práticas</h2>
<ul> <ul>
<li>Mova o card assim que a etapa mudar: é o que avisa o cliente e mede o tempo de produção na aba <b>Números</b>.</li> <li>Mova o card assim que a etapa mudar: é o que atualiza o Tiny, avisa o cliente e mede o tempo de produção na aba <b>Números</b>.</li>
<li>Escreva motivos que outra pessoa entenda sem perguntar.</li> <li>Escreva motivos que outra pessoa entenda sem perguntar.</li>
<li>Use sempre o seu acesso: o histórico mostra quem fez cada movimento.</li> <li>Use sempre o seu acesso: o histórico mostra quem fez cada movimento.</li>
<li>Clique em <b>Sair</b> ao deixar o computador.</li> <li>Clique em <b>Sair</b> ao deixar o computador.</li>
</ul> </ul>
<div class="folio">Página 11</div> <div class="folio">Página 13</div>
</section> </section>
</body> </body>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

After

Width:  |  Height:  |  Size: 360 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 236 KiB

After

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 112 KiB

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 212 KiB

After

Width:  |  Height:  |  Size: 207 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 87 KiB

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 204 KiB

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 213 KiB

After

Width:  |  Height:  |  Size: 442 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

View File

@@ -73,9 +73,9 @@
<p class="lead">Do envio da arte ao pedido pronto: o que o cliente vê e o que acontece em cada etapa.</p> <p class="lead">Do envio da arte ao pedido pronto: o que o cliente vê e o que acontece em cada etapa.</p>
<table> <table>
<tr><th style="width:50%">Endereço</th><th>Para quem</th></tr> <tr><th style="width:50%">Endereço</th><th>Para quem</th></tr>
<tr><td>dtf.agenciacompor.com.br<br>(endereço provisório)</td><td>Equipe Dropstar e atendimento</td></tr> <tr><td>dropstardtf.com.br</td><td>Equipe Dropstar e atendimento</td></tr>
</table> </table>
<p class="version">Versão de 7 de outubro de 2026</p> <p class="version">Versão de 19 de outubro de 2026</p>
</div> </div>
</section> </section>
@@ -92,13 +92,13 @@
<tr><td class="n">2</td><td class="k">Monta a folha</td> <tr><td class="n">2</td><td class="k">Monta a folha</td>
<td>Envia as artes, informa tamanho e quantidade e vê a folha, a nota e o total.</td></tr> <td>Envia as artes, informa tamanho e quantidade e vê a folha, a nota e o total.</td></tr>
<tr><td class="n">3</td><td class="k">Carrinho</td> <tr><td class="n">3</td><td class="k">Carrinho</td>
<td>Escolhe os itens que vai pagar, informa CNPJ, WhatsApp e e-mail e escolhe retirada ou entrega.</td></tr> <td>Escolhe os itens que vai pagar, informa nome, CPF ou CNPJ, WhatsApp e e-mail e escolhe retirada ou entrega.</td></tr>
<tr><td class="n">4</td><td class="k">Pagamento</td> <tr><td class="n">4</td><td class="k">Pagamento</td>
<td>Cartão de crédito ou PIX pelo Mercado Pago, na própria página. Os dados do cartão não passam pelo nosso servidor.</td></tr> <td>PIX ou cartão de crédito (à vista ou em até 3 vezes) pelo Mercado Pago, na própria página. Os dados do cartão não passam pelo nosso servidor.</td></tr>
<tr><td class="n">5</td><td class="k">Produção</td> <tr><td class="n">5</td><td class="k">Produção</td>
<td>Com o pagamento aprovado, o pedido aparece no Kanban da equipe.</td></tr> <td>Com o pagamento aprovado, o pedido aparece no Kanban da equipe e é lançado no Tiny.</td></tr>
<tr><td class="n">6</td><td class="k">Acompanhamento</td> <tr><td class="n">6</td><td class="k">Acompanhamento</td>
<td>Em <b>Minha conta</b>, pelo código do pedido, e por WhatsApp quando o pagamento é aprovado e quando o pedido fica pronto.</td></tr> <td>E-mail de confirmação, <b>Minha conta</b> com o andamento de cada pedido, e WhatsApp quando o pedido é aprovado, fica pronto para retirada ou é enviado.</td></tr>
</table> </table>
<img class="shot" src="img/inicio.png" alt="Página inicial do Site DTF"> <img class="shot" src="img/inicio.png" alt="Página inicial do Site DTF">
<p class="caption">Página inicial do Site DTF.</p> <p class="caption">Página inicial do Site DTF.</p>
@@ -124,7 +124,8 @@
<ul> <ul>
<li><b>Artes avulsas</b> incluem a montagem da folha: R$ 10,00 a mais por metro no têxtil e R$ 14,00 no UV, em qualquer nota.</li> <li><b>Artes avulsas</b> incluem a montagem da folha: R$ 10,00 a mais por metro no têxtil e R$ 14,00 no UV, em qualquer nota.</li>
<li>A cobrança é a cada <b>10 cm</b> (uma folha de 2,75 m custa 2,80 m) e o pedido mínimo é de <b>1 metro</b>.</li> <li>A cobrança é a cada <b>10 cm</b> (uma folha de 2,75 m custa 2,80 m) e o pedido mínimo é de <b>1 metro</b>.</li>
<li>Folhas em CDR, AI, PSD ou TIFF não têm conferência automática: o metro vai pela tabela cheia e a equipe prepara o arquivo à mão.</li> <li>Folhas em CDR, AI, PSD ou TIFF não têm conferência automática: o metro vai pela tabela cheia e a equipe prepara o
arquivo à mão. Quando a Dropstar define um valor para essa preparação, ele aparece no preço do item antes do pagamento.</li>
</ul> </ul>
<div class="folio">Página 3</div> <div class="folio">Página 3</div>
</section> </section>
@@ -185,10 +186,12 @@
<ul> <ul>
<li><b>Itens</b>: cada item aparece com a miniatura da arte. O cliente marca quais quer pagar agora; os outros ficam no <li><b>Itens</b>: cada item aparece com a miniatura da arte. O cliente marca quais quer pagar agora; os outros ficam no
carrinho. <b>Remover</b> e <b>Esvaziar carrinho</b> podem ser desfeitos na hora.</li> carrinho. <b>Remover</b> e <b>Esvaziar carrinho</b> podem ser desfeitos na hora.</li>
<li><b>Seus dados</b>: CNPJ (o mesmo da nota fiscal), WhatsApp e e-mail.</li> <li><b>Seus dados</b>: nome, CPF ou CNPJ (o mesmo da nota fiscal), WhatsApp e e-mail. Quem já tem conta entra com os
dados preenchidos.</li>
<li><b>Forma de entrega</b>: <b>Retirar em Franca</b> (Av. Major Elias Motta, 1281, Jardim São Luís, de segunda a <li><b>Forma de entrega</b>: <b>Retirar em Franca</b> (Av. Major Elias Motta, 1281, Jardim São Luís, de segunda a
sexta, das 7h às 17h) ou <b>Receber em casa</b>. Na entrega, o CEP preenche o endereço e o frete da Jadlog aparece sexta, das 7h às 17h) ou <b>Receber em casa</b>. Na entrega, o CEP preenche o endereço e aparecem as opções
na hora, com o prazo já contando o dia de produção.</li> <b>Jadlog</b>, <b>Correios PAC</b> e <b>Correios SEDEX</b>, da mais barata para a mais cara, com o prazo já contando o
dia de produção.</li>
<li><b>Arquivos enviados</b> confirma que as artes já chegaram. Os arquivos de um carrinho não pago ficam guardados <li><b>Arquivos enviados</b> confirma que as artes já chegaram. Os arquivos de um carrinho não pago ficam guardados
por 2 dias.</li> por 2 dias.</li>
</ul> </ul>
@@ -205,8 +208,8 @@
que não confere com os arquivos. Depois da aprovação, o cliente tem <b>24 horas</b> para pagar.</p> que não confere com os arquivos. Depois da aprovação, o cliente tem <b>24 horas</b> para pagar.</p>
<table> <table>
<tr><th style="width:38mm">Forma</th><th>Como funciona</th></tr> <tr><th style="width:38mm">Forma</th><th>Como funciona</th></tr>
<tr><td class="k">Cartão de crédito</td><td>No formulário seguro do Mercado Pago, dentro da página, em até 12 <tr><td class="k">Cartão de crédito</td><td>No formulário seguro do Mercado Pago, dentro da página: à vista sem juros,
parcelas. Os dados do cartão não passam pelo nosso servidor.</td></tr> ou em 2 ou 3 parcelas com juros. Os dados do cartão não passam pelo nosso servidor.</td></tr>
<tr><td class="k">PIX</td><td>QR Code e código copia e cola na própria página, válidos por 30 minutos, com contagem. <tr><td class="k">PIX</td><td>QR Code e código copia e cola na própria página, válidos por 30 minutos, com contagem.
A página confirma sozinha quando o pagamento cai.</td></tr> A página confirma sozinha quando o pagamento cai.</td></tr>
</table> </table>
@@ -218,8 +221,8 @@
<li>“O banco precisa autorizar este pagamento. Ligue para o banco emissor e tente de novo, ou use outro cartão.”</li> <li>“O banco precisa autorizar este pagamento. Ligue para o banco emissor e tente de novo, ou use outro cartão.”</li>
</ul> </ul>
<h2>Pagamento aprovado</h2> <h2>Pagamento aprovado</h2>
<p>A página mostra <b>Pagamento confirmado</b> e o botão <b>Ver meus pedidos</b>. O pedido entra na produção e aparece <p>A página mostra <b>Pagamento confirmado</b> e o botão <b>Ver meus pedidos</b>, e o cliente recebe o e-mail
no Kanban. Para o cliente, o pedido tem um <b>código</b> (ex.: <span class="chip">3F0CB7C2</span>); o número <b>Recebemos seu pedido</b> (página 10). O pedido entra na produção e aparece no Kanban. Para o cliente, o pedido tem um <b>código</b> (ex.: <span class="chip">3F0CB7C2</span>); o número
sequencial fica só com a equipe.</p> sequencial fica só com a equipe.</p>
<div class="folio">Página 7</div> <div class="folio">Página 7</div>
</section> </section>
@@ -229,17 +232,19 @@
<div class="running">DTF Dropstar - como funciona o Site DTF</div> <div class="running">DTF Dropstar - como funciona o Site DTF</div>
<p class="kicker">ACOMPANHAMENTO</p> <p class="kicker">ACOMPANHAMENTO</p>
<h1>Minha conta</h1> <h1>Minha conta</h1>
<p>O cliente entra com e-mail e senha, ou cria a conta com CNPJ, WhatsApp, e-mail e uma senha de 12 caracteres ou <p>O cliente entra com e-mail e senha, ou cria a conta com nome, CPF ou CNPJ, WhatsApp, e-mail e uma senha de 12
mais. Quem pagou sem conta vê os pedidos no mesmo navegador, e eles passam para a conta quando ela é criada.</p> caracteres ou mais. Para criar, ele confirma o e-mail com um <b>código de 6 números</b> enviado na hora. Os pedidos
feitos sem conta com o mesmo CPF/CNPJ e e-mail aparecem na conta sozinhos, de qualquer navegador.</p>
<img class="shot narrow" src="img/conta.png" alt="Visão geral de Minha conta"> <img class="shot narrow" src="img/conta.png" alt="Visão geral de Minha conta">
<ul> <ul>
<li><b>Visão geral</b>: quantos pedidos aguardam pagamento, estão em produção, em correção ou finalizados.</li> <li><b>Visão geral</b>: quantos pedidos aguardam pagamento, estão em produção, em correção ou finalizados.</li>
<li><b>Pedidos</b>: a lista com código, produto, metragem, situação e valor, com filtros e busca pelo código. Cada <li><b>Pedidos</b>: a lista com código, produto, metragem, situação e valor, com filtros e busca pelo código. Cada
pedido mostra as etapas e o andamento, com data e hora.</li> pedido mostra as etapas e o andamento, com data e hora.</li>
<li><b>Dados da conta</b>: CNPJ, WhatsApp e e-mail, e a troca de senha.</li> <li><b>Dados da conta</b>: nome, WhatsApp e endereço de entrega salvo; a troca de e-mail, confirmada por um código
enviado ao novo endereço (o antigo recebe um aviso); e a troca de senha. O CPF ou CNPJ não muda.</li>
</ul> </ul>
<div class="note"><b>Esqueci minha senha</b> ainda leva ao WhatsApp da Dropstar: a recuperação por e-mail entra <div class="note"><b>Esqueci minha senha</b>: o cliente recebe por e-mail um link para criar uma nova senha, que vale
quando o servidor de e-mail estiver configurado.</div> 1 hora e funciona uma vez só.</div>
<div class="folio">Página 8</div> <div class="folio">Página 8</div>
</section> </section>
@@ -254,14 +259,43 @@
a arte corrigida ali mesmo, com uma nota do que mudou, e a equipe segue com o pedido. A equipe avisa o cliente pelo a arte corrigida ali mesmo, com uma nota do que mudou, e a equipe segue com o pedido. A equipe avisa o cliente pelo
WhatsApp, com a mensagem pronta no Kanban.</p> WhatsApp, com a mensagem pronta no Kanban.</p>
<ul> <ul>
<li><b>Avisos automáticos por WhatsApp</b>: pagamento aprovado e pedido pronto para retirada, pelo número e pelas
mensagens que a Dropstar já usa.</li>
<li>As artes ficam guardadas por <b>30 dias</b>. Depois disso, para repetir o pedido, o cliente envia os arquivos de novo.</li> <li>As artes ficam guardadas por <b>30 dias</b>. Depois disso, para repetir o pedido, o cliente envia os arquivos de novo.</li>
</ul> </ul>
<div class="folio">Página 9</div> <div class="folio">Página 9</div>
</section> </section>
<!-- 10 · Situação atual --> <!-- 10 · Avisos -->
<section class="page">
<div class="running">DTF Dropstar - como funciona o Site DTF</div>
<p class="kicker">ACOMPANHAMENTO</p>
<h1>Avisos ao cliente</h1>
<div class="split">
<div>
<h2 style="margin-top:0">Por e-mail</h2>
<p>Saem de <b>dropstardtf.com.br</b>, no visual do Site, com o nome do cliente:</p>
<ul>
<li><b>Recebemos seu pedido</b>: quando o pagamento é aprovado, com os itens, a entrega, o total, as próximas etapas e
o botão <b>Ver meu pedido</b>.</li>
<li><b>Código de confirmação</b>: para criar a conta e para trocar o e-mail. Vale 15 minutos.</li>
<li><b>Criar nova senha</b>: o link de <b>Esqueci minha senha</b>, que vale 1 hora.</li>
<li><b>E-mail trocado</b>: aviso ao endereço antigo, com o WhatsApp da Dropstar se não foi o cliente.</li>
<li><b>Você já tem conta</b>: quando alguém tenta criar uma conta com um e-mail já cadastrado.</li>
</ul>
<h2>Por WhatsApp</h2>
<p>Pelo número e pelas mensagens que a Dropstar já usa, a partir da situação do pedido no Tiny:</p>
<ul>
<li><b>Pedido aprovado</b>, quando o pagamento é aprovado;</li>
<li><b>Pronto para retirada</b>, quando o pedido de retirada é finalizado;</li>
<li><b>Pedido enviado</b> e <b>entregue</b>, nos pedidos com entrega.</li>
</ul>
<p>Na correção, a equipe avisa pelo WhatsApp com a mensagem pronta no Kanban.</p>
</div>
<div class="side" style="flex-basis:70mm"><img class="shot" src="img/email-pedido.png" alt="E-mail Recebemos seu pedido"></div>
</div>
<div class="folio">Página 10</div>
</section>
<!-- 11 · Situação atual -->
<section class="page"> <section class="page">
<div class="running">DTF Dropstar - como funciona o Site DTF</div> <div class="running">DTF Dropstar - como funciona o Site DTF</div>
<p class="kicker">SITUAÇÃO ATUAL</p> <p class="kicker">SITUAÇÃO ATUAL</p>
@@ -270,15 +304,16 @@
<tr><th style="width:44mm">Parte</th><th style="width:36mm">Situação</th><th>Observação</th></tr> <tr><th style="width:44mm">Parte</th><th style="width:36mm">Situação</th><th>Observação</th></tr>
<tr><td class="k">Site: produtos, montagem, nota e preço</td><td>Funcionando</td><td>Tabela e regras comerciais do Site DTF mantidas.</td></tr> <tr><td class="k">Site: produtos, montagem, nota e preço</td><td>Funcionando</td><td>Tabela e regras comerciais do Site DTF mantidas.</td></tr>
<tr><td class="k">Arquivos de até 5 GB</td><td>Funcionando</td><td>Antivírus até 2 GB; acima disso, conferência do formato.</td></tr> <tr><td class="k">Arquivos de até 5 GB</td><td>Funcionando</td><td>Antivírus até 2 GB; acima disso, conferência do formato.</td></tr>
<tr><td class="k">Frete (receber em casa)</td><td>Funcionando</td><td>Jadlog, com a caixa e o peso informados pela Dropstar.</td></tr> <tr><td class="k">Frete (receber em casa)</td><td>Funcionando</td><td>Jadlog, Correios PAC e Correios SEDEX, com a caixa e o peso informados pela Dropstar.</td></tr>
<tr><td class="k">Pagamento</td><td>Funcionando em teste</td><td>Cartão de crédito e PIX testados com as credenciais de teste; falta ativar as de produção.</td></tr> <tr><td class="k">Pagamento</td><td>Funcionando</td><td>PIX e cartão de crédito (à vista ou em até 3 vezes), com as credenciais de produção do Mercado Pago.</td></tr>
<tr><td class="k">Minha conta</td><td>Funcionando</td><td>Pedidos, correção e dados da conta.</td></tr> <tr><td class="k">Minha conta e e-mails</td><td>Funcionando</td><td>Cadastro com código, recuperação de senha, troca de e-mail e confirmação do pedido.</td></tr>
<tr><td class="k">Kanban de produção</td><td>Funcionando</td><td>Veja o guia do operador.</td></tr> <tr><td class="k">Kanban de produção</td><td>Funcionando</td><td>Veja o guia do operador.</td></tr>
<tr><td class="k">Pedido no Tiny e avisos por WhatsApp</td><td>Pronto, falta o teste</td><td>Ativados depois do pedido de teste acompanhado no Tiny.</td></tr> <tr><td class="k">Cópia de segurança</td><td>Funcionando</td><td>Uma por dia, criptografada e fora do servidor.</td></tr>
<tr><td class="k">Recuperação de senha</td><td>Depende do e-mail</td><td>Entra com os dados do servidor de e-mail (SMTP).</td></tr> <tr><td class="k">Domínio</td><td>Definitivo</td><td>dropstardtf.com.br (Site) e kanban.dropstardtf.com.br (Kanban).</td></tr>
<tr><td class="k">Domínio</td><td>Provisório</td><td>dtf.agenciacompor.com.br até a definição do domínio definitivo.</td></tr> <tr><td class="k">Pedido no Tiny e avisos por WhatsApp</td><td>Pronto, falta ativar</td><td>Ativados no lançamento, depois de definir a categoria, o vendedor e o marcador dos pedidos do DTF no Tiny.</td></tr>
<tr><td class="k">Lançamento</td><td>Próximo passo</td><td>Teste com um grupo de 5 a 10 clientes antes de abrir para todos.</td></tr>
</table> </table>
<div class="folio">Página 10</div> <div class="folio">Página 11</div>
</section> </section>
</body> </body>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 248 KiB

After

Width:  |  Height:  |  Size: 310 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 120 KiB

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 215 KiB

After

Width:  |  Height:  |  Size: 234 KiB

View File

@@ -0,0 +1,27 @@
# Screenshots for the guides
The images in `operador/img/` and `site/img/` come from the local stack seeded
with fictional customers. To take them again:
1. Start the local stack with the CI settings (`docs/LOCAL_SETUP.md`), clear it as
`seed.py` says, and run `seed.py` in the api container.
2. Start a container from the browser-tests image on the stack's network and
give it internet too, so Google Fonts load (the stack's network is internal):
```bash
docker run -d --name dtf-shots --network dtf-sistema_local \
-v "$PWD/docs/guias/telas:/g" -v /tmp/telas:/shots -e CHROME_BIN=/usr/bin/chromium \
dtf-sistema-browser-tests sleep 1800
docker network connect bridge dtf-shots
docker exec dtf-shots node /g/shots.mjs kanban
docker exec dtf-shots node /g/shots.mjs site
```
`site` also needs `/g/email-pedido.html`, the order e-mail rendered with
`app.mail_html.order_paid`.
3. Copy what changed from `/tmp/telas` into the `img/` folders (the print queue
column is cropped to 444x700 px), print with `../imprimir.sh` and check every
page: a page is fixed at A4 and cuts what does not fit.
Integrações is shown in its production state with fictional values set in the
page (shots.mjs), since the local stack has no Tiny or Mercado Pago.

295
docs/guias/telas/seed.py Normal file
View File

@@ -0,0 +1,295 @@
"""Fictional orders for the guides' screenshots, on the LOCAL stack only.
Before: python -m ops.launch_reset --confirmar APAGAR --contas (worker), and in
the db container delete every operator but operator@example.test, the
machines, payment_events, mail_queue and cnpj_names. Then, from the repo:
docker compose -f compose.local.yaml exec -T -e SITE_BASE_URL=http://site -e SITE_HOST_HEADER=localhost -e PYTHONPATH=/app api python - < docs/guias/telas/seed.py
It makes orders #1-#11 in every Kanban stage, a quote above 50 m, a refused
payment, users and machines, and Pedro's account; see telas/README.md.
"""
import io
import math
import random
import time
from uuid import uuid4
from PIL import Image, ImageDraw
from psycopg.types.json import Jsonb
from app.core import db
from tests.smoke_test import Client, approved_quote, item_spec, upload_bytes
random.seed(7)
PALETTES = {
'aurora': [(255, 122, 89), (255, 196, 61), (61, 64, 91), (129, 178, 154)],
'ipe': [(244, 196, 48), (232, 93, 117), (45, 49, 66), (255, 255, 255)],
'mare': [(0, 119, 182), (0, 180, 216), (144, 224, 239), (3, 4, 94)],
'rocha': [(214, 40, 40), (247, 127, 0), (252, 191, 73), (0, 48, 73)],
'norte': [(46, 196, 182), (231, 29, 54), (255, 159, 28), (1, 22, 39)],
}
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
def cnpj(seed):
base = f'{seed:08d}0001'
d1 = check(base, [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2])
d2 = check(base + str(d1), [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2])
return base + f'{d1}{d2}'
def cpf(seed):
base = f'{seed:09d}'
d1 = check(base, range(10, 1, -1))
d2 = check(base + str(d1), range(11, 1, -1))
return base + f'{d1}{d2}'
def star(draw, cx, cy, r, color):
points = []
for i in range(10):
angle = math.pi / 2 + i * math.pi / 5
radius = r if i % 2 == 0 else r * 0.45
points.append((cx + radius * math.cos(angle), cy - radius * math.sin(angle)))
draw.polygon(points, fill=color)
def sticker(draw, x, y, size, palette, kind):
a, b, c, d = palette
if kind == 0:
draw.ellipse((x, y, x + size, y + size), fill=a)
draw.ellipse((x + size * .14, y + size * .14, x + size * .86, y + size * .86), fill=c)
star(draw, x + size / 2, y + size / 2, size * .28, b)
elif kind == 1:
draw.rounded_rectangle((x, y + size * .15, x + size, y + size * .85), radius=size * .18, fill=b)
for i in range(4):
draw.rectangle((x + size * (.12 + i * .2), y + size * .3, x + size * (.2 + i * .2), y + size * .7), fill=c)
elif kind == 2:
draw.polygon([(x + size / 2, y), (x + size, y + size / 2), (x + size / 2, y + size), (x, y + size / 2)], fill=d)
draw.ellipse((x + size * .3, y + size * .3, x + size * .7, y + size * .7), fill=a)
else:
draw.ellipse((x, y, x + size, y + size), fill=b)
draw.pieslice((x + size * .1, y + size * .1, x + size * .9, y + size * .9), 200, 340, fill=a)
draw.ellipse((x + size * .35, y + size * .55, x + size * .65, y + size * .85), fill=c)
def sheet(palette, width_cm, length_cm, px_per_cm=12):
"""A transparent finished sheet of stickers, as customers send."""
w, h = int(width_cm * px_per_cm), int(length_cm * px_per_cm)
image = Image.new('RGBA', (w, h), (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
size = int(9 * px_per_cm)
gap = int(1.2 * px_per_cm)
cols = max(1, (w - gap) // (size + gap))
margin = (w - cols * size - (cols - 1) * gap) // 2
y, row = gap, 0
while y + size <= h - gap:
for col in range(cols):
sticker(draw, margin + col * (size + gap), y, size, palette, (row + col) % 4)
y += size + gap
row += 1
return image
def png(image, max_side=None):
if max_side:
image = image.copy()
image.thumbnail((max_side, max_side))
out = io.BytesIO()
image.save(out, 'PNG', optimize=True)
return out.getvalue()
def put_thumbnail(client, uid, data):
from urllib.request import Request
from tests.smoke_test import BASE, with_host
request = Request(BASE + f'/api/uploads/{uid}/thumbnail', data=data, method='PUT',
headers=with_host({'Content-Type': 'image/png'}))
with client.opener.open(request, timeout=30) as response:
assert response.status == 200
def order(customer, palette, mode, metres, grade, delivery=None):
client = Client()
client.call('/session')
film = 28.5 if mode in ('uv', 'uvfile') else 57
art = sheet(PALETTES[palette], film, float(metres) * 100)
uid = upload_bytes(client, png(art), name=f'{palette}-folha.png')
put_thumbnail(client, uid, png(art, 520))
item = item_spec(mode, metres, grade, uid)
draft = {'request_key': str(uuid4()), 'items': [item], 'customer': customer,
'freight': {'service': 'pickup'}}
if delivery:
draft['freight'] = {'service': 'mock-standard', 'postal_code': delivery['postal_code']}
draft['destination'] = delivery
quote = client.call('/quotes', draft)
approved_quote(client, quote, [item])
paid = client.call('/orders/dev-paid', {'quote_id': quote['id']})
return client, paid
def board_order(client, oid):
return next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == oid)
def wait_print(client, oid):
deadline = time.monotonic() + 120
while time.monotonic() < deadline:
found = board_order(client, oid)
files = found.get('print_files') or []
if files and files[0]['status'] in ('ready', 'manual', 'failed'):
return found, files[0]
time.sleep(1)
raise AssertionError('no print file')
def approve_final(client, oid):
found, row = wait_print(client, oid)
return client.call(f'/operator/orders/{oid}/final-files',
{'version': found['version'], 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],
'note': 'Arquivo gerado conferido'}, operator=True)['version']
def move(client, oid, version, state, reason=''):
return client.call(f'/operator/orders/{oid}/move', {'state': state, 'version': version, 'reason': reason},
operator=True)['version']
def to(client, paid, stages, correction=None):
oid = paid['id']
version = paid.get('version', 0)
for stage in stages:
if stage == 'final':
version = approve_final(client, oid)
elif stage == 'cor':
version = move(client, oid, version, 'cor', correction)
else:
version = move(client, oid, version, stage)
return oid, version
AURORA = {'name': 'Juliana Martins', 'cnpj': cnpj(31920485), 'zap': '16991234567', 'mail': 'contato@estampariaaurora.com.br'}
IPE = {'name': 'Pedro Alves', 'cnpj': cnpj(27450318), 'zap': '16992345678', 'mail': 'pedidos@camisetasipe.com.br'}
MARE = {'name': 'Rafael Costa', 'cnpj': cnpj(40871236), 'zap': '16993456789', 'mail': 'studio@maremoda.com.br'}
MARIA = {'name': 'Maria Oliveira', 'cnpj': cpf(529982247), 'zap': '16994567890', 'mail': 'maria.oliveira@email.com'}
BIANCA = {'name': 'Bianca Rocha', 'cnpj': cpf(318507264), 'zap': '16995678901', 'mail': 'bianca.rocha@email.com'}
NORTE = {'name': 'Lucas Ferreira', 'cnpj': cnpj(52640197), 'zap': '16996789012', 'mail': 'compras@graficanorte.com.br'}
RIBEIRAO = {'recipient': 'Maria Oliveira', 'street': 'Rua São Sebastião', 'number': '820', 'complement': 'Sala 4',
'district': 'Centro', 'city': 'Ribeirão Preto', 'state': 'SP', 'postal_code': '14015040'}
def order300(customer, palette, metres, delivery):
client = Client()
client.call('/session')
art = sheet(PALETTES[palette], 57, float(metres) * 100, px_per_cm=118)
uid = upload_bytes(client, png(art), name='aurora-folha-300dpi.png')
put_thumbnail(client, uid, png(art, 520))
item = item_spec('file', metres, 100, uid)
draft = {'request_key': str(uuid4()), 'items': [item], 'customer': customer,
'freight': {'service': 'mock-standard', 'postal_code': delivery['postal_code']}, 'destination': delivery}
quote = client.call('/quotes', draft)
approved_quote(client, quote, [item])
return client, client.call('/orders/dev-paid', {'quote_id': quote['id']})
# Finalizado, Imprimindo, Fila, Arte conferida, Correção, Arte recebida.
client, paid = order(BIANCA, 'rocha', 'file', '1.20', 100)
to(client, paid, ['final', 'tra', 'fil', 'imp', 'fin'])
client, paid = order(AURORA, 'aurora', 'file', '2.10', 100)
to(client, paid, ['final', 'tra', 'fil', 'imp', 'fin'])
client, paid = order(MARE, 'mare', 'uvfile', '1.00', 92)
to(client, paid, ['final', 'tra', 'fil', 'imp'])
client, paid = order(IPE, 'ipe', 'file', '1.60', 100)
to(client, paid, ['final', 'tra', 'fil'])
client, paid = order(AURORA, 'aurora', 'file', '1.30', 100)
to(client, paid, ['final', 'tra', 'fil'])
client, paid = order(MARIA, 'mare', 'file', '1.40', 85, RIBEIRAO)
to(client, paid, ['tra'])
client, paid = order(IPE, 'ipe', 'file', '2.30', 78)
to(client, paid, ['cor'], 'A arte ipe-folha.png está com fundo branco. Envie com fundo transparente.')
client, paid = order(MARE, 'mare', 'uvfile', '1.10', 92)
oid, version = to(client, paid, ['cor'], 'A arte está com 96 DPI. Envie em 300 DPI para não perder nitidez.')
fixed = sheet(PALETTES['mare'], 28.5, 110)
correction = upload_bytes(client, png(fixed), name='mare-folha-300dpi.png')
put_thumbnail(client, correction, png(fixed, 520))
client.call(f'/customer/orders/{oid}/corrections',
{'version': version, 'files': [{'item_index': 0, 'upload_id': correction}],
'note': 'Mandei de novo em 300 DPI.'})
client, paid = order(AURORA, 'aurora', 'file', '1.80', 100)
wait_print(client, paid['id'])
client, paid = order(BIANCA, 'rocha', 'file', '1.00', 100)
wait_print(client, paid['id'])
client.call(f"/operator/orders/{paid['id']}/contact",
{'waiting': True, 'note': 'Confirmar se quer a arte espelhada'}, operator=True)
# A quote above 50 m waits for the team.
client = Client()
client.call('/session')
art = sheet(PALETTES['norte'], 57, 400)
uid = upload_bytes(client, png(art), name='norte-folha.png')
put_thumbnail(client, uid, png(art, 520))
item = item_spec('file', '55.00', 100, uid)
client.call('/quotes', {'request_key': str(uuid4()), 'items': [item], 'customer': NORTE,
'freight': {'service': 'pickup'}})
# A payment that could not become an order, for the Pagamentos tab.
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.payment_events(id,provider,event_id,reference,status,amount_cents,payload,
processed_at,outcome) VALUES(%s,'mercadopago',%s,%s,'approved',4590,%s,now(),%s)''',
(uuid4(), f'{random.randint(10**10, 10**11)}:approved', str(uuid4()),
Jsonb({'provider': 'mercadopago', 'status': 'approved'}),
'refused: amount 4590 does not match the quote total 5190'))
c.execute("UPDATE dtf_local.operators SET name='Equipe Compor' WHERE email='operator@example.test'")
# Order #11: a 300 DPI sheet in Arte conferida, delivered by Correios PAC,
# for the panel shots (the "approve the final file" step).
client, paid = order300(MARIA, 'aurora', '1.00', RIBEIRAO)
wait_print(client, paid['id'])
to(client, paid, ['tra'])
# The corrected order back in Arte conferida, where the correction is approved.
client = Client()
o8 = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['number'] == 8)
client.call(f"/operator/orders/{o8['id']}/move", {'state': 'tra', 'version': o8['version'], 'reason': ''}, operator=True)
# Delivery orders show a real carrier, not the local simulated one.
with db.connect() as c:
c.execute("""UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{freight,description}','"Correios PAC"')
WHERE jsonb_typeof(snapshot->'destination')='object'""")
# Users and machines for the Usuários tab (all fictional).
admin = Client()
textil = admin.call('/operator/machines', {'name': 'Têxtil 1', 'products': ['textil']}, operator=True)['id']
admin.call('/operator/machines', {'name': 'UV 1', 'products': ['uv']}, operator=True)
for name, email, role, machines in (
('Ana Souza', 'ana@dropstar.test', 'admin', []), ('Diego Ramos', 'diego@dropstar.test', 'gestao', []),
('Bruno Souza', 'bruno@dropstar.test', 'operador', [textil]), ('Carla Dias', 'carla@dropstar.test', 'vendedor', [])):
admin.call('/operator/users', {'name': name, 'email': email, 'role': role, 'password': 'senha-de-exemplo-123',
'machines': machines}, operator=True)
# Pedro's account (Camisetas Ipê): it brings his orders, one in correction, for Minha conta.
from tests.smoke_test import register
with db.connect() as c:
doc = c.execute("SELECT snapshot->'customer'->>'cnpj' AS d FROM dtf_local.orders WHERE number=7").fetchone()['d']
pedro = Client(); pedro.call('/session')
register(pedro, {**IPE, 'cnpj': doc}, 'senha-de-exemplo-123')
# Spread the orders over recent days, so Números and the cards look lived-in.
from datetime import datetime, timedelta, timezone
now = datetime.now(timezone.utc)
plan = {1: (timedelta(days=6), 3), 2: (timedelta(days=4), 4), 3: (timedelta(hours=7), 1), 4: (timedelta(hours=3), 1),
5: (timedelta(hours=3.5), 1), 6: (timedelta(hours=2), 1), 7: (timedelta(hours=2.5), 1), 8: (timedelta(hours=3), 1),
9: (timedelta(hours=1), 1), 10: (timedelta(minutes=40), 1), 11: (timedelta(hours=2), 1)}
with db.connect() as c:
for number, (ago, gap) in plan.items():
oid = c.execute('SELECT id FROM dtf_local.orders WHERE number=%s', (number,)).fetchone()['id']
base = last = now - ago
for i, m in enumerate(c.execute('SELECT id FROM dtf_local.movements WHERE order_id=%s ORDER BY id', (oid,)).fetchall()):
last = base + timedelta(hours=gap * (i + 1))
c.execute('UPDATE dtf_local.movements SET created_at=%s WHERE id=%s', (last, m['id']))
c.execute('UPDATE dtf_local.orders SET created_at=%s, updated_at=%s WHERE id=%s', (base, last, oid))
print('seeded for the screenshots')

170
docs/guias/telas/shots.mjs Normal file
View File

@@ -0,0 +1,170 @@
// Screenshots for the guides, from the local stack seeded with fictional
// orders (seed.py). Runs in the browser-tests image: node shots.mjs <which>.
import {spawn} from 'node:child_process';
import {mkdtemp,readFile,writeFile,mkdir} from 'node:fs/promises';
import {tmpdir} from 'node:os';
const OUT='/shots';
const which=process.argv[2]||'kanban';
const profile=await mkdtemp(tmpdir()+'/dtf-shots-');
const chrome=spawn(process.env.CHROME_BIN||'/usr/bin/chromium',[
'--headless=new','--lang=pt-BR','--disable-gpu','--no-first-run','--no-sandbox','--hide-scrollbars','--font-render-hinting=none',
'--unsafely-treat-insecure-origin-as-secure=http://site,http://kanban',
'--remote-debugging-port=0','--user-data-dir='+profile,'about:blank'],{stdio:['ignore','ignore','pipe']});
const pause=ms=>new Promise(r=>setTimeout(r,ms));
async function waitFor(fn,what,timeout=30000){const end=Date.now()+timeout;while(Date.now()<end){try{if(await fn())return;}catch{}await pause(200);}throw new Error('Timeout: '+what);}
class Page{
constructor(ws){this.ws=ws;this.n=0;this.p=new Map();ws.onmessage=e=>{const d=JSON.parse(e.data);if(d.id&&this.p.has(d.id)){const x=this.p.get(d.id);this.p.delete(d.id);d.error?x.j(d.error):x.r(d.result);}};}
call(m,params={}){return new Promise((r,j)=>{const id=++this.n;this.p.set(id,{r,j});this.ws.send(JSON.stringify({id,method:m,params}));});}
async eval(e){const res=await this.call('Runtime.evaluate',{expression:e,awaitPromise:true,returnByValue:true});if(res.exceptionDetails)throw new Error(JSON.stringify(res.exceptionDetails).slice(0,400));return res.result.value;}
async size(w,h){await this.call('Emulation.setDeviceMetricsOverride',{width:w,height:h,deviceScaleFactor:2,mobile:false});await pause(300);}
async rect(selector,pad=0){return this.eval(`(()=>{const el=${selector.startsWith('(')?selector:`document.querySelector(${JSON.stringify(selector)})`};
const r=el.getBoundingClientRect();return {x:Math.max(0,r.left-${pad})+scrollX,y:Math.max(0,r.top-${pad})+scrollY,width:r.width+2*${pad},height:r.height+2*${pad}};})()`);}
async shot(name,clip){
const res=await this.call('Page.captureScreenshot',{format:'png',captureBeyondViewport:true,...(clip?{clip:{...clip,scale:1}}:{})});
await writeFile(`${OUT}/${name}.png`,Buffer.from(res.data,'base64'));console.log('shot',name,clip?Math.round(clip.width)+'x'+Math.round(clip.height):'page');
}
async el(name,selector,pad=0){await pause(250);await this.shot(name,await this.rect(selector,pad));}
}
let port;
await waitFor(async()=>{port=Number((await readFile(profile+'/DevToolsActivePort','utf8')).split('\n')[0]);return port;},'chrome');
async function open(url,w=1440,h=1000){
const tab=await (await fetch(`http://localhost:${port}/json/new?about:blank`,{method:'PUT'})).json();
const ws=new WebSocket(tab.webSocketDebuggerUrl);await new Promise((r,j)=>{ws.onopen=r;ws.onerror=j;});
const p=new Page(ws);await p.call('Runtime.enable');await p.call('Page.enable');await p.size(w,h);
await p.call('Emulation.setLocaleOverride',{locale:'pt-BR'}).catch(()=>{});
await p.call('Network.enable').catch(()=>{});await p.call('Network.setUserAgentOverride',{userAgent:'Mozilla/5.0 Chrome/130 Safari/537.36',acceptLanguage:'pt-BR'}).catch(()=>{});
await p.call('Page.navigate',{url});await waitFor(()=>p.eval('document.readyState==="complete"'),'load '+url);await pause(800);return p;
}
await mkdir(OUT,{recursive:true});
try{
if(which==='kanban'){
const k=await open('http://kanban/',1440,1000);
await waitFor(()=>k.eval('!document.getElementById("login").hidden'),'login form');
await k.el('login','#login',24);
await k.eval(`(()=>{email.value=${JSON.stringify(process.env.OPERATOR_EMAIL||'operator@example.test')};password.value=${JSON.stringify(process.env.OPERATOR_PASSWORD||'local-operator-only')};
document.getElementById('login').requestSubmit();})()`);
await waitFor(()=>k.eval('typeof board!=="undefined"&&!!board&&board.orders.length>0'),'board');
// No refresh while shooting: the timer would repaint over the shots.
// No refresh while shooting: the timer would repaint over the shots.
await k.eval(`(()=>{window.load=async()=>{};})()`);
await pause(1500);
await k.shot('quadro',{x:0,y:0,width:1440,height:700});
const id=n=>`board.orders.find(o=>o.number===${n}).id`;
// The print queue column, top part.
await k.el('fila','(document.querySelector(\'section.col[data-state="fil"]\'))',0).catch(e=>console.log('fila',e.message));
// Panel of an order waiting for its final file.
await k.size(1440,1900);
await k.eval(`document.querySelector('[data-card="'+${id(11)}+'"]').click()`);
await waitFor(()=>k.eval(`!!document.querySelector('[data-order="'+${id(11)}+'"]')`),'panel');await pause(1200);
await k.shot('painel',{...(await k.rect('#panel')),height:900});
await k.el('arquivo-final','#panel .nextstep.lead',0);
await k.eval(`document.querySelector('#panel .more').click()`);await pause(300);
await k.shot('menu',{...(await k.rect('#panel')),height:520});
await k.eval(`document.body.click()`);
// An order in correction, and one whose correction came back.
for(const [n,name] of [[7,'correcao'],[8,'correcao-recebida'],[10,'contato']]){
await k.eval(`closePanel&&closePanel()`).catch(()=>{});await pause(300);
await k.eval(`document.querySelector('[data-card="'+${id(n)}+'"]').click()`);
await waitFor(()=>k.eval(`!!document.querySelector('[data-order="'+${id(n)}+'"]')`),'panel '+n);await pause(1200);
if(name==='correcao-recebida')await k.el(name,'#panel .nextstep.lead',0);
else if(name==='contato')await k.el(name,'#panel .callout.contact',0);
else await k.shot(name,{...(await k.rect('#panel')),height:350});
}
await k.eval(`closePanel&&closePanel()`).catch(()=>{});
await k.size(1440,1000);
// Quotes, payments, numbers.
await k.eval(`document.querySelector('[data-tab="quotes"]').click()`);await pause(1500);
await k.eval(`document.querySelector('#quote-list button, #quote-list [data-quote], #quote-list li')?.click()`).catch(()=>{});await pause(1500);
await k.shot('cotacoes',{x:0,y:0,width:1440,height:1000});
await k.eval(`document.querySelector('[data-tab="payments"]').click()`);await pause(1500);
await k.shot('pagamentos',{x:0,y:0,width:1440,height:300});
await k.eval(`document.querySelector('[data-tab="stats"]').click()`);await pause(2000);
await k.shot('numeros',{x:0,y:0,width:1440,height:900});
// Users and the edit dialog.
await k.eval(`document.querySelector('[data-tab="users"]').click()`);await pause(1500);
await k.el('usuarios','#tab-users',0);
await k.eval(`[...document.querySelectorAll('#users-list tr')].find(tr=>tr.textContent.includes('Bruno')).querySelector('button').click()`);await pause(600);
await k.el('usuario-editar','.modal-box',0);
await k.eval(`document.querySelector('.modal').remove()`);
// Integrações as in production, with fictional values; the folder as on the print room's computer.
await k.eval(`document.querySelector('[data-tab="integrations"]').click()`);await pause(1200);
await k.eval(`(()=>{window.syncFolder=async()=>{};window.load=async()=>{};
const now=new Date(),at=h=>new Date(now-h*3600e3).toISOString();
board.tiny={configured:true,connected:true,connected_by:'tiny@dropstar.test',orders_enabled:true,offline:true,connected_at:at(72),renewed_at:at(2)};
board.providers={...board.providers,payment:'mercadopago',
freight:{services:{jadlog:'Jadlog',pac:'Correios PAC',sedex:'Correios SEDEX'},box_cm:['63','15.5','15.5'],production_days:1,
base_kg:'0.3',per_metre_kg:'0.075',cubage_kg_m3:'300',cubed_kg:'4.541',metres_per_box:'60'},
mail:{adapter:'smtp',pending:0,last_sent:at(1),from:'nao-responda@dropstardtf.com.br'},
backup:{last_ok:new Date(now.getFullYear(),now.getMonth(),now.getDate(),3,0).toISOString(),bytes:418000,failed:null,requested:false}};
FOLDER.mode='folder';FOLDER.handle={name:'FlexiPRINT'};FOLDER.granted=true;FOLDER.when='rec';FOLDER.error='';FOLDER.status='';
FOLDER.saved=new Map(Array.from({length:12},(_,i)=>['u'+i,{place:'queue'}]));FOLDER.last=new Date(now-25*60e3);
renderIntegrations();})()`);
await pause(600);
await k.el('integracoes','#integrations',0);
await k.eval(`document.querySelector('#folder-card .integ-more').click()`);await pause(400);
await k.el('pasta','#folder-card',0);
await k.eval(`(()=>{FOLDER.granted=false;OPEN_INTEG.clear();paintFolder();})()`);await pause(400);
await k.el('pasta-liberar','#folder-card',0);
await k.el('aba-aviso','[data-tab="integrations"]',10);
}
if(which==='site'){
// Minha conta: the overview, and an order waiting for a correction.
if(process.argv[3]!=='cart'){const c=await open('http://site/conta/entrar',1440,1000);
await waitFor(()=>c.eval('!!document.getElementById("login")'),'portal');
await c.eval(`(()=>{document.getElementById('email').value='pedidos@camisetasipe.com.br';
document.getElementById('password').value='senha-de-exemplo-123';document.getElementById('login').requestSubmit();})()`);
await pause(2500);
await c.call('Page.navigate',{url:'http://site/conta'});await pause(2500);
await c.eval(`(()=>{for(const el of document.querySelectorAll('body *'))if(el.children.length===0&&el.textContent.includes('Ambiente de desenvolvimento local'))el.closest('div,p,section').style.display='none';window.scrollTo(0,0);})()`);await pause(400);
await c.shot('conta',{x:0,y:0,width:1440,height:540});
const seven=await c.eval(`fetch('/api/customer/orders?page=1&size=10').then(r=>r.json()).then(d=>(d.items.find(i=>i.number===7)||d.items.find(i=>i.state==='cor')).id)`);
await c.call('Page.navigate',{url:'http://site/conta/pedidos?order='+seven});await pause(2500);
await c.eval(`(()=>{for(const el of document.querySelectorAll('body *'))if(el.children.length===0&&el.textContent.includes('Ambiente de desenvolvimento local'))el.closest('div,p,section').style.display='none';window.scrollTo(0,0);})()`);await pause(400);
await c.shot('pedido-correcao',{x:0,y:0,width:1440,height:960});}
// The cart: artworks added for real, then the customer's details and the delivery options.
const s=await open('http://site/',1440,1000);
await waitFor(()=>s.eval(`typeof window.dtfCheckout==="function"&&!!document.querySelector('[data-modo="avulsa"]')`),'site');
await s.eval(`document.querySelector('[data-modo="avulsa"]').click()`);await pause(800);
await s.eval(`(async()=>{
const make=async(name,w,h,draw)=>{const c=document.createElement('canvas');c.width=w;c.height=h;const x=c.getContext('2d');draw(x,w,h);
return new File([await new Promise(r=>c.toBlob(r,'image/png'))],name,{type:'image/png'});};
const files=[await make('logo-frente.png',2362,1417,(x,w,h)=>{x.fillStyle='#F26B1D';x.beginPath();x.roundRect(0,0,w,h,120);x.fill();
x.fillStyle='#FFD23F';x.beginPath();x.arc(w*.24,h/2,h*.32,0,7);x.fill();x.fillStyle='#fff';x.font='bold '+(h*.26)+'px sans-serif';x.fillText('AURORA',w*.44,h*.6);}),
await make('escudo.png',1181,1181,(x,w,h)=>{x.fillStyle='#1B998B';x.beginPath();x.arc(w/2,h/2,w/2,0,7);x.fill();x.fillStyle='#fff';
x.font='bold '+(h*.2)+'px sans-serif';x.textAlign='center';x.fillText('ESCUDO',w/2,h*.57);}),
await make('patrocinio.png',2835,472,(x,w,h)=>{x.fillStyle='#E84855';x.fillRect(0,0,w,h);x.fillStyle='#fff';x.font='bold '+(h*.5)+'px sans-serif';
x.textAlign='center';x.fillText('PATROCÍNIO',w/2,h*.68);})];
const dt=new DataTransfer();files.forEach(f=>dt.items.add(f));
const inp=document.getElementById('inp');inp.files=dt.files;inp.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await waitFor(()=>s.eval('artes.length===3&&artes.every(a=>a.src)'),'artworks measured',30000);
for(const [i,cm,q] of [[0,20,4],[1,10,8],[2,24,3]]){
await s.eval(`(()=>{const set=(sel,v)=>{const el=document.querySelectorAll(sel)[${i}];el.value=v;el.dispatchEvent(new Event('change',{bubbles:true}));};
set('[data-cm]',${cm});set('[data-q]',${q});})()`);await pause(500);
}
await pause(1200);
await s.eval(`(()=>{const c=document.getElementById('cienteOk');if(c&&!c.checked){c.checked=true;c.dispatchEvent(new Event('change',{bubbles:true}));}})()`);
await waitFor(()=>s.eval('!!itemAtual&&itemPodeEnviar(itemAtual)'),'item ready for the cart',60000);
await s.eval(`document.getElementById('bAdd').click()`);
await waitFor(()=>s.eval('location.pathname==="/carrinho"'),'cart page',20000);
await waitFor(()=>s.eval(`document.getElementById('carr').innerText.includes('Arquivos enviados')&&!document.getElementById('carr').innerText.includes('verificando')`),'uploads done',180000);
await s.eval(`(()=>{const g=id=>document.getElementById(id);const fill=(id,v)=>{const el=g(id);el.value=v;el.dispatchEvent(new Event('input',{bubbles:true}));};
fill('fNome','Juliana Martins');fill('fCnpj','31920485000165');fill('fZap','16991234567');fill('fMail','contato@estampariaaurora.com.br');
entrega.tipo='frete';entrega.cep='14015040';g('cepIn').value='14015-040';
entrega.opcoes=[{service:'pac',description:'Correios PAC',days:7,total_cents:2183},{service:'jadlog',description:'Jadlog',days:5,total_cents:2690},
{service:'sedex',description:'Correios SEDEX',days:3,total_cents:4417}];
entrega.servico='pac';entrega.valor=21.83;entrega.dias=7;entrega.cotado=true;
entrega.end={nome:'Juliana Martins',rua:'Rua São Sebastião',num:'820',comp:'Sala 4',bairro:'Centro',cidade:'Ribeirão Preto',uf:'SP'};
for(const [id,k] of [['eNome','nome'],['eRua','rua'],['eNum','num'],['eComp','comp'],['eBairro','bairro'],['eCidade','cidade'],['eUf','uf']])g(id).value=entrega.end[k];
pintaFretes();pintaEntrega();if(typeof pintaPedido==='function')pintaPedido();window.scrollTo(0,0);})()`);
await pause(800);
const h=await s.eval(`Math.ceil(document.getElementById('fretes').getBoundingClientRect().bottom+28)`);
await s.shot('carrinho',{x:0,y:0,width:1440,height:h});
// The order confirmation e-mail, as the customer's mail app shows it.
const m=await open('file:///g/email-pedido.html',720,1000);
const mh=await m.eval('Math.ceil(document.body.scrollHeight)');
await m.shot('email-pedido',{x:0,y:0,width:720,height:mh});
}
}catch(e){console.error(e);process.exitCode=1;}
finally{chrome.kill();}

View File

@@ -24,9 +24,12 @@ server {
try_files /index.html =404; try_files /index.html =404;
} }
# The customer's area: one page, which shows the right part for each address. # The customer's area: one page, which shows the right part for each address.
location ~ ^/conta(/(entrar|pedidos|dados))?/?$ { location ~ ^/conta(/(entrar|pedidos|dados|redefinir))?/?$ {
try_files /portal.html =404; try_files /portal.html =404;
} }
location ~ ^/termos/?$ {
try_files /termos.html =404;
}
location / { try_files $uri $uri/ =404; } location / { try_files $uri $uri/ =404; }
} }
server { server {

View File

@@ -28,9 +28,9 @@ botocore==1.38.46 \
# via # via
# boto3 # boto3
# s3transfer # s3transfer
certifi==2026.7.22 \ certifi==2026.10.19 \
--hash=sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775 \ --hash=sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae \
--hash=sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55 --hash=sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b
# via # via
# httpcore # httpcore
# httpx # httpx
@@ -295,94 +295,90 @@ pikepdf==10.13.0.post1 \
--hash=sha256:f7962a75cf22d0d683b49ab19b8966e94dc7014d9aa6806f3c0d2b37fb9ae607 \ --hash=sha256:f7962a75cf22d0d683b49ab19b8966e94dc7014d9aa6806f3c0d2b37fb9ae607 \
--hash=sha256:fb05fb7b42d85754219b55111aa61beff4e48da56069e971de1e5aca380c0ac1 --hash=sha256:fb05fb7b42d85754219b55111aa61beff4e48da56069e971de1e5aca380c0ac1
# via -r infra/requirements.txt # via -r infra/requirements.txt
pillow==12.3.0 \ pillow==13.0.0 \
--hash=sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756 \ --hash=sha256:02464da86f561f410e13b061ec37c3068a9cb557a095494157742d07b3c24a27 \
--hash=sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a \ --hash=sha256:04a63720f79e22fd54d897c233a68314c50ca0603360f54ce2bd5db8f0f43782 \
--hash=sha256:06ff022112bc9cbf83b60f8e028d94ad87b60621706487e65f673de61610ab59 \ --hash=sha256:05cd2cd39055d0b9650060e4513ef4a9a0aea870083950bd046a0d6490f93a22 \
--hash=sha256:0740a512dc522224c77d9aa5a8d70d8b7d73fb91f2c21125d8d025d3b8990e45 \ --hash=sha256:06903aac074d00c988e77a1fc435286dc498506d4ca8d6f69df9babddf4ecc15 \
--hash=sha256:0847a763afefb695bc912d7c131e7e0632d4edc1d8698f58ddabec8e46b8b6d3 \ --hash=sha256:08b826a9bf1265c76de04a42061d61ea6b109418b7826f28ff1ecdfaa26c5502 \
--hash=sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df \ --hash=sha256:0d1a9cf7bc6917538b20f8d06b9ab2147e542f68849e96fc58eb66bdf6acc692 \
--hash=sha256:0feb2e9d6ad6c9e3c06effe9d00f3f1e618a6643273576b016f591e9315a7139 \ --hash=sha256:10b5019883c98f1dd819ca48ffc6f33a91cee04948fe637c605f4345c7cafd6f \
--hash=sha256:10e41f0fbf1eec8cfd234b8fe17a4caac7c9d0db4c204d3c173a8f9f6ef3232b \ --hash=sha256:12b0fa15879fe5a9d9eebe66e4e2d74128a773b1a4448010c9c714f45e04b9d8 \
--hash=sha256:1182d52bc2d5e5d7d0949503aa7e36d12f42205dc287e4883f407b1988820d39 \ --hash=sha256:12fbb851cf323cc19aac3eea1df5ad17b57e91e9fe3cfd06100dba7bb8208c13 \
--hash=sha256:164b31cd1a0490ab6efae01aa5df49da7061be0af1b30e035b6e9a1bfe34ee6e \ --hash=sha256:149a1c323ba366f90b48e6f1a6db6582eb50512df374588de56fc909abc0f0f3 \
--hash=sha256:1657923d2d45afb66526e5b933e5b3052e6bdea196c90d3abb2424e18c77dae8 \ --hash=sha256:19b66ca0a4d25cc0200b381ce824c7ea090db61427315e73cfb05dbf1b35c369 \
--hash=sha256:186941b6aef820ad110fb01fb06eb925374dc3a21b17e37ec9a53b250c6fe2d1 \ --hash=sha256:1c774b9c0ba0d0b356f71530677b39028878a2cae5a93e0a13779cfd17120f88 \
--hash=sha256:1cca606cd25738df4ed873d5ad46bbdb3d83b5cbca291f6b4ff13a4df6b0bbe8 \ --hash=sha256:20722cd5375533ad754053363a80b8fb30c79d37930a6f7228030e237ce3bd5d \
--hash=sha256:21900ce7ba264168cd50defae43cd75d25c833ad4ad6e73ffc5596d12e25ac89 \ --hash=sha256:20822140c9a2ba9c5e42df342b0a892ab2e102fc0e3db967a133bb9ce3f898bb \
--hash=sha256:236ff70b9312fb68943c703aa842ca6a758abfa45ac187a5e7c1452e96ef72b5 \ --hash=sha256:21c32061a5512dc13f87cc7303e120e4d77c2f70df89a35af0e3ce246e5ac57f \
--hash=sha256:23aceaa007d6172b02c277f0cd359c79492bbb14f7072b4ede9fbcaf20648130 \ --hash=sha256:2310e2adfc13c6d457d7d0f2ffdd5c56a74a317650cf765887df8d515a647ac0 \
--hash=sha256:23d27a3e0307ec2244cc51e7287b919aa68d097504ebe19df4e76a98a3eea5bd \ --hash=sha256:23edf4ec4b6f4f240e8df6e4985e9ee2ced86474632433e55fb1e2548744bf40 \
--hash=sha256:24870b09b224f7ae3c39ed07d10e819d06f8720bc551847b1d623832b5b0e28d \ --hash=sha256:2d50500a4a3bc6469adcdb319cf05d688b08ca3bf0f22a05339f3b25b433a599 \
--hash=sha256:251bf95b67017e27b13d82f5b326234ca62d70f9cf4c2b9032de2358a3b12c7b \ --hash=sha256:2e31c4e68cffd7b1f116127626813b82fcba19edf6b940a7b0c266d6484d0055 \
--hash=sha256:25b9b82bb22e6e2b3cd07b39c68b7b862001226cb3dff7130d1cb914121b39ed \ --hash=sha256:34fb3db1149c879343861831728c243c432d4a5afc8f1878ca7612ef8de2a033 \
--hash=sha256:28ce87c5ab450a9dd970b52e5aca5fe63ed432d18a2eaddd1979a00a1ba24ace \ --hash=sha256:37290fbef0c73e2d51d594eb78fded7dc7170d1c3ad0a890269e6fd8c8c4e061 \
--hash=sha256:300557495eb45ebb8aec96c2da9c4be642fbf7cd937278b4013ba894ea8eb0eb \ --hash=sha256:405be6058e206a86fedce2f715ecc2343f94072d7925251632dffa2c05f70dca \
--hash=sha256:30f2aa603c41533cc25c05acd0da21636e84a315768feb631c937177db558931 \ --hash=sha256:40a266371ece581e5de13b6635ef78d7487824af80561b6ca27694a88c19bc0f \
--hash=sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510 \ --hash=sha256:42d63be3af4f9b951b199b0a9d23365d37ab14687e6d77b74940432c8515c4ca \
--hash=sha256:37d6d0a00072fd2948eb22bce7e1475f34569d90c87c59f7a2ec59541b77f7a6 \ --hash=sha256:44629d4498c9cb6b2051806155f22141df0d8a929c56134b166655232dfb2f8c \
--hash=sha256:37dc8f7bbb66efe481bb60defacef820c950c24713fb44962ed6aa2a50966de1 \ --hash=sha256:49c12af515073e9bf511e4ef736743bf70d531a643668722279314b937742ba4 \
--hash=sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce \ --hash=sha256:4a25756244bdcce3b50580baadf320fa48297f0eeb8e114ba64139a40d4d0fc8 \
--hash=sha256:3edce1d53195db527e0191f84b71d02022de0540bf43a16ed734ed7537b07385 \ --hash=sha256:4bd024d567eca931b668978d672dba914d4b8e2628e2c3073a2ad178de8a2620 \
--hash=sha256:446c34dcc4324b084a53b705127dc15717b22c5e140ae0a3c38349d4efec071e \ --hash=sha256:4f8db54177035a2b5f717f94475b74907e12a96dc74f6d487f3966b0a4694071 \
--hash=sha256:4998562bf62a445225f22e07c896bb04b35b1b1f2eb6d760584c9c51d7a5f78c \ --hash=sha256:51ebb529fc5e8abdd55302f6c3f8943037348ec2384329a3e55677f69ae2fdfc \
--hash=sha256:4b0a7fe987b14c31ebda6083f74f22b561fd3739bc0ac51e019622e3d72668c7 \ --hash=sha256:567f20f1c75897d7663830da6ea8af719e03d712b1d9ee7f813319f9ece42e5a \
--hash=sha256:4e8c2a84d977f50b9daed6eeaf3baef67d00d5d74d932288f02cb94518ee3ace \ --hash=sha256:5933fcea5a5ba64c686f55c886a115cbfd92f2900460784a1e79909fdbafd7b6 \
--hash=sha256:4f883547d4b7f0495ebe7056b0cc2aea76094e7a4abc8e933540f3271df27d9c \ --hash=sha256:5bdb38ba220b61b4ec31dd1046dea6b016d3c6850a23f43ed8b58332b2fc668e \
--hash=sha256:514435a37670e3e5e08f3945b68718b6ed329bb84367777e16f9f4dfe1e61a0f \ --hash=sha256:5f56499c1a74d2b862beb0c33b8016f99d095858455df9d21583bbbc1c15b582 \
--hash=sha256:53aa02d20d10c3d814d536aa4e5ac9b84ca0ff5a88377963b085ad6822f93e64 \ --hash=sha256:67871a13cf47275201553b536c025da777f997fa562a19eb798af4ad4b97c18f \
--hash=sha256:5594fc43d548a7ed94949d139aa1341b270f1863f11cfd37f5a6c8b778a6b67f \ --hash=sha256:67c8d44ad89fa7eb88de5d6ef6199b1e03dd24974f85a67639fc8badb801fe79 \
--hash=sha256:571b9fcb07b97ef3a492028fb3d2dc0993ca23a06138b0315286566d29ef718a \ --hash=sha256:6a0920cb55df5a4d3f6862964908078c0bd59332bdd1bcd20d14e8c70ef27cc5 \
--hash=sha256:57b3d78c95ba9059768b10e28b813002261d3f3dfc55cc48b0c988f625175827 \ --hash=sha256:6bce6a29c3898191f4c9998e4d4e8f69790caeabde46e54da4bc235ce5bde683 \
--hash=sha256:5afb51d599ea772b8365ae807ae557f18bccfe46ab261fd1c2a9ed700fc6eb17 \ --hash=sha256:6f38f3f885a09cafc93fd667b1173a92f379e43785d635e7983c893f0da319fb \
--hash=sha256:6b02afb9b97f65fbca5f31db6a2a3ba21aa93030225f150fa3f249717e938fb4 \ --hash=sha256:73ee25cf8cf8b75d5a5aeed7cb6588f5e5dbfbb0fde51707b630bbb23897645c \
--hash=sha256:6c0016e7b354317c4e9e525b937ac8596c38d2d232b419529b9cd7a1cd46e39a \ --hash=sha256:7b999816b5850a35ada08443e6e03945f1f6488144a83afe2d37b240a552aafa \
--hash=sha256:71d6097b330eea8fd15097780c8e89cb1a8ce7838669f48c5bacd6f663dd4701 \ --hash=sha256:7c88c10dd432f3b39ccdafc9ed81d0c21b8fd634502574da76d1bfa4fe2c76d0 \
--hash=sha256:756c768d0c9c2955feb7a56c37ea24aea2e369f8d36a88da270b6a9f19e62b5e \ --hash=sha256:7d5e097eabd5d4915c27ac9f6e9325bb1e01a7c94d7348b5c4451d3fc30e8521 \
--hash=sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91 \ --hash=sha256:7e91e97a929232cdb828889ee6ad0e48d7f40f4ec38818f4e4a8968b2b1af22e \
--hash=sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66 \ --hash=sha256:7f6299e494e46253d40c34653cac369412f44ca53b5f85d848d3f95b1ed0546c \
--hash=sha256:85f998ea1848bc6757289e739cfbdda3a04adfd58b02fc018ce54d754a5ce468 \ --hash=sha256:816752a5ef76a80484c8c441c85593b7ea9304f6231fc5776ad1fbff7e773058 \
--hash=sha256:8728f216dcdb6e6d555cf971cb34076139ad74b31fc2c14da4fafc741c5f6217 \ --hash=sha256:83b37abd87b590acd8f47ca8a61f70893322b11834d36e07c2298dacad4d14d2 \
--hash=sha256:877c3f311ff35410f690861c4409e7ccbf0cd2f878e50628a28e5a0bb689e658 \ --hash=sha256:8619685cad8efc4c38c66d3b36aad854523297c43d748b3b6f0cc03c90ba3463 \
--hash=sha256:8cd2f7bdda092d99c9fc2fb7391354f306d01443d22785d0cbfafa2e2c8bb418 \ --hash=sha256:8bf295fe459343bc6093c8e5e0df60bfa189e0fcb775a22e2c2488fdeccc6c0d \
--hash=sha256:8e95e1385e4998ae9694eeaa4730ba5457ff61185b3a55e2e7bea0880aef452a \ --hash=sha256:8e459b613cf31f8980f584387b4fe47bf08e076e288d61aa8eba1f7fd4ddbb81 \
--hash=sha256:962864dc93511324d51ddbb5b9f8731bf71675b93ca612a07441896f4688fb8c \ --hash=sha256:8f36aa77f74b14a2103622b196402c71330e4e7cf4122ee45c854e9a01e0eecf \
--hash=sha256:9cf95fe4d0f84c82d282745d9bb08ad9f926efa00be4697e767b814ce40d4330 \ --hash=sha256:93ff9c9c3663ce23aaa5d0b6b6abac55359e2a0c06c7e30f3771829af816be63 \
--hash=sha256:9e881fca225083806662a5c43d627d215f258ff43c890f831966c7d7ba9c7402 \ --hash=sha256:9a635068d9793c7f0d929f39f18b58f1bd86c236e8e7b64167b86af9232ebca0 \
--hash=sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09 \ --hash=sha256:9dda0788a9932776a75d8bcc020076edc308ce2508b51f6739a45e3158b3fc42 \
--hash=sha256:a45650e8ce7fafffd731db8550230db6b0d306d181a90b67d3e6bca2f1990930 \ --hash=sha256:a192360d512305fe92d3053e4f7627bbad1f7708f1f4ad38cccd9336acabe9ad \
--hash=sha256:a876864214e136f0eb367788dbd7df045f4806801518e2cfe9e13229cfe06d8f \ --hash=sha256:a2a14cd73d5e6c927f644b0110ee81f59c4ef506259ec9183904747f2caacc81 \
--hash=sha256:ae26d61dfa7a47befdc7572b521024e8745f3d809bd95ca9505a7bba9ef849ec \ --hash=sha256:a625df9a2a5597fa5e5266e01aefc82604bb85d291e3547981e863560d75da6c \
--hash=sha256:af8d94b0db561cf68b88a267c5c44b49e134f525d0dc2cb7ed413a66bc23559a \ --hash=sha256:a6aaa7871aebca081eb5c45f83e845bbd9712ae99fa9286dbfdcee835e63f4b4 \
--hash=sha256:b343699e8308bdc51978310e1c959c584e7869cc8c40780058c87da7781a1e94 \ --hash=sha256:aa694c49787040943570d61c9b8fc01271bd2a2cfdd55f0d896f8aecdce1a981 \
--hash=sha256:b3c777e849237620b022f7f297dd67705f9f5cf1685f09f02e46f93e92725468 \ --hash=sha256:adb3c2124c68e480f4632d06cb7caa3b48a51678475f483b4edb1c6dee29ea43 \
--hash=sha256:b629de27fda84b42cde7edef0d85f13b958b47f6e9bbcbba9b673c562a89bd8b \ --hash=sha256:b84be41387fc00db28c13c02e30d42b02d8d8f6a4a741a1aee6012ca7f1f6039 \
--hash=sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965 \ --hash=sha256:bf97ba1b5542050e9b0c74e632323b6d8136cc99d64e193abebee22fe6013c76 \
--hash=sha256:ba54cfebe86920a559a7c4d6b9050791c20513650a1952ebe3368c7dc70306f8 \ --hash=sha256:c3bc8ee0271387e0b1e3ad0ff893645990a656e79bf9c42f4f734a3642b11d51 \
--hash=sha256:bcb46e2f9feff8d06323983bd83ed00c201fdcab3d74973e7072a889b3979fcd \ --hash=sha256:c50c80e3591e5cf9a8dfa6007d4f10732f02e32263850999286e56ccd650cfb2 \
--hash=sha256:bcc33feacfaefce60c12fd500a277533bdc02b10a19f7f6d348763d8140bbba7 \ --hash=sha256:c6fd031333dedcad7ce3e03d244093f43504f209e86925ebdb2b868fa4037630 \
--hash=sha256:bf16ba1b4d0b6b7c8e534936632270cf70eb00dbe09005bc345b2677b726855c \ --hash=sha256:c87a04e7f152ee4db5dbe15f0bfa3fe628a1aeedbe66b81c43b87f52c813f9ac \
--hash=sha256:cf1845d02ad822a369a49f2bb9345b1614744267682e7a03527dc3bf6eea1777 \ --hash=sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510 \
--hash=sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35 \ --hash=sha256:d4737f50d23ddd11d6685faacbb9252887dde0bc7997127757247983d74399d6 \
--hash=sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9 \ --hash=sha256:d7710eb676e9bb68965cb045be0d333b4c0d7f9dfbaa7fbf121385b1588683d3 \
--hash=sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f \ --hash=sha256:d9b0a2bee3f3e03e9f29057aedb807dbf1e1d96ee1b9d0f422d9db6c8583271d \
--hash=sha256:dc624f6bc473dacdf7ef7eb8678d0d08edf15cd94fad6ae5c7d6cc67a4e4902f \ --hash=sha256:e65dd6e75de67b2362a4fa3e16aa627595f65054dc4ec73d64680c84d592fa61 \
--hash=sha256:e158cb00350dc278f3b91551101aa7d12415a66ebf2c91d8d5ac14e56ddd3ad0 \ --hash=sha256:e892354a424b1e82a78ba16785822bdd40de06f19446a3d4a28047df1a4f8932 \
--hash=sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c \ --hash=sha256:e8ca8f69b7c77fa96dad99f8638c1fc4f1c0bed4acaa1baf7a3c31bdb80a0ab1 \
--hash=sha256:e795b7eb908249c4e43c7c99fac7c2c75dab0c43566e37db472a355f63693d71 \ --hash=sha256:e91c2b1cbeae768c98752e67e717e283d68dae45717b41f2d91eaee648e37b7d \
--hash=sha256:e7e480451b9fa137494bccd3a7d69adbe8ac65a87d97be61e11f1b1050a5bac3 \ --hash=sha256:e98b4f91f99b24b1da72e10621ba181f7281922384a7403094debb4199de6c00 \
--hash=sha256:e91206ee562682b51b98ef4b26a6ef48fd84e15fd4c4bc5ec768eb641d206838 \ --hash=sha256:ef5fe6b7db3f501c56000ba8fe7c7e1a35ca1d45824fbeb95a67daa85cff4dbe \
--hash=sha256:e9871b1ffbfa9656b60aeee92ed5136a5742696006fa322b29ea3d8da0ecc9cf \ --hash=sha256:f11a3c1358bb3c68012a7b1f41b223c3db9f7bfde90b481df028cfe1c3363313 \
--hash=sha256:e9aeb04d6aef139de265b29683e119b638208f88cf73cdd1658aa07221165321 \ --hash=sha256:f391dc92a015c478745192fe4f2e120c2af2aba18d9fe0616341cbf537599806 \
--hash=sha256:ebaea975e03d3141d9d3a507df75c9b3ec90fa9d2ffd07567b3a978d9d790b26 \ --hash=sha256:f7cbb7a64e7ec664775195e4f81923bc8a93d9451b963f844e59118f63147a7a \
--hash=sha256:f0606c8bf2cdefea14a43530f7657cbbb7ecf1c4222512492ef4a4434a9501ec \ --hash=sha256:f9bd7d260d986f3553518c5d723544346fa48031f8aef3265d786aeb59845bc0 \
--hash=sha256:f13c32a3abd6079a66d9526e18dad9b6d280384d49d7c54040cd57b6424041d9 \ --hash=sha256:fc481f742ccda20e9ed760b8f978dff50f2a4e9bc253ac167fb0a05b0783ef52 \
--hash=sha256:f7401aebd7f581d7f83a439d87d474999317ee099218e5ad25d125290990ba65 \ --hash=sha256:ff3fe9eb621fbb9db4c4be33ab946f6bac5f98ab50ca8d3260503653656c961b \
--hash=sha256:fa4ecea169a355be7a3ade2c783e2ed12f0e40d2c5621cda8b3297faf7fbb9f5 \ --hash=sha256:ffea6b2986a797c84b6d1d27d4f43e0b83c73fc16281a930891cd237cf0d08fe
--hash=sha256:fbd139c8447d25dd750ab79ee274cc5e1fe80fc56340ab10b18a195e1b6eca3e \
--hash=sha256:fdafc9cce40277e0f7a0feabce0ee50dd2fa1800f3b38015e51296b5e814048d \
--hash=sha256:fe3cca2e4e8a592be0f269a1ca4835c25199d9f3ce815c8491048f785b0a0198 \
--hash=sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7
# via # via
# -r infra/requirements.txt # -r infra/requirements.txt
# pikepdf # pikepdf

View File

@@ -4,5 +4,5 @@ uvicorn==0.34.2
psycopg[binary]==3.2.9 psycopg[binary]==3.2.9
boto3==1.38.23 boto3==1.38.23
httpx==0.28.1 httpx==0.28.1
pillow==12.3.0 pillow==13.0.0
pikepdf==10.13.0.post1 pikepdf==10.13.0.post1

View File

@@ -43,6 +43,8 @@ PREFIX = 'db/'
RETRY = timedelta(hours=1) RETRY = timedelta(hours=1)
# A backup older than this means the daily run has stopped working. # A backup older than this means the daily run has stopped working.
STALE = timedelta(hours=26) STALE = timedelta(hours=26)
# How often the service looks for a "Fazer backup agora" from the Kanban.
POLL = 60
TABLES = ('orders', 'quotes', 'uploads', 'accounts', 'movements', 'payment_intents') TABLES = ('orders', 'quotes', 'uploads', 'accounts', 'movements', 'payment_intents')
@@ -167,8 +169,13 @@ def serve():
now = datetime.now(timezone.utc) now = datetime.now(timezone.utc)
# A fresh deployment, or one that missed a day, backs up straight away. # A fresh deployment, or one that missed a day, backs up straight away.
due = now if previous is None or now - previous > STALE else next_run(now, hour) due = now if previous is None or now - previous > STALE else next_run(now, hour)
checked = now
while True: while True:
time.sleep(max(0, (due - datetime.now(timezone.utc)).total_seconds())) now = datetime.now(timezone.utc)
if now < due and not requested_since(checked):
time.sleep(min(POLL, (due - now).total_seconds()))
continue
checked = datetime.now(timezone.utc)
try: try:
run_once() run_once()
due = next_run(datetime.now(timezone.utc), hour) due = next_run(datetime.now(timezone.utc), hour)
@@ -176,6 +183,16 @@ def serve():
due = datetime.now(timezone.utc) + RETRY due = datetime.now(timezone.utc) + RETRY
def requested_since(moment):
"""Whether someone asked for a backup in the Kanban after `moment`."""
try:
with admin_connect() as c:
return c.execute('SELECT 1 FROM dtf_local.backup_requests WHERE requested_at>%s LIMIT 1',
(moment,)).fetchone() is not None
except psycopg.Error:
return False
def listing(): def listing():
client, name = bucket() client, name = bucket()
keys = [] keys = []

View File

@@ -51,14 +51,14 @@ def main():
approved_quote(client, quote, [item]) approved_quote(client, quote, [item])
orders.append(client.call('/orders/dev-paid', {'quote_id': quote['id']})) orders.append(client.call('/orders/dev-paid', {'quote_id': quote['id']}))
# Spread them over the production stages, one waiting for a correction. # Spread them over the production stages, one waiting for a correction.
stages = {0: ['tra', 'fil', 'imp', 'fin'], 1: ['tra', 'fil', 'imp', 'fin'], 2: ['tra', 'fil', 'imp'], stages = {0: ['tra', 'imp', 'rev', 'fin'], 1: ['tra', 'imp', 'rev', 'fin'], 2: ['tra', 'imp', 'rev'],
3: ['tra', 'fil'], 4: ['tra'], 5: ['cor']} 3: ['tra', 'imp'], 4: ['tra'], 5: ['cor']}
for index, path in stages.items(): for index, path in stages.items():
order = orders[index] order = orders[index]
version = order['version'] version = order['version']
for state in path: for state in path:
if state == 'fil': if state == 'tra':
# The print queue takes approved final files, as on the Kanban. # Arte conferida, the print queue, takes approved final files, as on the Kanban.
final = upload_bytes(client, b'DEMO FINAL %d' % index, order_id=order['id']) final = upload_bytes(client, b'DEMO FINAL %d' % index, order_id=order['id'])
version = client.call('/operator/orders/' + order['id'] + '/final-files', version = client.call('/operator/orders/' + order['id'] + '/final-files',
{'version': version, 'files': [{'item_index': 0, 'upload_id': final}], {'version': version, 'files': [{'item_index': 0, 'upload_id': final}],
@@ -74,7 +74,7 @@ def main():
'freight': {'service': 'pickup'}}) 'freight': {'service': 'pickup'}})
approved_quote(client, quote, [item]) approved_quote(client, quote, [item])
client.call('/payments/intent', {'quote_id': quote['id'], 'method': {'type': 'pix'}}) client.call('/payments/intent', {'quote_id': quote['id'], 'method': {'type': 'pix'}})
client.call('/account/register', {'customer': profile, 'password': DEMO_PASSWORD}) smoke.register(client, profile, DEMO_PASSWORD)
print(f'Demo customer created: {DEMO_EMAIL}') print(f'Demo customer created: {DEMO_EMAIL}')

View File

@@ -14,9 +14,8 @@ minute. Operators, the Tiny connection and the backups are kept.
It refuses if any payment was made with real money (Mercado Pago's It refuses if any payment was made with real money (Mercado Pago's
live_mode): those are customers' orders, not tests. live_mode): those are customers' orders, not tests.
Order numbers start again at #1 only with the database administrator's Order numbers start again at #1. A database set up before the worker could
rights, which the worker does not have. The script prints the one command do that prints the one command to run in the database container's console.
to run in the database container's console for that.
""" """
import argparse import argparse
import sys import sys
@@ -37,6 +36,8 @@ TABLES = [ # in an order the foreign keys allow
ACCOUNTS = [('sessions', 'sessões de clientes'), ('accounts', 'contas de clientes')] ACCOUNTS = [('sessions', 'sessões de clientes'), ('accounts', 'contas de clientes')]
CONFIRM = 'APAGAR' CONFIRM = 'APAGAR'
RESTART = 'ALTER TABLE dtf_local.orders ALTER COLUMN number RESTART WITH 1;' RESTART = 'ALTER TABLE dtf_local.orders ALTER COLUMN number RESTART WITH 1;'
# What the worker's role may do itself (app/bootstrap.py grants it).
RENUMBER = "SELECT setval(pg_get_serial_sequence('dtf_local.orders','number'), 1, false)"
def counts(c, tables): def counts(c, tables):
@@ -69,7 +70,7 @@ def main(argv=None, out=print, connect=db.connect):
out('Apagado.') out('Apagado.')
try: try:
with connect() as c: with connect() as c:
c.execute(RESTART) c.execute(RENUMBER)
out('A numeração dos pedidos recomeça em #1.') out('A numeração dos pedidos recomeça em #1.')
except Exception as exc: # the application's role cannot alter the table except Exception as exc: # the application's role cannot alter the table
if 'permission' not in str(exc).lower() and 'owner' not in str(exc).lower(): if 'permission' not in str(exc).lower() and 'owner' not in str(exc).lower():

View File

@@ -122,7 +122,7 @@ try{
encaixar=(pieces,width)=>{const result=original(pieces,width); encaixar=(pieces,width)=>{const result=original(pieces,width);
if(pieces.some(p=>p.a))window.lastLayout={altura:result.altura,pos:result.pos.map(p=>({x:p.x,y:p.y,w:p.w,h:p.h,rot:p.rot}))}; if(pieces.some(p=>p.a))window.lastLayout={altura:result.altura,pos:result.pos.map(p=>({x:p.x,y:p.y,w:p.w,h:p.h,rot:p.rot}))};
return result;}; return result;};
window.sendImage=async(type='image/jpeg',drop=false)=>{ window.sendImage=async(type='image/png',drop=false)=>{
const c=document.createElement('canvas');c.width=200;c.height=400; const c=document.createElement('canvas');c.width=200;c.height=400;
const ctx=c.getContext('2d');ctx.fillStyle='white';ctx.fillRect(0,0,200,400); const ctx=c.getContext('2d');ctx.fillStyle='white';ctx.fillRect(0,0,200,400);
ctx.fillStyle='#222';ctx.fillRect(85,20,20,360);ctx.fillRect(25,100,140,20); ctx.fillStyle='#222';ctx.fillRect(85,20,20,360);ctx.fillRect(25,100,140,20);
@@ -133,12 +133,15 @@ try{
if(drop)$('zona').dispatchEvent(new DragEvent('drop',{dataTransfer:dt,bubbles:true,cancelable:true})); if(drop)$('zona').dispatchEvent(new DragEvent('drop',{dataTransfer:dt,bubbles:true,cancelable:true}));
else{$('inp').files=dt.files;$('inp').dispatchEvent(new Event('change',{bubbles:true}));} else{$('inp').files=dt.files;$('inp').dispatchEvent(new Event('change',{bubbles:true}));}
}; };
// A genuine mounted sheet spans the film width with printable resolution. // A genuine mounted sheet spans the film width with printable resolution,
window.sendSheet=async()=>{ // on a transparent background; or with a solid one, or a residue dot.
window.sendSheet=async({fundo=false,ponto=false}={})=>{
const cm=larguraFilme(), px=Math.ceil(cm/2.54*150); const cm=larguraFilme(), px=Math.ceil(cm/2.54*150);
const c=document.createElement('canvas');c.width=px;c.height=Math.round(px*0.6); const c=document.createElement('canvas');c.width=px;c.height=Math.round(px*0.6);
const ctx=c.getContext('2d');ctx.fillStyle='white';ctx.fillRect(0,0,c.width,c.height); const ctx=c.getContext('2d');
if(fundo){ctx.fillStyle='white';ctx.fillRect(0,0,c.width,c.height);}
ctx.fillStyle='#222';ctx.fillRect(40,40,px/4,px/4); ctx.fillStyle='#222';ctx.fillRect(40,40,px/4,px/4);
if(ponto)ctx.fillRect(Math.round(px*0.8),Math.round(c.height/2),4,4);
const blob=await new Promise(r=>c.toBlob(r,'image/png')); const blob=await new Promise(r=>c.toBlob(r,'image/png'));
const dt=new DataTransfer();dt.items.add(new File([blob],'folha-montada.png',{type:'image/png'})); const dt=new DataTransfer();dt.items.add(new File([blob],'folha-montada.png',{type:'image/png'}));
$('inp').files=dt.files;$('inp').dispatchEvent(new Event('change',{bubbles:true})); $('inp').files=dt.files;$('inp').dispatchEvent(new Event('change',{bubbles:true}));
@@ -148,6 +151,14 @@ try{
// Reproduce the reported entry path, with no navigation workaround. // Reproduce the reported entry path, with no navigation workaround.
// Navigation links must reach the chooser, never preselect a product. // Navigation links must reach the chooser, never preselect a product.
assert.equal(await evaluate(`document.querySelectorAll('[data-modo-cta]').length`),0); assert.equal(await evaluate(`document.querySelectorAll('[data-modo-cta]').length`),0);
// One price per product (Dropstar, 2026-10-23), the same in the top chip, the
// home example, the product cards and the price table; nothing on the page
// still prices by the grade.
assert.deepEqual(await evaluate(`(()=>{const de=m=>[...document.querySelectorAll('[data-preco="'+m+'"]')].map(e=>e.textContent);
return {file:de('file'),avulsa:de('avulsa'),uvfile:de('uvfile'),uv:de('uv'),
stale:/14,90|conforme a nota|desconto|escada|menor preço da tabela/i.test(document.body.textContent)};})()`),
{file:['R$ 19,90','R$ 19,90','R$ 19,90','R$ 19,90'],avulsa:['R$ 21,90','R$ 21,90'],
uvfile:['R$ 79,90','R$ 79,90'],uv:['R$ 89,90','R$ 89,90'],stale:false});
await click('[data-modo="file"]'); await click('[data-modo="file"]');
// Opening a product paints on the next frame; on a busy runner the check // Opening a product paints on the next frame; on a busy runner the check
// must wait for it rather than race it. // must wait for it rather than race it.
@@ -156,59 +167,68 @@ try{
assert.deepEqual(await evaluate(`({shown:!$('tipoEnvio').hidden, assert.deepEqual(await evaluate(`({shown:!$('tipoEnvio').hidden,
on:[...document.querySelectorAll('#tipoEnvio .cam.on')].map(b=>b.dataset.tipo)})`), on:[...document.querySelectorAll('#tipoEnvio .cam.on')].map(b=>b.dataset.tipo)})`),
{shown:true,on:['folha']}); {shown:true,on:['folha']});
await evaluate(`(()=>{const f=new File(['x'],'oversize.cdr');Object.defineProperty(f,'size',{value:5*1073741824+1});sel([f]);})()`); await evaluate(`(()=>{const f=new File(['x'],'oversize.cdr');Object.defineProperty(f,'size',{value:4294967296+1});return sel([f]);})()`);
assert.equal(await evaluate(`folhas.length===0 && $('recusa').textContent.includes('5 GB')`),true, assert.equal(await evaluate(`folhas.length===0 && $('recusa').textContent.includes('4 GB')`),true,
'files beyond the 5 GB upload limit are rejected before browser analysis'); 'files beyond the 4 GB upload limit are rejected before browser analysis');
// A multi-GB sheet is the normal order: graded from the pixel size in its // A large sheet (here 900 MB) is the normal order: graded from the pixel size in its
// header, never decoded. 6732 x 35433 px across 57 cm is 3 m at 300 DPI. // header, never decoded. 6732 x 35433 px across 57 cm is 3 m at 300 DPI.
await evaluate(`(()=>{const h=new Uint8Array(33);h.set([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0,0,0,13,0x49,0x48,0x44,0x52]); await evaluate(`(()=>{const h=new Uint8Array(33);h.set([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0,0,0,13,0x49,0x48,0x44,0x52]);
const v=new DataView(h.buffer);v.setUint32(16,6732);v.setUint32(20,35433);h.set([8,6,0,0,0],24); const v=new DataView(h.buffer);v.setUint32(16,6732);v.setUint32(20,35433);h.set([8,6,0,0,0],24);
const f=new File([h],'folha-grande.png');Object.defineProperty(f,'size',{value:3*1073741824});sel([f]);})()`); const f=new File([h],'folha-grande.png');Object.defineProperty(f,'size',{value:900*1048576});return sel([f]);})()`);
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].an`),'large sheet graded from its header'); await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].an`),'large sheet graded from its header');
assert.deepEqual(await evaluate(`({grande:folhas[0].an.grande,dpi:folhas[0].an.dpi,alt:folhas[0].med.alt,preview:!!folhas[0].previewSrc})`), assert.deepEqual(await evaluate(`({grande:folhas[0].an.grande,dpi:folhas[0].an.dpi,alt:folhas[0].med.alt,preview:!!folhas[0].previewSrc})`),
{grande:true,dpi:300,alt:300,preview:false}); {grande:true,dpi:300,alt:300,preview:false});
await evaluate(`folhas=[];pintaFolha()`); await evaluate(`folhas=[];pintaFolha()`);
await evaluate(`pickTipo('avulsa')`); await evaluate(`pickTipo('avulsa')`);
assert.equal(await evaluate('modo'),'avulsa'); assert.equal(await evaluate('modo'),'avulsa');
// A large JPG artwork cannot be read in parts: it is measured from its // JPG has no transparency: refused in loose artwork as in a sheet (Dropstar,
// header and placed as a full box, with the discount, instead of refused. // 2026-10-23), with the reason, before anything is read.
await evaluate(`(()=>{const h=new Uint8Array(20);h.set([0xFF,0xD8,0xFF,0xC0,0,17,8,0x09,0x3A,0x09,0x3A,3]); await evaluate(`sel([new File(['x'],'arte.jpg',{type:'image/jpeg'})])`);
const f=new File([h],'arte-grande.jpg');Object.defineProperty(f,'size',{value:400*1048576});sel([f]);})()`); assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('JPG não dá para enviar')`),true);
await waitFor(()=>evaluate(`artes.length===1 && artes[0].semPrevia===true`),'large JPG artwork measured from its header'); // The content decides, not the name (D-13): a JPG called ".png" is refused as a JPG.
await evaluate(`sel([new File([new Uint8Array([0xFF,0xD8,0xFF,0xE0])],'disfarce.png',{type:'image/png'})])`);
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('disfarce.png é JPG')`),true);
// A large WebP artwork cannot be read in parts: it is measured from its
// header and placed as a full box, with its grade, instead of refused.
await evaluate(`(()=>{const h=new Uint8Array(30);h.set([0x52,0x49,0x46,0x46,0,0,0,0,0x57,0x45,0x42,0x50,0x56,0x50,0x38,0x58]);
h.set([0x39,0x09,0x00,0x39,0x09,0x00],24);
const f=new File([h],'arte-grande.webp');Object.defineProperty(f,'size',{value:400*1048576});return sel([f]);})()`);
await waitFor(()=>evaluate(`artes.length===1 && artes[0].semPrevia===true`),'large WebP artwork measured from its header');
await fill('[data-cm]',20); await fill('[data-cm]',20);
await waitFor(()=>evaluate(`!!itemAtual?.production?.sources?.length`),'large JPG artwork packed'); await waitFor(()=>evaluate(`!!itemAtual?.production?.sources?.length`),'large WebP artwork packed');
assert.deepEqual(await evaluate(`({dpi:Math.round(dpiDe(artes[0])),src:!!artes[0].src, assert.deepEqual(await evaluate(`({dpi:Math.round(dpiDe(artes[0])),src:!!artes[0].src,
measurement:itemAtual.production.sources[0].measurement,note:$('lista').textContent.includes('Sem prévia')})`), measurement:itemAtual.production.sources[0].measurement,note:$('lista').textContent.includes('Sem prévia')})`),
{dpi:300,src:false,measurement:'file',note:true}); {dpi:300,src:false,measurement:'file',note:true});
await evaluate(`artes=[];pintaArtes()`); await evaluate(`artes=[];pintaArtes()`);
await evaluate('sendImage()'); await evaluate('sendImage()');
await waitFor(()=>evaluate(`artes.length===1 && !!artes[0].src`),'JPG artwork model'); await waitFor(()=>evaluate(`artes.length===1 && !!artes[0].src`),'PNG artwork model');
assert.deepEqual(await evaluate(`({mode:modo,sheets:folhas.length,width:artes[0].cm,quantity:artes[0].q})`),{mode:'avulsa',sheets:0,width:0,quantity:1}); assert.deepEqual(await evaluate(`({mode:modo,sheets:folhas.length,width:artes[0].cm,quantity:artes[0].q})`),{mode:'avulsa',sheets:0,width:0,quantity:1});
await fill('[data-cm]',20);await fill('[data-q]',6); await fill('[data-cm]',20);await fill('[data-q]',6);
let layout=await packed(6); let layout=await packed(6);
await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.copies===6`),'per-file production record'); await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.copies===6`),'per-file production record');
assert.deepEqual(await evaluate(`({version:itemAtual.production.version,source:itemAtual.production.sources[0]})`), assert.deepEqual(await evaluate(`({version:itemAtual.production.version,source:itemAtual.production.sources[0]})`),
{version:2,source:{kind:'artwork',width_cm:20,length_cm:40,copies:6, {version:3,source:{kind:'artwork',width_cm:20,length_cm:40,copies:6,
rotation_degrees:0,mirrored:false,measurement:'file'}}); rotation_degrees:0,mirrored:false,measurement:'file'}});
assert.equal(await evaluate('itemAtual.production.placements.length'),6); assert.equal(await evaluate('itemAtual.production.placements.length'),6);
assert.equal(await evaluate('itemAtual.production.height_cm'),121); // 5 mm margins top and bottom, between rows, at the edges and between pieces.
assert.equal(await evaluate('itemAtual.production.height_cm'),122);
assert.deepEqual(await evaluate('itemAtual.production.placements.map(p=>[p.source_index,p.copy_index,p.x_cm,p.y_cm])'), assert.deepEqual(await evaluate('itemAtual.production.placements.map(p=>[p.source_index,p.copy_index,p.x_cm,p.y_cm])'),
[[0,0,0,0],[0,1,20.5,0],[0,2,0,40.5],[0,3,20.5,40.5],[0,4,0,81],[0,5,20.5,81]]); [[0,0,0.5,0.5],[0,1,21,0.5],[0,2,0.5,41],[0,3,21,41],[0,4,0.5,81.5],[0,5,21,81.5]]);
assert.equal(layout.heading,'Montagem ao vivo');assert.equal(layout.height,121); assert.equal(layout.heading,'Montagem ao vivo');assert.equal(layout.height,122);
assert.equal(layout.billed,1.3); assert.equal(layout.billed,1.3);
assert.deepEqual(layout.pos.map(p=>[p.x,p.y]),[[0,0],[20.5,0],[0,40.5],[20.5,40.5],[0,81],[20.5,81]]); assert.deepEqual(layout.pos.map(p=>[p.x,p.y]),[[0.5,0.5],[21,0.5],[0.5,41],[21,41],[0.5,81.5],[21,81.5]]);
assert.ok(layout.pos.every(p=>p.h/p.w===2 && p.x+p.w<=57)); assert.ok(layout.pos.every(p=>p.h/p.w===2 && p.x+p.w<=57));
await screenshot('artwork-packed'); await screenshot('artwork-packed');
await fill('[data-cm]',15); await fill('[data-cm]',15);
await waitFor(()=>evaluate('lastLayout?.altura===60.5 && metros===0.605'),'width updates without blur'); await waitFor(()=>evaluate('lastLayout?.altura===61.5 && metros===0.615'),'width updates without blur');
await fill('[data-q]',9);layout=await packed(9);assert.equal(layout.height,91); await fill('[data-q]',9);layout=await packed(9);assert.equal(layout.height,92);
await click('[data-giro]'); await click('[data-giro]');
await waitFor(()=>evaluate('lastLayout?.altura===23.5 && metros===0.235'),'rotation updates packing'); await waitFor(()=>evaluate('lastLayout?.altura===24.5 && metros===0.245'),'rotation updates packing');
const beforeMirror=await evaluate(`$('vArea').querySelector('canvas').toDataURL()`); // A textile transfer is pressed face down: mirrored, it prints backwards on
await click('[data-esp]'); // the garment. Textile has no mirror button (Dropstar, 2026-10-21).
await waitFor(()=>evaluate(`$('vArea').querySelector('canvas').toDataURL()!==${JSON.stringify(beforeMirror)}`),'mirror updates pixels'); assert.equal(await evaluate(`!!document.querySelector('[data-esp]')`),false,'textile has no mirror button');
assert.equal(await evaluate('metros'),0.235); assert.equal(await evaluate('metros'),0.245);
await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.mirrored===true`),'transforms in production record'); await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.mirrored===false`),'transforms in production record');
assert.deepEqual(await evaluate(`({rotation:itemAtual.production.sources[0].rotation_degrees,copies:itemAtual.production.sources[0].copies})`), assert.deepEqual(await evaluate(`({rotation:itemAtual.production.sources[0].rotation_degrees,copies:itemAtual.production.sources[0].copies})`),
{rotation:90,copies:9}); {rotation:90,copies:9});
await waitFor(()=>evaluate(`itemAtual?.qualityStatus==='rejected'`),'low resolution refusal'); await waitFor(()=>evaluate(`itemAtual?.qualityStatus==='rejected'`),'low resolution refusal');
@@ -231,6 +251,27 @@ try{
assert.equal(await evaluate('cartPodeEnviar()'),false); assert.equal(await evaluate('cartPodeEnviar()'),false);
assert.equal(await evaluate(`(()=>{try{encaixar([{w:58,h:10,img:null}],57);return false}catch(error){return error instanceof RangeError}})()`),true, assert.equal(await evaluate(`(()=>{try{encaixar([{w:58,h:10,img:null}],57);return false}catch(error){return error instanceof RangeError}})()`),true,
'packing engine must not shrink an oversized source'); 'packing engine must not shrink an oversized source');
// Dropstar's order 1 (2026-10-21): six 28,2 x 29,14 cm pieces. Two fit across
// 57 cm only with 2 mm at each edge and between them: aligned columns, 5 mm
// rows and margins, 89,42 cm instead of the 97,14 cm the grid gave.
assert.deepEqual(await evaluate(`(()=>{const a={};
const r=encaixar(Array.from({length:6},(_,i)=>({w:28.2,h:29.14,img:null,a,copyIndex:i})),57);
return {altura:+r.altura.toFixed(2),folga:+r.folga.toFixed(3),
xs:[...new Set(r.pos.map(p=>+p.x.toFixed(2)))],ys:[...new Set(r.pos.map(p=>+p.y.toFixed(2)))]};})()`),
{altura:89.42,folga:0.2,xs:[0.2,28.6],ys:[0.5,30.14,59.78]});
// UV, 27 cm: two 13,2 cm pieces still share a row, 2 mm apart.
assert.equal(await evaluate(`(()=>{const a={};const r=encaixar([{w:13.2,h:10,img:null,a},{w:13.2,h:10,img:null,a}],27);
return new Set(r.pos.map(p=>p.y)).size===1 && Math.abs(r.folga-0.6/3)<1e-9})()`),true);
// A long piece stands up when that shortens the sheet: 30 x 10 cm, eight copies,
// five to a row turned instead of one to a row as sent.
assert.deepEqual(await evaluate(`(()=>{const a={};const r=encaixar(Array.from({length:8},()=>({w:30,h:10,img:null,a})),57);
return {rot:[...new Set(r.pos.map(p=>p.rot))],altura:+r.altura.toFixed(2)}})()`),
{rot:[90],altura:61.5});
// Any piece that is not square is tried both ways (Dropstar, 2026-10-23):
// 19,5 x 18,5 cm fits 2 to a row standing and 3 lying down.
assert.deepEqual(await evaluate(`(()=>{const a={};const r=encaixar(Array.from({length:6},()=>({w:19.5,h:18.5,img:null,a})),57);
return {rot:[...new Set(r.pos.map(p=>p.rot))],altura:+r.altura.toFixed(2)}})()`),
{rot:[90],altura:40.5});
await click('[data-rm]'); await click('[data-rm]');
assert.equal(await evaluate(`artes.length===0 && itemAtual===null && !cartPodeEnviar()`),true, assert.equal(await evaluate(`artes.length===0 && itemAtual===null && !cartPodeEnviar()`),true,
'removed artwork cannot remain in the cart'); 'removed artwork cannot remain in the cart');
@@ -247,7 +288,22 @@ try{
await click('#bVoltar');await click('[data-modo="file"]'); await click('#bVoltar');await click('[data-modo="file"]');
await evaluate('sendSheet()'); await evaluate('sendSheet()');
await waitFor(()=>evaluate('folhas.length===1 && !!folhas[0].previewSrc && metros===0.342'),'ready-sheet image'); await waitFor(()=>evaluate('folhas.length===1 && !!folhas[0].previewSrc && metros===0.342'),'ready-sheet image');
assert.deepEqual(await evaluate(`({mode:modo,art:artes.length,title:$('montcabTit').textContent,rate:precoBase(100)})`),{mode:'file',art:0,title:'Sua folha',rate:14.9}); // On its way at once, with its own row under the uploader (Dropstar,
// 2026-10-29). There is no storage here, so it fails, and says so with a
// way to try again; tests/browser_test.mjs sends it for real.
await waitFor(()=>evaluate(`!!dtfEnvio.estado(folhas[0].f)`),'the sheet starts uploading at once');
await waitFor(()=>evaluate(`$('envios').textContent.includes('Não foi possível enviar folha-montada.png') &&
!!$('envios').querySelector('[data-envio]')`),'a failed upload says so under the uploader');
assert.deepEqual(await evaluate(`({mode:modo,art:artes.length,title:$('montcabTit').textContent,rate:precoMetro()})`),{mode:'file',art:0,title:'Sua folha',rate:19.9});
// One price per product (Dropstar, 2026-10-23): the sheet is graded, and the
// grade is shown, but the metre costs the same as for any other grade.
await waitFor(()=>evaluate('itemAtual?.nota>0'),'graded ready sheet');
assert.deepEqual(await evaluate(`({unit:itemAtual.unit,total:itemAtual.total,shown:$('cNota').textContent===itemAtual.nota+'/100',
metre:$('cMetro').textContent,ladder:!!document.getElementById('cEscada'),
discount:/desconto/i.test($('carrLin').textContent+$('resLin').textContent+$('compra').textContent)})`),
{unit:19.9,total:19.9,shown:true,metre:'R$ 19,90',ladder:false,discount:false});
assert.deepEqual(await evaluate(`({folha:$('tipoFolhaPreco').textContent,avulsa:$('tipoAvulsaPreco').textContent})`),
{folha:'R$ 19,90 /m',avulsa:'R$ 21,90 /m'});
assert.equal(await evaluate(`document.querySelectorAll('[data-cm]').length`),0); assert.equal(await evaluate(`document.querySelectorAll('[data-cm]').length`),0);
// With a sheet loaded the declaration is locked; it cannot flip under the customer. // With a sheet loaded the declaration is locked; it cannot flip under the customer.
assert.equal(await evaluate(`document.querySelector('#tipoEnvio .cam[data-tipo="avulsa"]').disabled`),true); assert.equal(await evaluate(`document.querySelector('#tipoEnvio .cam[data-tipo="avulsa"]').disabled`),true);
@@ -255,7 +311,47 @@ try{
await waitFor(()=>evaluate('metros===0.684'),'ready-sheet repetitions'); await waitFor(()=>evaluate('metros===0.684'),'ready-sheet repetitions');
assert.equal(await evaluate(`document.querySelectorAll('.folhaPrevia').length`),1); assert.equal(await evaluate(`document.querySelectorAll('.folhaPrevia').length`),1);
await evaluate(`(()=>{folhas.push({f:new File(['manual'],'manual.cdr'),med:null,rep:1,m:1,an:null});pintaFolha();})()`); await evaluate(`(()=>{folhas.push({f:new File(['manual'],'manual.cdr'),med:null,rep:1,m:1,an:null});pintaFolha();})()`);
await waitFor(()=>evaluate(`itemAtual?.nota===0 && itemAtual?.unit===TABELA[modo]`),'mixed analyzed and manual sheets use table pricing'); await waitFor(()=>evaluate(`itemAtual?.nota===0 && itemAtual?.unit===PRECO[modo]+TAXA_MANUAL`),'mixed analyzed and manual sheets: the price plus the manual charge');
// Residue and a solid background stop the order before payment (Dropstar,
// 2026-10-21). A residue is ink under 2 mm on both sides, measured in real
// millimetres: the same dot, wherever it falls on the 1 mm grid, gets the
// same verdict, from 0,5 to 4 mm.
assert.deepEqual(await evaluate(`(async()=>{
const medir=async(mm,dx,dy)=>{const c=document.createElement('canvas');c.width=5700;c.height=600;
const ctx=c.getContext('2d');ctx.fillStyle='#000';ctx.fillRect(100,100,3000,300);
const lado=Math.round(mm*10);ctx.fillRect(4000+dx,300+dy,lado,lado);
return analisarMapa(await mapaDaImagem(c,57)).residuos;};
const out={};
for(const mm of [0.5,1.5,1.9,2.1,4])out[mm]=[await medir(mm,0,0),await medir(mm,5,0),await medir(mm,0,5),await medir(mm,5,5)];
return out;})()`),
{'0.5':[1,1,1,1],'1.5':[1,1,1,1],'1.9':[1,1,1,1],'2.1':[0,0,0,0],'4':[0,0,0,0]});
// A large PNG is read as a stream; every pixel goes into the same ink map.
assert.deepEqual(await evaluate(`(async()=>{
const c=document.createElement('canvas');c.width=5700;c.height=600;
const ctx=c.getContext('2d');ctx.fillStyle='#000';ctx.fillRect(100,100,3000,300);ctx.fillRect(4005,305,12,12);
const blob=await new Promise(r=>c.toBlob(r,'image/png'));
const lido=await previaPngGrande(new File([blob],'folha.png'),600,null,57);
const a=analisarMapa(lido.mapa), b=analisarMapa(await mapaDaImagem(c,57));
return {stream:[a.residuos,a.artes,a.fundoChapado,a.pontos[0].mm],direct:[b.residuos,b.artes,b.fundoChapado,b.pontos[0].mm]};})()`),
{stream:[1,1,false,1.2],direct:[1,1,false,1.2]});
await click('#bVoltar');await click('[data-modo="file"]');
await evaluate('sendSheet({ponto:true})');
await waitFor(()=>evaluate(`folhas.length===1 && folhas[0].pct==null && folhas[0].an?.residuos===1`),'residue found');
await waitFor(()=>evaluate(`$('aoVivo').textContent.includes('ponto de recorte') && itemAtual===null`),'residue stops the order');
assert.equal(await evaluate(`$('lista').textContent.includes('Sobrou 1 ponto de recorte na sua folha')`),true);
await waitFor(()=>evaluate(`folhas[0].previewSrc.startsWith('data:image/webp')`),'residue circled on the preview');
// Unless the customer accepts printing the dot (Dropstar, 2026-10-29): ticked,
// the sheet goes on and the item says how many dots were accepted.
assert.equal(await evaluate(`$('lista').textContent.includes('Esta arte tem 1 ponto menor que 2 mm. Estou ciente e aceito imprimir assim')`),true);
await click('[data-residuo="0"]');
await waitFor(()=>evaluate(`itemAtual?.residueAccepted===1 && !$('lista').textContent.includes('Sobrou 1 ponto')`),'accepted residue lets the sheet go on');
await click('[data-residuo="0"]');
await waitFor(()=>evaluate(`itemAtual===null && $('aoVivo').textContent.includes('ponto de recorte')`),'unticked, the residue stops it again');
await evaluate(`folhas=[];pintaFolha()`);
await evaluate('sendSheet({fundo:true})');
await waitFor(()=>evaluate(`folhas[0]?.an?.fundoChapado===true && itemAtual===null && $('aoVivo').textContent.includes('fundo transparente')`),'solid background stops the order');
assert.equal(await evaluate(`$('lista').textContent.includes('O fundo da sua folha não é transparente')`),true);
await evaluate(`folhas=[];pintaFolha()`);
// An image too small to span the film is refused, never silently repriced. // An image too small to span the film is refused, never silently repriced.
await click('#bVoltar');await click('[data-modo="file"]'); await click('#bVoltar');await click('[data-modo="file"]');
await evaluate('sendImage()'); await evaluate('sendImage()');
@@ -279,6 +375,10 @@ try{
assert.deepEqual(rotated,{larg:50.8,alt:25.4,fonte:'página do PDF · UserUnit 2'}); assert.deepEqual(rotated,{larg:50.8,alt:25.4,fonte:'página do PDF · UserUnit 2'});
const rendered=await evaluate(`rasterizarPdf(${pdfFile(pdfData({media:'[0 0 720 1440]',crop:'[0 0 360 720]',rotate:90,unit:2}))},50.8,25.4).then(r=>({ok:!!r.tela,error:r.erro||null}))`); const rendered=await evaluate(`rasterizarPdf(${pdfFile(pdfData({media:'[0 0 720 1440]',crop:'[0 0 360 720]',rotate:90,unit:2}))},50.8,25.4).then(r=>({ok:!!r.tela,error:r.erro||null}))`);
assert.deepEqual(rendered,{ok:true,error:null}); assert.deepEqual(rendered,{ok:true,error:null});
// A PDF sheet gets the same ink map, rendered in strips: a blank page is all transparent.
const mapped=await evaluate(`rasterizarPdf(${pdfFile(pdfData())},25.4,12.7,true).then(r=>{const a=analisarMapa(r.mapa);
return {fundo:a.fundoChapado,residuos:a.residuos,largura:r.mapa.wPx}})`);
assert.deepEqual(mapped,{fundo:false,residuos:0,largura:1270});
const multi=await evaluate(`medirFolha(${pdfFile(pdfData({pages:2}))})`); const multi=await evaluate(`medirFolha(${pdfFile(pdfData({pages:2}))})`);
assert.equal(multi.rejected,true);assert.match(multi.reason,/2 páginas/); assert.equal(multi.rejected,true);assert.match(multi.reason,/2 páginas/);
const beyondSpec=await evaluate(`medirFolha(${pdfFile(pdfData({media:'[0 0 20000 720]'}))})`); const beyondSpec=await evaluate(`medirFolha(${pdfFile(pdfData({media:'[0 0 20000 720]'}))})`);
@@ -291,6 +391,13 @@ try{
assert.equal(await evaluate(`avaliar().pronto`),false); assert.equal(await evaluate(`avaliar().pronto`),false);
assert.equal(await evaluate(`cartPodeEnviar()`),false); assert.equal(await evaluate(`cartPodeEnviar()`),false);
assert.match(await evaluate(`$('lista').textContent`),/não pode ser orçado/); assert.match(await evaluate(`$('lista').textContent`),/não pode ser orçado/);
// A ".cdr" that is a PDF (D-13) is renamed and measured as a PDF, not handled by hand.
await click('#bVoltar');await click('[data-modo="file"]');
await evaluate(`sel([${pdfFile(pdfData(),'folha.cdr')}])`);
// Measured, and its ink check finished: a check still running repaints the list after the mode below changes.
await waitFor(()=>evaluate(`folhas.length===1 && !!(folhas[0].med || folhas[0].measurementError) && folhas[0].pct==null`),'renamed PDF measured');
assert.deepEqual(await evaluate(`({name:folhas[0].f.name,measured:!!folhas[0].med,manual:folhaManual()})`),
{name:'folha.pdf',measured:true,manual:false});
await click('#bVoltar');await click('[data-modo="avulsa"]'); await click('#bVoltar');await click('[data-modo="avulsa"]');
await evaluate(`sel([new File(['not an image'],'broken.png',{type:'image/png'})])`); await evaluate(`sel([new File(['not an image'],'broken.png',{type:'image/png'})])`);
await waitFor(()=>evaluate('artes.length===1 && artes[0].decodeError===true'),'failed image decode'); await waitFor(()=>evaluate('artes.length===1 && artes[0].decodeError===true'),'failed image decode');
@@ -306,6 +413,12 @@ try{
assert.equal(await evaluate('modo'),expected); assert.equal(await evaluate('modo'),expected);
await fill('[data-cm]',10);await fill('[data-q]',4);await packed(4); await fill('[data-cm]',10);await fill('[data-q]',4);await packed(4);
} }
// UV keeps the mirror until Dropstar decides; it changes the pixels and the record.
const beforeMirror=await evaluate(`$('vArea').querySelector('canvas').toDataURL()`);
await click('[data-esp]');
await waitFor(()=>evaluate(`$('vArea').querySelector('canvas').toDataURL()!==${JSON.stringify(beforeMirror)}`),'mirror updates pixels');
await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.mirrored===true`),'UV mirror in production record');
await click('[data-esp]');
// An older image load must not overwrite a newer edit, even before debounce. // An older image load must not overwrite a newer edit, even before debounce.
// The packing loads each artwork's image through imagemDaArte. // The packing loads each artwork's image through imagemDaArte.
await evaluate(`(()=>{window.realLoad=imagemDaArte;window.delayed=[]; await evaluate(`(()=>{window.realLoad=imagemDaArte;window.delayed=[];
@@ -345,6 +458,6 @@ try{
console.log('Supplied image:',JSON.stringify(layout)); console.log('Supplied image:',JSON.stringify(layout));
} }
assert.deepEqual(errors,[]); assert.deepEqual(errors,[]);
console.log('PASS: JPG/PNG upload and drop, packed copies, 5 mm gaps, aspect ratio, live width/quantity/rotation/mirror, metres, ready-sheet pricing/repeats, UV, stale renders, strict inline CSP.'); console.log('PASS: PNG upload and drop, JPG refused, packed copies, 5 mm gaps, aspect ratio, live width/quantity/rotation/mirror, metres, ready-sheet pricing/repeats, residue and solid background stop the order, UV, stale renders, strict inline CSP.');
}catch(error){console.error(error);if(stderr)console.error(stderr.slice(-1200));process.exitCode=1;} }catch(error){console.error(error);if(stderr)console.error(stderr.slice(-1200));process.exitCode=1;}
finally{ws?.close();chrome.kill();server.closeAllConnections();await new Promise(r=>server.close(r));} finally{ws?.close();chrome.kill();server.closeAllConnections();await new Promise(r=>server.close(r));}

View File

@@ -31,6 +31,14 @@ def main():
os.environ['BACKUP_AGE_RECIPIENT'] = public os.environ['BACKUP_AGE_RECIPIENT'] = public
check(db_backup.configured(), 'the local backup service is configured once a recipient is set') check(db_backup.configured(), 'the local backup service is configured once a recipient is set')
# "Fazer backup agora" in the Kanban is seen by the service.
before = datetime.now(timezone.utc)
with admin_connect() as c:
c.execute("INSERT INTO dtf_local.backup_requests(requested_by) VALUES('backup-test')")
check(db_backup.requested_since(before), 'a backup asked for in the Kanban is seen by the service')
with admin_connect() as c:
c.execute("DELETE FROM dtf_local.backup_requests WHERE requested_by='backup-test'")
live = db_backup.counts(None) live = db_backup.counts(None)
key = db_backup.run_once() key = db_backup.run_once()
with admin_connect() as c: with admin_connect() as c:

View File

@@ -52,7 +52,7 @@ try{
await waitFor(()=>site.eval('typeof window.dtfCheckout === "function"'),'checkout bridge'); await waitFor(()=>site.eval('typeof window.dtfCheckout === "function"'),'checkout bridge');
// Prove escaping itself, independently of the CSP's second line of defense. // Prove escaping itself, independently of the CSP's second line of defense.
await site.call('Page.setBypassCSP',{enabled:true}); await site.call('Page.setBypassCSP',{enabled:true});
await site.eval(`(()=>{window.xssProbe=0;abrir('file');sel([new File(['test'],'<img src=x onerror=window.xssProbe=1>.cdr')]);})()`); await site.eval(`(()=>{window.xssProbe=0;abrir('file');return sel([new File(['test'],'<img src=x onerror=window.xssProbe=1>.cdr')]);})()`);
await pause(500); await pause(500);
assert.equal(await site.eval('window.xssProbe'),0); assert.equal(await site.eval('window.xssProbe'),0);
assert.equal(await site.eval('document.querySelectorAll("#lista img[onerror]").length'),0); assert.equal(await site.eval('document.querySelectorAll("#lista img[onerror]").length'),0);
@@ -73,9 +73,20 @@ try{
const input=await site.call('DOM.querySelector',{nodeId:root.root.nodeId,selector:'#inp'}); const input=await site.call('DOM.querySelector',{nodeId:root.root.nodeId,selector:'#inp'});
await site.call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve('tests/fixtures/local-test.cdr')]}); await site.call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve('tests/fixtures/local-test.cdr')]});
await waitFor(()=>site.eval('!!document.querySelector("[data-comp]")'),'manual length field'); await waitFor(()=>site.eval('!!document.querySelector("[data-comp]")'),'manual length field');
// On its way from the product page already, with its own row under the
// uploader (Dropstar, 2026-10-29).
await waitFor(()=>site.eval(`$('envios').textContent.includes('local-test.cdr') && !$('envios').textContent.includes('Não foi possível')`),
'the file uploads from the product page',45000);
await site.fill('[data-comp]','1.01','change'); await site.fill('[data-comp]','1.01','change');
await waitFor(()=>site.eval('!!itemAtual'),'cart calculation'); await waitFor(()=>site.eval('!!itemAtual'),'cart calculation');
assert.equal(await site.eval('itemAtual.total'),21.89); // A CDR is opened by hand: the full price, plus the per-metre charge when
// the server sets one (MANUAL_FILE_EXTRA_CENTS), shown before checkout.
const extraCents=(await site.eval('dtfSessionReady')).manual_extra_cents;
const itemCents=Math.round(1.1*(1990+extraCents));
const total=Math.round(itemCents)/100;
await waitFor(()=>site.eval(`Math.abs(itemAtual.total-${total})<0.005`),'manual-file price');
assert.equal(await site.eval(`$('carrLin').textContent.includes('Arquivo aberto na mão')`),extraCents>0);
await site.fill('#fNome','Cliente Teste');
await site.fill('#fCnpj','11222333000181'); await site.fill('#fCnpj','11222333000181');
await site.fill('#fZap','11999999999'); await site.fill('#fZap','11999999999');
await site.fill('#fMail','local-browser@example.test'); await site.fill('#fMail','local-browser@example.test');
@@ -97,11 +108,24 @@ try{
await waitFor(()=>site.eval(`!$('carrVazio').hidden||document.documentElement.hasAttribute('data-sem-itens')`),'empty cart state'); await waitFor(()=>site.eval(`!$('carrVazio').hidden||document.documentElement.hasAttribute('data-sem-itens')`),'empty cart state');
assert.deepEqual(await site.eval(`({items:pedido.length,empty:!$('carrVazio').hidden||document.documentElement.hasAttribute('data-sem-itens'),undo:!$('desfazer').hidden})`),{items:0,empty:true,undo:true}); assert.deepEqual(await site.eval(`({items:pedido.length,empty:!$('carrVazio').hidden||document.documentElement.hasAttribute('data-sem-itens'),undo:!$('desfazer').hidden})`),{items:0,empty:true,undo:true});
await site.click('#desfazerBtn'); await site.click('#desfazerBtn');
assert.equal(await site.eval('pedido.length===1 && pedido[0].total===21.89 && $("desfazer").hidden'),true); assert.equal(await site.eval(`pedido.length===1 && Math.abs(pedido[0].total-${total})<0.005 && $("desfazer").hidden`),true);
// The items come back after a reload; the customer's details do not. // The items come back after a reload; the customer's details do not.
assert.deepEqual(await site.eval(`['fCnpj','fZap','fMail'].map(id=>$(id).value)`),['','','']); assert.deepEqual(await site.eval(`['fNome','fCnpj','fZap','fMail'].map(id=>$(id).value)`),['','','','']);
assert.equal(await site.eval('document.getElementById("bPagar").disabled'),true); assert.equal(await site.eval('document.getElementById("bPagar").disabled'),true);
// A name is required: without it, no payment.
await site.fill('#fNome','A');
await site.fill('#fCnpj','52998224725');await site.fill('#fZap','11999999999');await site.fill('#fMail','local-browser@example.test');
assert.equal(await site.eval('clienteOk()'),false);
await site.fill('#fNome',' Maria da Silva');
assert.equal(await site.eval('cliente.name'),'Maria da Silva');
// A CPF or a CNPJ, each in its own mask; this order is a person's.
await site.fill('#fCnpj','11222333000181'); await site.fill('#fCnpj','11222333000181');
assert.equal(await site.eval(`$('fCnpj').value`),'11.222.333/0001-81');
await site.fill('#fCnpj','52998224724');
assert.equal(await site.eval(`$('fCnpj').value`),'529.982.247-24');
assert.equal(await site.eval('docOk(cliente.cnpj)'),false);
await site.fill('#fCnpj','52998224725');
assert.equal(await site.eval(`$('fCnpj').value+' '+$('fCnpj').classList.contains('bom')`),'529.982.247-25 true');
await site.fill('#fZap','11999999999'); await site.fill('#fZap','11999999999');
await site.fill('#fMail','local-browser@example.test'); await site.fill('#fMail','local-browser@example.test');
assert.equal(await site.eval('pedido[0].localFiles[0].name'),'local-test.cdr'); assert.equal(await site.eval('pedido[0].localFiles[0].name'),'local-test.cdr');
@@ -111,7 +135,7 @@ try{
{marcado:false,pagar:0,zero:true,row:true}); {marcado:false,pagar:0,zero:true,row:true});
await site.click('[data-sel="0"]'); await site.click('[data-sel="0"]');
assert.equal(await site.eval('pedido[0].marcado===true && itensAPagar().length===1'),true); assert.equal(await site.eval('pedido[0].marcado===true && itensAPagar().length===1'),true);
assert.equal(await site.eval('pedido[0].total'),21.89); assert.equal(await site.eval(`Math.abs(pedido[0].total-${total})<0.005`),true);
assert.equal(await site.eval('document.getElementById("bPagar").disabled'),false); assert.equal(await site.eval('document.getElementById("bPagar").disabled'),false);
await site.click('#bPagar'); await site.click('#bPagar');
try{ try{
@@ -126,6 +150,8 @@ try{
throw error; throw error;
} }
const qid=await site.eval('localStorage.getItem("dtf-quote")'); const qid=await site.eval('localStorage.getItem("dtf-quote")');
// The server charged what the Site showed.
assert.equal(await site.eval(`dtfApi('/quotes/'+${JSON.stringify(qid)}).then(q=>q.approved.items[0].total_cents)`),itemCents);
const kanban=await page(kanbanOrigin); const kanban=await page(kanbanOrigin);
await kanban.fill('#email',process.env.OPERATOR_EMAIL||'operator@example.test'); await kanban.fill('#email',process.env.OPERATOR_EMAIL||'operator@example.test');
await kanban.fill('#password',process.env.OPERATOR_PASSWORD||'local-operator-only'); await kanban.fill('#password',process.env.OPERATOR_PASSWORD||'local-operator-only');
@@ -157,20 +183,38 @@ try{
await kanban.click('#refresh'); await kanban.click('#refresh');
await waitFor(()=>kanban.eval(`board.orders.some(o=>o.quote_id===${JSON.stringify(qid)})`),'paid card'); await waitFor(()=>kanban.eval(`board.orders.some(o=>o.quote_id===${JSON.stringify(qid)})`),'paid card');
const oid=await kanban.eval(`board.orders.find(o=>o.quote_id===${JSON.stringify(qid)}).id`); const oid=await kanban.eval(`board.orders.find(o=>o.quote_id===${JSON.stringify(qid)}).id`);
// The customer's name is on the order, and the Kanban card is titled with it.
assert.equal(await kanban.eval(`board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.customer.name`),'Maria da Silva');
assert.deepEqual(await kanban.eval(`(()=>{const spec=board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.items[0].production;const source=spec.sources[0];return {kind:source.kind,copies:source.copies,length:Number(source.length_cm),height:Number(spec.height_cm),placed:spec.placements.length}})()`), assert.deepEqual(await kanban.eval(`(()=>{const spec=board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.items[0].production;const source=spec.sources[0];return {kind:source.kind,copies:source.copies,length:Number(source.length_cm),height:Number(spec.height_cm),placed:spec.placements.length}})()`),
{kind:'sheet',copies:1,length:101,height:101,placed:1}); {kind:'sheet',copies:1,length:101,height:101,placed:1});
// The orders' three folders, switched on in Integrações. The native picker
// cannot be driven headless: it answers with a folder in the browser's own
// storage, which has the same file API.
await kanban.click('[data-tab="integrations"]');
await waitFor(()=>kanban.eval('!!document.getElementById("folder-card")'),'folder card');
await kanban.eval(`(async()=>{const root=await navigator.storage.getDirectory();
window.picked=await root.getDirectoryHandle('fila-'+Date.now(),{create:true});
window.showDirectoryPicker=async()=>window.picked;FOLDER.mode='folder';renderIntegrations();
[...document.querySelectorAll('#folder-card button')].find(b=>b.textContent==='Escolher pasta').click();})()`);
await waitFor(()=>kanban.eval('folderActive()&&!FOLDER.busy'),'folder chosen');
// Dropstar's three folders (2026-10-26): the file arrives in Arte recebida,
// goes to Arte conferida with the card and to Finalizado at the end.
await waitFor(()=>kanban.eval(`!FOLDER.busy`),'folder idle');
const savedFiles=(sub)=>kanban.eval(`(async()=>{const dir=await window.picked.getDirectoryHandle(${JSON.stringify(sub)},{create:true});
const out=[];for await(const [name,h] of dir.entries())if(h.kind==='file')out.push(name);return out;})()`);
// Open the order's panel from its card, then click the real transition // Open the order's panel from its card, then click the real transition
// buttons there, including the rerender after each move. // buttons there, including the rerender after each move.
await kanban.click('[data-tab="board"]'); await kanban.click('[data-tab="board"]');
await kanban.click(`[data-card="${oid}"]`); await kanban.click(`[data-card="${oid}"]`);
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel'); await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel');
for(const [title,state] of [['Arte tratada','tra'],['Fila de impressão','fil'],['Imprimindo','imp'],['Finalizado','fin']]){ // Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão before Finalizado.
if(state==='fil'){ for(const [title,state] of [['Arte conferida','tra'],['Imprimindo','imp'],['Revisão','rev'],['Finalizado','fin']]){
if(state==='tra'){
// Without an approved final, the next step at the top is approving it, // Without an approved final, the next step at the top is approving it,
// not a move the server would refuse. The CDR has no ready file, so // not a move the server would refuse. The CDR has no ready file, so
// the button opens the upload form there. // the button opens the upload form there.
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-approve]')`),'approve final button'); await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-approve]')`),'approve final button');
assert.equal(await kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="fil"]')`),false); assert.equal(await kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="tra"]')`),false);
await kanban.click(`[data-order="${oid}"] [data-approve]`); await kanban.click(`[data-order="${oid}"] [data-approve]`);
await waitFor(()=>kanban.eval(`(()=>{const input=document.querySelector('[data-order="${oid}"] [data-final-item]');return !!input&&!input.closest('form').hidden;})()`),'final upload controls'); await waitFor(()=>kanban.eval(`(()=>{const input=document.querySelector('[data-order="${oid}"] [data-final-item]');return !!input&&!input.closest('form').hidden;})()`),'final upload controls');
const doc=await kanban.call('DOM.getDocument'); const doc=await kanban.call('DOM.getDocument');
@@ -178,18 +222,62 @@ try{
await kanban.call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve('tests/fixtures/local-test.cdr')]}); await kanban.call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve('tests/fixtures/local-test.cdr')]});
await kanban.fill(`[data-order="${oid}"] input[placeholder="Nota da revisão"]`,'Browser test final file'); await kanban.fill(`[data-order="${oid}"] input[placeholder="Nota da revisão"]`,'Browser test final file');
await kanban.eval(`(()=>{const check=document.querySelector('[data-order="${oid}"] [data-confirm]');check.click();check.closest('form').requestSubmit();})()`); await kanban.eval(`(()=>{const check=document.querySelector('[data-order="${oid}"] [data-confirm]');check.click();check.closest('form').requestSubmit();})()`);
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').version===2`),'final file approval'); await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').version===1`),'final file approval');
// Approved before the queue: already on this computer, in Arte recebida.
const early='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
await kanban.eval('syncFolder(true)');
await waitFor(async()=>(await savedFiles('1. Arte recebida')).some(n=>n.startsWith(early)&&!n.endsWith('.baixando')),'final file saved in Arte recebida',45000);
assert.equal((await savedFiles('2. Arte conferida')).some(n=>n.startsWith(early)),false);
} }
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title); await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title);
await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`); await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`);
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state); await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state);
if(state==='tra'){
// Entering the queue moves its file to Arte conferida, whole and named after the order.
const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
await waitFor(async()=>(await savedFiles('2. Arte conferida')).some(n=>n.startsWith(prefix)&&!n.endsWith('.baixando')),'final file in Arte conferida',45000);
// Other orders the earlier suites left in the queue may still be coming
// down: only once the round ends must no half-written file be left.
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder round finished',60000);
assert.equal((await savedFiles('2. Arte conferida')).some(n=>n.endsWith('.baixando')),false);
assert.equal((await savedFiles('1. Arte recebida')).some(n=>n.startsWith(prefix)),false);
// A file whose order was deleted leaves the folder.
await kanban.eval(`(async()=>{const dir=await window.picked.getDirectoryHandle('2. Arte conferida',{create:true});
const f=await dir.getFileHandle('pedido-0-item-1-excluido.png',{create:true});
const w=await f.createWritable();await w.write('x');await w.close();
FOLDER.saved.set(crypto.randomUUID(),{order:crypto.randomUUID(),item:1,name:'pedido-0-item-1-excluido.png',folder:'2. Arte conferida'});})()`);
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder idle',60000);
await kanban.eval('syncFolder(true)');
await waitFor(async()=>!(await savedFiles('2. Arte conferida')).includes('pedido-0-item-1-excluido.png'),'deleted order file removed',30000);
}
if(state==='rev'||state==='fin'){
// In Revisão the file leaves the queue for 4. Revisão; finalized, it
// goes on to 5. Finalizado (Dropstar's numbering, 2026-10-30).
const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
const [now,before]=state==='rev'?['4. Revisão','2. Arte conferida']:['5. Finalizado','4. Revisão'];
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder idle',60000);
await kanban.eval('syncFolder(true)');
await waitFor(async()=>(await savedFiles(now)).some(n=>n.startsWith(prefix)),'final file in '+now,30000);
assert.equal((await savedFiles(before)).some(n=>n.startsWith(prefix)),false);
}
if(state==='fin'){
// The folder of before the numbering goes once nothing is left in it.
const folders=()=>kanban.eval(`(async()=>{const out=[];for await(const [name,h] of window.picked.entries())if(h.kind==='directory')out.push(name);return out.sort();})()`);
await kanban.eval(`window.picked.getDirectoryHandle('3. Finalizado',{create:true})`);
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder idle',60000);
await kanban.eval('syncFolder(true)');
await waitFor(async()=>!(await folders()).includes('3. Finalizado'),'old Finalizado folder removed',30000);
const tree=await folders();
for(const name of ['1. Arte recebida','2. Arte conferida','3. Imprimindo','4. Revisão','5. Finalizado','Recibos'])
assert.ok(tree.includes(name),name+' missing from '+tree.join(', '));
}
} }
// Undo a mistaken move from the panel: one stage back with an internal reason. // Undo a mistaken move from the panel: one stage back with an internal reason.
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-back="imp"]')`),'back button'); await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-back="rev"]')`),'back button');
await kanban.click(`[data-order="${oid}"] [data-back="imp"]`); await kanban.click(`[data-order="${oid}"] [data-back="rev"]`);
await kanban.fill(`[data-order="${oid}"] form.reason input`,'Movido por engano (teste)'); await kanban.fill(`[data-order="${oid}"] form.reason input`,'Movido por engano (teste)');
await kanban.eval(`document.querySelector('[data-order="${oid}"] form.reason input').closest('form').requestSubmit()`); await kanban.eval(`document.querySelector('[data-order="${oid}"] form.reason input').closest('form').requestSubmit()`);
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='imp'`),'undo to Imprimindo'); await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='rev'`),'undo to Revisão');
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="fin"]')`),'move to Finalizado again'); await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="fin"]')`),'move to Finalizado again');
await kanban.click(`[data-order="${oid}"] [data-move="fin"]`); await kanban.click(`[data-order="${oid}"] [data-move="fin"]`);
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='fin'`),'finished again'); await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='fin'`),'finished again');
@@ -207,10 +295,15 @@ try{
await waitFor(()=>portal.eval('document.querySelector("#order-'+oid+' .detalhe")?.hidden===false'),'order from the link opened'); await waitFor(()=>portal.eval('document.querySelector("#order-'+oid+' .detalhe")?.hidden===false'),'order from the link opened');
await portal.click('#navEntrar'); await portal.click('#navEntrar');
await waitFor(()=>portal.eval('location.pathname==="/conta/entrar" && !document.getElementById("auth").hidden'),'sign-in page'); await waitFor(()=>portal.eval('location.pathname==="/conta/entrar" && !document.getElementById("auth").hidden'),'sign-in page');
await portal.fill('#cnpj','11222333000181');await portal.fill('#phone','11999999999'); await portal.fill('#register-name','Cliente Portal');await portal.fill('#cnpj','11222333000181');await portal.fill('#phone','11999999999');
await portal.fill('#register-email','browser-'+Date.now()+'@example.test'); await portal.fill('#register-email','browser-'+Date.now()+'@example.test');
await portal.fill('#register-password','local-browser-password-123'); await portal.fill('#register-password','local-browser-password-123');
await portal.eval('document.getElementById("register").requestSubmit()'); await portal.eval('document.getElementById("register").requestSubmit()');
// The account waits for the code e-mailed to the address; the local stack
// keeps it readable for this test.
await waitFor(()=>portal.eval('!document.getElementById("fCodigo").hidden'),'signup code step');
await portal.eval(`fetch('/api/account/register/dev-code?signup='+signup).then(r=>r.json()).then(({code})=>{
const field=document.getElementById('codigo');field.value=code;field.dispatchEvent(new Event('input'));})`);
await waitFor(()=>portal.eval('document.getElementById("auth").hidden && location.pathname==="/conta"'),'customer registration'); await waitFor(()=>portal.eval('document.getElementById("auth").hidden && location.pathname==="/conta"'),'customer registration');
await waitFor(async()=> (await portal.text()).includes('Finalizado'),'overview shows the last order'); await waitFor(async()=> (await portal.text()).includes('Finalizado'),'overview shows the last order');
await portal.click('[data-view="dados"]'); await portal.click('[data-view="dados"]');

View File

@@ -4,12 +4,14 @@ Run against the local stack: python3 -m tests.kanban_test
""" """
import base64 import base64
import secrets import secrets
from datetime import date, timedelta
from urllib.error import HTTPError from urllib.error import HTTPError
from urllib.parse import urlencode from urllib.parse import urlencode
from urllib.request import Request from urllib.request import Request
from uuid import uuid4 from uuid import uuid4
import httpx import httpx
import psycopg
from psycopg.types.json import Jsonb from psycopg.types.json import Jsonb
from app.core import db from app.core import db
@@ -80,8 +82,8 @@ def run():
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved) c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved)
VALUES(%s,%s,%s,%s,%s,%s)''', (qid, owner, uuid4(), 'kanban-fixture', Jsonb(content), VALUES(%s,%s,%s,%s,%s,%s)''', (qid, owner, uuid4(), 'kanban-fixture', Jsonb(content),
Jsonb(accepted) if accepted else None)) Jsonb(accepted) if accepted else None))
number = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) number = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
VALUES(%s,%s,%s,%s,%s) RETURNING number''', VALUES(%s,%s,%s,%s,%s,'site') RETURNING number''',
(order_id, paid, owner, Jsonb({**draft(item('file')), 'total_cents': 1490}), (order_id, paid, owner, Jsonb({**draft(item('file')), 'total_cents': 1490}),
Jsonb({'provider': 'teste', 'id': f'kanban-{tag}'}))).fetchone()['number'] Jsonb({'provider': 'teste', 'id': f'kanban-{tag}'}))).fetchone()['number']
@@ -125,7 +127,58 @@ def run():
assert (after['orders'], after['cents']) == (before['orders'] + 1, before['cents'] + 1490), (before, after) assert (after['orders'], after['cents']) == (before['orders'] + 1, before['cents'] + 1490), (before, after)
assert after['daily'][-1]['orders'] == before['daily'][-1]['orders'] + 1 assert after['daily'][-1]['orders'] == before['daily'][-1]['orders'] + 1
assert after['waiting']['rec']['orders'] == before.get('waiting', {}).get('rec', {}).get('orders', 0) + 1 assert after['waiting']['rec']['orders'] == before.get('waiting', {}).get('rec', {}).get('orders', 0) + 1
# Each way in apart (D-21), all three listed even when empty.
assert [o['origin'] for o in after['origins']] == ['site', 'dropflow', 'atendimento']
site = lambda stats: next(o for o in stats['origins'] if o['origin'] == 'site')
assert (site(after)['orders'], site(after)['cents']) == (site(before)['orders'] + 1, site(before)['cents'] + 1490)
# No order without an origin, and only the three (D-21, D-35).
for origin in (None, 'whatsapp'):
try:
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
VALUES(%s,%s,%s,'{}','{}',%s)''', (uuid4(), approved, owner, origin))
except (psycopg.errors.NotNullViolation, psycopg.errors.CheckViolation):
pass
else:
raise AssertionError(f'an order with origin {origin!r} was accepted')
client.call('/operator/stats?days=3', operator=True, expected=422) client.call('/operator/stats?days=3', operator=True, expected=422)
# Or two dates: the same week asked as a range gives the same numbers.
week = client.call(f"/operator/stats?start={after['start']}&end={after['end']}", operator=True)
assert (week['orders'], week['cents'], len(week['daily'])) == (after['orders'], after['cents'], 7), week
one = client.call(f"/operator/stats?start={after['end']}&end={after['end']}", operator=True)
assert len(one['daily']) == 1 and one['daily'][0] == after['daily'][-1]
client.call(f"/operator/stats?start={after['end']}&end={after['start']}", operator=True, expected=422)
client.call(f"/operator/stats?start={after['start']}", operator=True, expected=422)
client.call('/operator/stats?start=2025-01-01&end=2026-12-31', operator=True, expected=422)
assert isinstance(after['machines'], list)
# An order sent back counts once per stage; its passages are counted apart.
with db.connect() as c:
for step, (frm, to) in enumerate((('rec', 'tra'), ('tra', 'cor'), ('cor', 'tra'), ('tra', 'imp'))):
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
VALUES(%s,%s,%s,'kanban-test','',false,now()+%s*interval '1 second')''', (order_id, frm, to, step + 1))
moved = client.call('/operator/stats?days=7', operator=True)
tra_before = after['stages'].get('tra', {'orders': 0, 'passages': 0})
assert moved['stages']['tra']['orders'] == tra_before['orders'] + 1, moved['stages']
assert moved['stages']['tra']['passages'] == tra_before['passages'] + 2, moved['stages']
# Its time in a stage is the sum of its passages: on a day of its own, one
# hour in Arte conferida, a correction, and another hour there read as 2 h.
alone = (date(2001, 1, 1) + timedelta(days=int(tag, 16) % 3000)).isoformat()
with db.connect() as c:
c.execute('UPDATE dtf_local.orders SET created_at=%s::timestamptz WHERE id=%s', (f'{alone} 08:00-03', order_id))
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (order_id,))
for hour, (frm, to) in enumerate((('rec', 'tra'), ('tra', 'cor'), ('cor', 'tra'), ('tra', 'imp')), start=9):
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
VALUES(%s,%s,%s,'kanban-test','',false,%s::timestamptz)''', (order_id, frm, to, f'{alone} {hour}:00-03'))
day = client.call(f'/operator/stats?start={alone}&end={alone}', operator=True)
assert day['stages']['tra'] == {'orders': 1, 'passages': 2, 'median_hours': 2.0}, day['stages']
assert day['stages']['rec']['median_hours'] == 1.0, day['stages']
# Half an hour of it waiting for the customer does not count (D-38).
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.contact_waits(order_id, started_at, ended_at)
VALUES(%s, %s::timestamptz, %s::timestamptz)''', (order_id, f'{alone} 09:15-03', f'{alone} 09:45-03'))
day = client.call(f'/operator/stats?start={alone}&end={alone}', operator=True)
assert day['stages']['tra']['median_hours'] == 1.5, day['stages']
assert day['stages']['rec']['median_hours'] == 1.0, day['stages']
# The company's name from the registry: on the board, and found by the search. # The company's name from the registry: on the board, and found by the search.
from app import cnpj as registry from app import cnpj as registry
@@ -145,9 +198,20 @@ def run():
assert row['fetched_at'] is None and row['failed_at'] is not None assert row['fetched_at'] is None and row['failed_at'] is not None
assert '11222333000181' not in registry.pending(c, 500) assert '11222333000181' not in registry.pending(c, 500)
Client().call('/operator/stats', expected=401) Client().call('/operator/stats', expected=401)
print('PASS: artwork pictures (owner only, images only), quote filters, the order/quote search and the numbers') # "Fazer backup agora": recorded for the backup service, shown as asked.
with db.connect() as c:
c.execute('DELETE FROM dtf_local.backup_requests')
Client().call('/operator/backup/run', {}, expected=401)
client.call('/operator/backup/run', {}, operator=True)
assert client.call('/operator/board', operator=True)['providers']['backup']['requested'] is True
with db.connect() as c:
c.execute('DELETE FROM dtf_local.backup_requests')
assert client.call('/operator/board', operator=True)['providers']['backup']['requested'] is False
print('PASS: artwork pictures (owner only, images only), quote filters, the order/quote search, the numbers '
'and a backup asked for now')
finally: finally:
with db.connect() as c: with db.connect() as c:
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (order_id,))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,)) c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([pending, approved, paid],)) c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([pending, approved, paid],))
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (uid,)) c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (uid,))

View File

@@ -17,7 +17,7 @@ def run():
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'reset-fixture',%s,%s,now())''', VALUES(%s,%s,%s,'reset-fixture',%s,%s,now())''',
(quote, owner, uuid4(), Jsonb({'customer': {}, 'items': []}), Jsonb({'items': [], 'total_cents': 1490}))) (quote, owner, uuid4(), Jsonb({'customer': {}, 'items': []}), Jsonb({'items': [], 'total_cents': 1490})))
c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)', c.execute("INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')",
(order, quote, owner, Jsonb({'items': [], 'total_cents': 1490}), Jsonb({'provider': 'teste'}))) (order, quote, owner, Jsonb({'items': [], 'total_cents': 1490}), Jsonb({'provider': 'teste'})))
live = c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method, live = c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,
status,amount_cents,response) VALUES(%s,%s,'mercadopago',%s,'card','approved',1490,%s) RETURNING id''', status,amount_cents,response) VALUES(%s,%s,'mercadopago',%s,'card','approved',1490,%s) RETURNING id''',
@@ -45,7 +45,19 @@ def run():
assert not c.execute('''SELECT 1 FROM dtf_local.uploads WHERE purged_at IS NULL assert not c.execute('''SELECT 1 FROM dtf_local.uploads WHERE purged_at IS NULL
AND expires_at>now()''').fetchone() AND expires_at>now()''').fetchone()
assert c.execute('SELECT count(*) AS n FROM dtf_local.operators').fetchone()['n'] >= 1 assert c.execute('SELECT count(*) AS n FROM dtf_local.operators').fetchone()['n'] >= 1
assert 'Apagado.' in lines and any('#1' in line for line in lines), lines assert 'Apagado.' in lines and 'A numeração dos pedidos recomeça em #1.' in lines, lines
# The worker's own role restarts the numbers: the next order is #1.
with db.connect() as c:
quote = uuid4()
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'reset-fixture',%s,%s,now())''',
(quote, owner, uuid4(), Jsonb({'customer': {}, 'items': []}), Jsonb({'items': [], 'total_cents': 1490})))
first = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
VALUES(%s,%s,%s,%s,%s,'site') RETURNING number''', (uuid4(), quote, owner, Jsonb({'items': []}),
Jsonb({'provider': 'teste'}))).fetchone()['number']
assert first == 1, first
c.execute('DELETE FROM dtf_local.orders WHERE quote_id=%s', (quote,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
print('PASS: launch cleanup refuses real payments, counts first, then removes test orders and quotes') print('PASS: launch cleanup refuses real payments, counts first, then removes test orders and quotes')

410
tests/mail_test.py Normal file
View File

@@ -0,0 +1,410 @@
"""E-mail: a customer's password recovery, signup codes and order confirmation.
Run inside the API container: python -m tests.mail_test
The local stack keeps e-mail in the database (MAIL_ADAPTER=log); the SMTP
path is checked against a small SMTP server this test runs itself.
"""
import email
import email.utils
import hashlib
import os
import re
import secrets
import socketserver
import threading
from email import policy
from uuid import uuid4
from app import mail
from app.core import db
from tests.smoke_test import Client, approved_quote, item_spec, register, upload_bytes
CNPJ = '11222333000181'
PASSWORD = 'senha-antiga-12345'
NEW_PASSWORD = 'senha-nova-678901'
class Sink(socketserver.ThreadingTCPServer):
"""Just enough SMTP to receive what smtplib sends, kept in `messages`."""
allow_reuse_address = True
daemon_threads = True
def __init__(self):
self.messages = []
super().__init__(('127.0.0.1', 0), SinkHandler)
class SinkHandler(socketserver.StreamRequestHandler):
def reply(self, line):
self.wfile.write(line.encode() + b'\r\n')
def handle(self):
self.reply('220 sink')
rcpt = []
while line := self.rfile.readline():
verb = line.decode().strip().split(' ')[0].upper()
if verb == 'EHLO':
self.wfile.write(b'250-sink\r\n250 8BITMIME\r\n')
elif verb == 'RCPT':
rcpt.append(line.decode().strip())
self.reply('250 ok')
elif verb == 'DATA':
self.reply('354 go')
data = b''
while (chunk := self.rfile.readline()) != b'.\r\n':
data += chunk[1:] if chunk.startswith(b'..') else chunk
self.server.messages.append((rcpt, email.message_from_bytes(data, policy=policy.default)))
self.reply('250 queued')
elif verb == 'QUIT':
self.reply('221 bye')
return
else:
self.reply('250 ok')
def queued(c, to, kind):
return c.execute('SELECT * FROM dtf_local.mail_queue WHERE to_addr=%s AND kind=%s ORDER BY id',
(to, kind)).fetchall()
def recovery(tag):
address = f'cliente-{tag}@example.test'
customer = Client()
assert customer.call('/session')['password_recovery'] is True
register(customer, {'cnpj': CNPJ, 'zap': '16999990000', 'mail': address}, PASSWORD)
# Signed in elsewhere with the old password: the reset signs that out.
elsewhere = Client()
elsewhere.call('/session')
elsewhere.call('/account/login', {'email': address, 'password': PASSWORD})
# The same answer whether or not the e-mail has an account.
stranger = Client()
stranger.call('/session')
unknown = stranger.call('/account/forgot', {'email': f'ninguem-{tag}@example.test'})
known = stranger.call('/account/forgot', {'email': address.upper()})
assert unknown == known and 'Se houver uma conta' in known['message']
with db.connect() as c:
assert not queued(c, f'ninguem-{tag}@example.test', 'reset')
[message] = queued(c, address, 'reset')
link = re.search(r'(\S+)/conta/redefinir#([A-Za-z0-9_-]+)', message['body'])
assert link and '1 hora' in message['body'], message['body']
token = link.group(2)
with db.connect() as c:
# Only the token's hash is kept.
assert not c.execute('SELECT 1 FROM dtf_local.password_resets WHERE token_hash=%s', (token,)).fetchone()
# An account never confirmed: the reset link, sent to the address, confirms it.
c.execute('UPDATE dtf_local.accounts SET email_verified=false WHERE email=%s', (address,))
stranger.call('/account/reset', {'token': 'x' * 43, 'password': NEW_PASSWORD}, expected=400)
stranger.call('/account/reset', {'token': token, 'password': 'curta'}, expected=422)
assert stranger.call('/account/reset', {'token': token, 'password': NEW_PASSWORD})['customer']['mail'] == address
assert stranger.call('/account/me')['customer']['mail'] == address
with db.connect() as c:
assert c.execute('SELECT email_verified FROM dtf_local.accounts WHERE email=%s', (address,)).fetchone()['email_verified']
# Works once; the old password and the old sessions are gone.
stranger.call('/account/reset', {'token': token, 'password': NEW_PASSWORD}, expected=400)
elsewhere.call('/account/me', expected=401)
Client().call('/account/login', {'email': address, 'password': PASSWORD}, expected=401)
Client().call('/account/login', {'email': address, 'password': NEW_PASSWORD})
# An expired link does nothing.
expired = secrets.token_urlsafe(32)
with db.connect() as c:
account = c.execute('SELECT id FROM dtf_local.accounts WHERE email=%s', (address,)).fetchone()['id']
c.execute('''INSERT INTO dtf_local.password_resets(token_hash,account_id,expires_at)
VALUES(%s,%s,now()-interval '1 minute')''', (hashlib.sha256(expired.encode()).hexdigest(), account))
stranger.call('/account/reset', {'token': expired, 'password': NEW_PASSWORD}, expected=400)
# A few links an hour per address, so nobody fills someone's inbox.
other = f'muitos-{tag}@example.test'
for _ in range(3):
stranger.call('/account/forgot', {'email': other})
stranger.call('/account/forgot', {'email': other}, expected=429)
return address
def code_of(c, address):
body = c.execute("SELECT body FROM dtf_local.mail_queue WHERE kind='code' AND to_addr=%s ORDER BY id DESC LIMIT 1",
(address,)).fetchone()['body']
return re.search(r'\b(\d{6})\b', body).group(1)
def signup(tag):
"""The account exists only once the code sent to the address is entered."""
address = f'novo-{tag}@example.test'
customer = {'cnpj': CNPJ, 'zap': '16999990000', 'mail': address}
browser = Client()
browser.call('/session')
started = browser.call('/account/register', {'customer': customer, 'password': PASSWORD})
assert started['email'] == address and started['minutes'] == 15 and started['verify'], started
assert browser.call('/account/me')['customer'] is None
with db.connect() as c:
assert not c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (address,)).fetchone()
first = code_of(c, address)
html = queued(c, address, 'code')[-1]['html']
assert '&nbsp;'.join(first) in html and 'Confirme seu e-mail' in html, html[:200]
# The password is stored hashed from the first step.
assert c.execute('SELECT password_hash FROM dtf_local.account_signups WHERE id=%s',
(started['verify'],)).fetchone()['password_hash'].startswith('scrypt-v2$')
wrong = '000000' if first != '000000' else '111111'
attempt = lambda code, expected: browser.call('/account/register/verify', {'signup': started['verify'], 'code': code},
expected=expected)
assert 'Restam 4' in attempt(wrong, 400)['detail']
attempt('12a456', 422)
# Another code only after a minute; the old one stops working.
browser.call('/account/register/resend', {'signup': started['verify']}, expected=429)
with db.connect() as c:
c.execute("UPDATE dtf_local.account_signups SET sent_at=now()-interval '2 minutes' WHERE id=%s", (started['verify'],))
browser.call('/account/register/resend', {'signup': started['verify']})
with db.connect() as c:
second = code_of(c, address)
if second != first:
attempt(first, 400)
# Five wrong codes lock it until a new code is asked for.
with db.connect() as c:
c.execute('UPDATE dtf_local.account_signups SET attempts=5 WHERE id=%s', (started['verify'],))
attempt(second, 429)
with db.connect() as c:
c.execute('UPDATE dtf_local.account_signups SET attempts=0 WHERE id=%s', (started['verify'],))
assert attempt(second, 200)['customer']['mail'] == address
assert browser.call('/account/me')['customer']['mail'] == address
attempt(second, 410)
Client().call('/account/login', {'email': address, 'password': PASSWORD})
# An address that already has an account: the same answer, a notice instead
# of a code, and no code opens anything.
again = Client()
again.call('/session')
other = again.call('/account/register', {'customer': customer, 'password': NEW_PASSWORD})
assert set(other) == set(started) and other['email'] == address
with db.connect() as c:
notices = c.execute("SELECT subject FROM dtf_local.mail_queue WHERE kind='account' AND to_addr=%s",
(address,)).fetchall()
assert len(notices) == 1 and 'já tem conta' in notices[0]['subject']
assert code_of(c, address) == second
again.call('/account/register/verify', {'signup': other['verify'], 'code': second}, expected=400)
Client().call('/account/login', {'email': address, 'password': NEW_PASSWORD}, expected=401)
# An expired code.
late = Client()
late.call('/session')
expiring = late.call('/account/register', {'customer': {**customer, 'mail': f'tarde-{tag}@example.test'},
'password': PASSWORD})
with db.connect() as c:
code = code_of(c, f'tarde-{tag}@example.test')
c.execute("UPDATE dtf_local.account_signups SET expires_at=now()-interval '1 second' WHERE id=%s",
(expiring['verify'],))
late.call('/account/register/verify', {'signup': expiring['verify'], 'code': code}, expected=410)
def email_change(tag):
"""A new e-mail is the account's only once the code sent to it is entered,
and the old address is told."""
old, new, taken = (f'{n}-{tag}@example.test' for n in ('antigo', 'trocado', 'ocupado'))
owner = Client()
owner.call('/session')
register(owner, {'cnpj': CNPJ, 'zap': '16999990000', 'mail': old}, PASSWORD)
register(Client(), {'cnpj': CNPJ, 'zap': '16999990000', 'mail': taken}, PASSWORD)
owner.call('/account/email', {'email': new, 'password': 'senha-errada-123'}, expected=401)
owner.call('/account/email', {'email': old, 'password': PASSWORD}, expected=422)
owner.call('/account/email', {'email': taken, 'password': PASSWORD}, expected=409)
started = owner.call('/account/email', {'email': new.upper(), 'password': PASSWORD})
assert started['email'] == new and started['verify'], started
assert owner.call('/account/me')['customer']['mail'] == old
with db.connect() as c:
code = code_of(c, new)
wrong = '000000' if code != '000000' else '111111'
assert 'Restam 4' in owner.call('/account/email/verify', {'change': started['verify'], 'code': wrong}, expected=400)['detail']
# Another signed-in customer cannot complete someone else's change.
stranger = Client()
stranger.call('/session')
register(stranger, {'cnpj': CNPJ, 'zap': '16999990000', 'mail': f'outro-{tag}@example.test'}, PASSWORD)
stranger.call('/account/email/verify', {'change': started['verify'], 'code': code}, expected=410)
owner.call('/account/email/resend', {'change': started['verify']}, expected=429)
assert owner.call('/account/email/verify', {'change': started['verify'], 'code': code})['customer']['mail'] == new
assert owner.call('/account/me')['customer']['mail'] == new
owner.call('/account/email/verify', {'change': started['verify'], 'code': code}, expected=410)
Client().call('/account/login', {'email': new, 'password': PASSWORD})
Client().call('/account/login', {'email': old, 'password': PASSWORD}, expected=401)
with db.connect() as c:
[notice] = queued(c, old, 'notice')
assert new in notice['body'] and 'Se não foi você' in notice['body']
def smtp_delivery(tag):
"""The worker's SMTP path, against a server of our own."""
sink = Sink()
threading.Thread(target=sink.serve_forever, daemon=True).start()
saved = mail.ADAPTER, {k: os.environ.get(k) for k in ('SMTP_HOST', 'SMTP_PORT', 'SMTP_SECURITY', 'MAIL_FROM')}
to = f'smtp-{tag}@example.test'
try:
mail.ADAPTER = 'smtp'
os.environ.update(SMTP_HOST='127.0.0.1', SMTP_PORT=str(sink.server_address[1]), SMTP_SECURITY='none',
MAIL_FROM='DTF Dropstar <nao-responda@dropstar.test>')
with db.connect() as c:
# Not due yet, so the stack's own worker leaves them to this test.
ids = [c.execute('''INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body,html,available_at)
VALUES(%s,%s,%s,%s,%s,now()+interval '1 hour') RETURNING id''',
(kind, to, subject, body, html)).fetchone()['id']
for kind, subject, body, html in (
('reset', 'Crie uma nova senha · DTF Dropstar', 'link secreto ção', None),
('test', 'Teste de e-mail', 'olá equipe', None),
('code', '123456 é o seu código', 'código 123456', '<p>código 123456</p>'))]
mail.send_pending(db.connect, ids=ids)
assert len(sink.messages) == 3, sink.messages
# A customer message goes as plain text and HTML, the client picks.
coded = sink.messages[2][1]
assert coded.get_content_type() == 'multipart/alternative', coded.get_content_type()
assert coded.get_body(('plain',)).get_content().strip() == 'código 123456'
assert '<p>código 123456</p>' in coded.get_body(('html',)).get_content()
rcpt, first = sink.messages[0]
assert to in rcpt[0] and first['Subject'] == 'Crie uma nova senha · DTF Dropstar'
assert first['From'] == 'DTF Dropstar <nao-responda@dropstar.test>'
assert first['Date'] and email.utils.parsedate_to_datetime(first['Date'])
assert first.get_content().strip() == 'link secreto ção'
with db.connect() as c:
sent = {r['kind']: r for r in queued(c, to, 'reset') + queued(c, to, 'test') + queued(c, to, 'code')}
# A recovery link or a signup code is erased once sent; other messages keep their text.
assert sent['reset']['sent_at'] and sent['reset']['body'] == ''
assert sent['code']['sent_at'] and sent['code']['body'] == '' and sent['code']['html'] is None
assert sent['test']['sent_at'] and sent['test']['body'] == 'olá equipe'
# A server that does not answer: retried later, with the error kept.
os.environ['SMTP_PORT'] = '1'
with db.connect() as c:
failing = c.execute('''INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body,available_at)
VALUES('test',%s,'x','y',now()+interval '1 hour') RETURNING id''', (to,)).fetchone()['id']
mail.send_pending(db.connect, ids=[failing])
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.mail_queue WHERE id=%s', (failing,)).fetchone()
assert row['attempts'] == 1 and row['last_error'] and not row['sent_at'] and not row['failed_at']
assert mail.status(c)['error']['to'] == to
c.execute('DELETE FROM dtf_local.mail_queue WHERE id=%s', (failing,))
finally:
mail.ADAPTER = saved[0]
for key, value in saved[1].items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
sink.shutdown()
def order_confirmation(tag):
"""A paid order sends the customer the confirmation, and the team nothing."""
su = Client()
su.call('/session')
customer = Client()
customer.call('/session')
uid = upload_bytes(customer, b'MAIL ORDER ARTWORK')
item = item_spec('file', '1.2', 0, uid)
quote = customer.call('/quotes', {'request_key': str(uuid4()), 'items': [item],
'customer': {'cnpj': CNPJ, 'zap': '16999990000', 'mail': f'pedido-{tag}@example.test'},
'freight': {'service': 'pickup'}})
approved_quote(customer, quote, [item])
order = customer.call('/orders/dev-paid', {'quote_id': quote['id']})
with db.connect() as c:
# The customer gets the confirmation, with the order in the account.
[confirmed] = queued(c, f'pedido-{tag}@example.test', 'order')
assert confirmed['subject'] == f"Recebemos seu pedido #{order['number']} · DTF Dropstar"
assert f"/conta/pedidos?order={order['id']}" in confirmed['body'] and 'Retirada em Franca-SP' in confirmed['body']
assert f"Recebemos seu pedido #{order['number']}" in confirmed['html'] and 'Ver meu pedido' in confirmed['html']
assert not c.execute("SELECT 1 FROM dtf_local.mail_queue WHERE kind='alert' AND subject LIKE %s",
(f"%#{order['number']} %",)).fetchone()
# The test message goes to whoever asked for it.
sent = su.call('/operator/mail/test', {}, operator=True)
with db.connect() as c:
assert queued(c, sent['to'], 'test')
return order['id'], quote['id']
def guest_order(document, address, made):
"""An order bought without an account, in a browser of its own."""
browser = Client()
browser.call('/session')
uid = upload_bytes(browser, b'GUEST ORDER ARTWORK')
item = item_spec('file', '1.2', 0, uid)
quote = browser.call('/quotes', {'request_key': str(uuid4()), 'items': [item],
'customer': {'cnpj': document, 'zap': '16999990000', 'mail': address},
'freight': {'service': 'pickup'}})
approved_quote(browser, quote, [item])
order = browser.call('/orders/dev-paid', {'quote_id': quote['id']})
made.append((order['id'], quote['id']))
return order['id'], uid
def claimed_orders(tag, made):
"""A confirmed account brings the orders bought without it with its CPF or
CNPJ and e-mail, from any browser; a CPF alone or an unconfirmed e-mail
brings nothing."""
cpf, address = '52998224725', f'comprador-{tag}@example.test'
mine, art = guest_order('529.982.247-25', address.upper(), made)
other_mail, _ = guest_order(cpf, f'outro-{tag}@example.test', made)
other_document, _ = guest_order(CNPJ, address, made)
# Someone who knows the CPF, with an e-mail of their own: nothing.
stranger = Client()
stranger.call('/session')
register(stranger, {'cnpj': cpf, 'zap': '16999990000', 'mail': f'curioso-{tag}@example.test'}, PASSWORD)
assert stranger.call('/customer/orders?page=1&size=10')['items'] == []
# The customer, on another computer: the order comes with its cart and files.
customer = Client()
customer.call('/session')
register(customer, {'cnpj': cpf, 'zap': '16999990000', 'mail': address}, PASSWORD)
listed = lambda client: {e['id'] for e in client.call('/customer/orders?page=1&size=10')['items'] if e['kind'] == 'order'}
assert listed(customer) == {mine}, listed(customer)
customer.call('/customer/orders/' + mine)
with db.connect() as c:
account = c.execute('SELECT id,email_verified FROM dtf_local.accounts WHERE email=%s', (address,)).fetchone()
assert account['email_verified']
assert c.execute('SELECT owner FROM dtf_local.uploads WHERE id=%s', (art,)).fetchone()['owner'] == account['id']
owners = {r['id']: r['owner'] for r in c.execute('SELECT id,owner FROM dtf_local.orders WHERE id=ANY(%s)',
([other_mail, other_document],)).fetchall()}
assert account['id'] not in owners.values()
# Bought later without signing in, elsewhere: it comes at the next sign-in.
later, _ = guest_order(cpf, address, made)
Client().call('/account/login', {'email': address, 'password': PASSWORD})
assert listed(customer) == {mine, later}
# An account whose e-mail was never confirmed brings nothing.
with db.connect() as c:
c.execute('UPDATE dtf_local.accounts SET email_verified=false WHERE id=%s', (account['id'],))
unconfirmed, _ = guest_order(cpf, address, made)
Client().call('/account/login', {'email': address, 'password': PASSWORD})
assert unconfirmed not in listed(customer)
def run():
tag = secrets.token_hex(3)
order = quote = None
made = []
with db.connect() as c:
# The recovery's per-source limit would make a second run within 15 minutes fail.
c.execute('DELETE FROM dtf_local.login_attempts')
try:
recovery(tag)
signup(tag)
email_change(tag)
smtp_delivery(tag)
order, quote = order_confirmation(tag)
made.append((order, quote))
claimed_orders(tag, made)
print('PASS: password recovery by a one-time link, signup and e-mail changes confirmed by an e-mailed code, '
'SMTP delivery and retry, order confirmation and no team alerts, guest orders brought by CPF/CNPJ and e-mail')
finally:
with db.connect() as c:
for order, quote in made:
for table in ('movements', 'print_files', 'order_files'):
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (order,))
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{order}:%',))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
c.execute('DELETE FROM dtf_local.payment_intents WHERE quote_id=%s', (quote,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
c.execute("DELETE FROM dtf_local.mail_queue WHERE to_addr LIKE %s OR kind='test'", (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.account_signups WHERE email LIKE %s', (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.email_changes WHERE new_email LIKE %s', (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.accounts WHERE email LIKE %s', (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.login_attempts')
if __name__ == '__main__':
run()

View File

@@ -1,4 +1,5 @@
"""Discarding an unpaid quote, deleting a test order, cancelling a paid one. """Discarding an unpaid quote, deleting a test order, marking an order as waiting
for contact, cancelling a paid one.
Run inside the API container: python -m tests.order_actions_test Run inside the API container: python -m tests.order_actions_test
""" """
@@ -26,7 +27,7 @@ def run():
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'actions-fixture',%s,%s,now())''', VALUES(%s,%s,%s,'actions-fixture',%s,%s,now())''',
(qid, owner, uuid4(), Jsonb({'customer': {'mail': mail}, 'items': []}), Jsonb(approved))) (qid, owner, uuid4(), Jsonb({'customer': {'mail': mail}, 'items': []}), Jsonb(approved)))
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)''', c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')''',
(paid_order, paid_quote, owner, Jsonb(approved), Jsonb({'provider': 'mercadopago', 'id': '1'}))) (paid_order, paid_quote, owner, Jsonb(approved), Jsonb({'provider': 'mercadopago', 'id': '1'})))
listed = lambda: {q['id'] for q in client.call('/operator/quotes?' + urlencode({'kind': 'approved', 'q': mail}), listed = lambda: {q['id'] for q in client.call('/operator/quotes?' + urlencode({'kind': 'approved', 'q': mail}),
operator=True)['quotes']} operator=True)['quotes']}
@@ -52,6 +53,22 @@ def run():
test_order = None test_order = None
assert str(test_quote) in listed() assert str(test_quote) in listed()
# "Aguardando contato": a mark with what to agree, on the board until cleared.
client.call(f'/operator/orders/{paid_order}/contact', {'waiting': True, 'note': ' '}, operator=True, expected=422)
client.call(f'/operator/orders/{paid_order}/contact', {'waiting': True, 'note': 'Confirmar a cor do fundo'},
operator=True)
marked = {o['id']: o for o in client.call('/operator/board', operator=True)['orders']}[str(paid_order)]
assert marked['contact_note'] == 'Confirmar a cor do fundo' and marked['contact_since'], marked
assert marked['contact_by'] and marked['state'] == 'rec'
client.call(f'/operator/orders/{paid_order}/contact', {'waiting': False}, operator=True)
cleared = {o['id']: o for o in client.call('/operator/board', operator=True)['orders']}[str(paid_order)]
assert cleared['contact_since'] is None and cleared['contact_note'] is None
# The wait is kept, from mark to clear, for the time figures that leave it out (D-38).
with db.connect() as c:
waits = c.execute('SELECT started_at, ended_at FROM dtf_local.contact_waits WHERE order_id=%s',
(paid_order,)).fetchall()
assert len(waits) == 1 and waits[0]['ended_at'] and waits[0]['ended_at'] >= waits[0]['started_at'], waits
# A paid order is cancelled with a reason, kept, and can no longer move. # A paid order is cancelled with a reason, kept, and can no longer move.
# A paid order in progress is not deleted: it is cancelled first. # A paid order in progress is not deleted: it is cancelled first.
client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True, expected=409) client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True, expected=409)
@@ -60,6 +77,16 @@ def run():
board = client.call('/operator/board', operator=True) board = client.call('/operator/board', operator=True)
order = next(o for o in board['orders'] if o['id'] == str(paid_order)) order = next(o for o in board['orders'] if o['id'] == str(paid_order))
assert order['cancelled_at'] and order['cancel_reason'] == 'Cliente desistiu' assert order['cancelled_at'] and order['cancel_reason'] == 'Cliente desistiu'
# Tiny is told, once (app/tiny.py cancels it there while not invoiced).
with db.connect() as c:
told = c.execute("SELECT provider,payload FROM dtf_local.outbox WHERE event_key=%s",
(f'{paid_order}:cancelled:tiny',)).fetchall()
assert [(t['provider'], t['payload']['event'], t['payload']['reason']) for t in told] == \
[('tiny', 'cancelled', 'Cliente desistiu')], told
# The automatic folder hears it is cancelled, and so removes its files.
held = client.call('/operator/queue/folder', {'early': True, 'held': [str(paid_order)]}, operator=True)
assert held['states'] == {str(paid_order): 'cancelled'}, held['states']
assert not [f for f in held['files'] if f['order'] == str(paid_order)]
client.call(f'/operator/orders/{paid_order}/move', {'state': 'tra', 'version': order['version'], 'reason': ''}, client.call(f'/operator/orders/{paid_order}/move', {'state': 'tra', 'version': order['version'], 'reason': ''},
operator=True, expected=409) operator=True, expected=409)
client.call(f'/operator/orders/{paid_order}/cancel', {'note': 'de novo'}, operator=True, expected=404) client.call(f'/operator/orders/{paid_order}/cancel', {'note': 'de novo'}, operator=True, expected=404)
@@ -67,8 +94,8 @@ def run():
# Dragged within its column: first paid first, unless moved; moving on resets it. # Dragged within its column: first paid first, unless moved; moving on resets it.
with db.connect() as c: with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET created_at=now()-interval '1 hour' WHERE id=%s", (paid_order,)) c.execute("UPDATE dtf_local.orders SET created_at=now()-interval '1 hour' WHERE id=%s", (paid_order,))
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,created_at) c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,created_at,origin)
VALUES(%s,%s,%s,%s,%s,now())''', (newer_order, newer_quote, owner, Jsonb(approved), VALUES(%s,%s,%s,%s,%s,now(),'site')''', (newer_order, newer_quote, owner, Jsonb(approved),
Jsonb({'provider': 'teste', 'id': 't'}))) Jsonb({'provider': 'teste', 'id': 't'})))
client.call(f'/operator/orders/{newer_order}/queue', {'before': str(paid_order)}, operator=True) client.call(f'/operator/orders/{newer_order}/queue', {'before': str(paid_order)}, operator=True)
with db.connect() as c: with db.connect() as c:
@@ -82,6 +109,9 @@ def run():
client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True) client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True)
with db.connect() as c: with db.connect() as c:
assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (paid_order,)).fetchone() assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (paid_order,)).fetchone()
# Deleted: no state at all, so the folder removes its files too.
assert client.call('/operator/queue/folder', {'held': [str(paid_order)]}, operator=True)['states'] == {}
with db.connect() as c:
assert c.execute('SELECT discarded_at FROM dtf_local.quotes WHERE id=%s', (paid_quote,)).fetchone()['discarded_at'] assert c.execute('SELECT discarded_at FROM dtf_local.quotes WHERE id=%s', (paid_quote,)).fetchone()['discarded_at']
assert str(paid_quote) not in listed() assert str(paid_quote) not in listed()
@@ -99,8 +129,8 @@ def run():
'total_cents': 1490} 'total_cents': 1490}
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'actions-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb(content), Jsonb(content))) VALUES(%s,%s,%s,'actions-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb(content), Jsonb(content)))
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,cancelled_at,cancelled_by,cancel_reason) c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,cancelled_at,cancelled_by,cancel_reason,origin)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s)''', (order, quote, owner, Jsonb(content), Jsonb({'provider': provider, 'id': '1'}), VALUES(%s,%s,%s,%s,%s,%s,%s,%s,'site')''', (order, quote, owner, Jsonb(content), Jsonb({'provider': provider, 'id': '1'}),
'now()' if cancelled else None, 'x' if cancelled else None, 'now()' if cancelled else None, 'x' if cancelled else None,
'teste' if cancelled else None)) 'teste' if cancelled else None))
place(gone_quote, gone_order, [files['original'], files['shared']], 'mercadopago', True) place(gone_quote, gone_order, [files['original'], files['shared']], 'mercadopago', True)

View File

@@ -134,9 +134,8 @@ def run():
events = board.call('/operator/events?order=' + str(order['number']), operator=True)['events'] events = board.call('/operator/events?order=' + str(order['number']), operator=True)['events']
paid = [e for e in events if e['payload'].get('order_id') == order['id'] paid = [e for e in events if e['payload'].get('order_id') == order['id']
and e['payload'].get('event') == 'payment_approved'] and e['payload'].get('event') == 'payment_approved']
assert len(paid) == 2, f'expected one tiny and one whatsapp event, got {len(paid)}' assert [e['provider'] for e in paid] == ['tiny'], paid
assert {e['provider'] for e in paid} == {'tiny', 'whatsapp'}, paid print('PASS: exactly one Tiny notification for the order')
print('PASS: exactly one notification per provider for the order')
# A payment that was never reviewed, and one for something that is not a quote. # A payment that was never reviewed, and one for something that is not a quote.
deliver({'event_id': 'nonsense-' + uuid4().hex, 'reference': 'not-a-uuid', deliver({'event_id': 'nonsense-' + uuid4().hex, 'reference': 'not-a-uuid',
@@ -153,6 +152,11 @@ def run():
assert order['payment']['provider'] == 'teste' and order['state'] == 'rec', order assert order['payment']['provider'] == 'teste' and order['state'] == 'rec', order
assert tester.call('/operator/quotes/' + test_quote + '/test-order', {}, operator=True)['id'] == order['id'] assert tester.call('/operator/quotes/' + test_quote + '/test-order', {}, operator=True)['id'] == order['id']
version = order['version'] version = order['version']
# Arte conferida, the print queue, takes the order once its final is approved.
final = upload_bytes(tester, b'TEST ORDER FINAL', order_id=order['id'])
version = tester.call('/operator/orders/' + order['id'] + '/final-files',
{'version': version, 'files': [{'item_index': 0, 'upload_id': final}], 'note': 'Teste'},
operator=True)['version']
for state in ('tra',): for state in ('tra',):
moved = tester.call('/operator/orders/' + order['id'] + '/move', {'state': state, 'version': version}, operator=True) moved = tester.call('/operator/orders/' + order['id'] + '/move', {'state': state, 'version': version}, operator=True)
version = moved['version'] version = moved['version']
@@ -160,7 +164,48 @@ def run():
queued = c.execute("SELECT count(*) AS n FROM dtf_local.outbox WHERE event_key LIKE %s", (order['id'] + ':%',)).fetchone()['n'] queued = c.execute("SELECT count(*) AS n FROM dtf_local.outbox WHERE event_key LIKE %s", (order['id'] + ':%',)).fetchone()['n']
jobs = c.execute('SELECT count(*) AS n FROM dtf_local.print_files WHERE order_id=%s', (order['id'],)).fetchone()['n'] jobs = c.execute('SELECT count(*) AS n FROM dtf_local.print_files WHERE order_id=%s', (order['id'],)).fetchone()['n']
assert queued == 0 and jobs == 1, (queued, jobs) assert queued == 0 and jobs == 1, (queued, jobs)
print('PASS: an operator test order reaches the board and the print queue, never Tiny or WhatsApp') print('PASS: an operator test order reaches the board and the print queue, never Tiny')
# An order paid outside the system, registered by the team from its Site
# quote (D-35): origin and payment are chosen, never assumed.
_, counter_quote, counter_total = reviewed_quote()
register = lambda qid, body, expected=200: board.call('/operator/quotes/' + qid + '/register', body,
operator=True, expected=expected)
for body in ({'method': 'pix'}, {'origin': 'atendimento'}, {'origin': 'whatsapp', 'method': 'pix'},
{'origin': 'atendimento', 'method': 'boleto'}):
register(counter_quote, body, expected=422)
order = register(counter_quote, {'origin': 'atendimento', 'method': 'cash', 'note': 'Balcão'})
assert (order['origin'], order['state'], order['payment']['provider'], order['payment']['method'],
order['payment']['total_cents']) == ('atendimento', 'rec', 'manual', 'cash', counter_total), order
register(counter_quote, {'origin': 'atendimento', 'method': 'cash'}, expected=409)
with db.connect() as c:
sent = c.execute("SELECT payload FROM dtf_local.outbox WHERE event_key=%s", (order['id'] + ':paid:tiny',)).fetchone()
assert sent and sent['payload']['origin'] == 'atendimento' and sent['payload']['payment'] == {'method': 'cash', 'outside': True}, sent
# A Dropflow batch reaches Tiny too, carrying its origin for its own category; and its cancel.
_, batch_quote, _ = reviewed_quote()
batch = register(batch_quote, {'origin': 'dropflow', 'method': 'credit'})
board.call('/operator/orders/' + batch['id'] + '/cancel', {'note': 'Lote refeito'}, operator=True)
with db.connect() as c:
events = {r['event_key']: r['payload'] for r in c.execute(
"SELECT event_key, payload FROM dtf_local.outbox WHERE event_key LIKE %s", (batch['id'] + ':%',)).fetchall()}
paid = events.get(batch['id'] + ':paid:tiny')
assert batch['origin'] == 'dropflow' and paid and paid['origin'] == 'dropflow', (batch, events)
assert batch['id'] + ':cancelled:tiny' in events, events
print('PASS: an order paid outside is registered with its origin and payment, Dropflow ones included')
# The customer's proof only above 10 m (Dropstar, 2026-10-28): asked for on a
# shorter order, the server leaves it out.
for metres, kept in (('1.01', False), ('12', True)):
asker = Client()
asker.call('/session')
art = upload_bytes(asker, b'PROOF ' + metres.encode())
spec = item_spec('file', metres, 0, art)
profile = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'proof-' + uuid4().hex[:8] + '@example.test'}
asked = asker.call('/quotes', {'request_key': str(uuid4()), 'customer': profile, 'items': [spec],
'freight': {'service': 'pickup'}, 'proof': True})
approved = approved_quote(asker, asked, [spec])
assert bool(approved.get('proof')) is kept, (metres, approved.get('proof'))
print('PASS: a proof asked for at checkout is kept only above 10 m')
# Files are uploaded before payment. An unpaid cart keeps them briefly; a # Files are uploaded before payment. An unpaid cart keeps them briefly; a
# paid order keeps them for its 30 days; a payment never starts for files # paid order keeps them for its 30 days; a payment never starts for files

View File

@@ -87,19 +87,53 @@ def run():
pdf = response.read() pdf = response.read()
assert pdf.startswith(b'%PDF-') and pdf.rstrip().endswith(b'%%EOF') assert pdf.startswith(b'%PDF-') and pdf.rstrip().endswith(b'%%EOF')
width, height = map(float, re.search(rb'/MediaBox \[0 0 ([\d.]+) ([\d.]+)\]', pdf).groups()) width, height = map(float, re.search(rb'/MediaBox \[0 0 ([\d.]+) ([\d.]+)\]', pdf).groups())
assert abs(width - 57 * PT_PER_CM) < 0.01 and abs(height - 10 * PT_PER_CM) < 0.01, (width, height) # The layout's 10 cm and the 1,5 cm footer band, outside the billed length.
print('PASS: paid order generated a 57 x 10 cm print file with both copies') assert abs(width - 57 * PT_PER_CM) < 0.01 and abs(height - 11.5 * PT_PER_CM) < 0.01, (width, height)
assert row['detail']['footer'].startswith('DROPSTAR · Pedido DTF-%d · Item 1/1 · ' % order['number']), row['detail']
print('PASS: paid order generated a 57 x 10 cm print file with both copies and its footer')
# The automatic folder, downloading on arrival, gets the generated file
# before anyone approves it; at the queue only, it does not.
oid = order['id']
early = client.call('/operator/queue/folder', {'early': True, 'held': [oid]}, operator=True)
mine = [f for f in early['files'] if f['order'] == oid]
assert [(f['upload_id'], f['state']) for f in mine] == [(str(row['upload_id']), 'rec')], early['files']
assert mine[0]['name'].startswith('DTF-%d-item-1' % order['number']) and early['states'] == {oid: 'rec'}
late = client.call('/operator/queue/folder', {'early': False, 'held': []}, operator=True)
assert not [f for f in late['files'] if f['order'] == oid] and late['states'] == {}
client.call('/operator/queue/folder', {'early': True, 'held': []}, expected=401)
print('PASS: the folder gets a received order\'s generated file early, and only at the queue otherwise')
# The operator approves the generated file as the final one, with no upload, # The operator approves the generated file as the final one, with no upload,
# and the order can then enter the print queue. # and the order can then enter the print queue.
oid = order['id']
result = client.call('/operator/orders/' + oid + '/final-files', result = client.call('/operator/orders/' + oid + '/final-files',
{'version': order['version'], 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}], {'version': order['version'], 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],
'note': 'Generated print file checked'}, operator=True) 'note': 'Generated print file checked'}, operator=True)
version = result['version'] version = result['version']
for state in ('tra', 'fil'): # The file the system generated from the customer's art is not "Arte tratada".
client.call('/operator/orders/' + oid + '/move', {'state': state, 'version': version}, operator=True) board = client.call('/operator/board', operator=True)['orders']
version += 1 assert next(o for o in board if o['id'] == oid)['treated'] is None
# Arte conferida is the print queue (2026-10-23).
client.call('/operator/orders/' + oid + '/move', {'state': 'tra', 'version': version}, operator=True)
version += 1
# Printing, the folders still get the file of an order they hold (to take
# it to Finalizado later), and no one else's.
client.call('/operator/orders/' + oid + '/move', {'state': 'imp', 'version': version}, operator=True)
version += 1
held = client.call('/operator/queue/folder', {'early': True, 'held': [oid]}, operator=True)
assert [(f['state'], f['upload_id']) for f in held['files'] if f['order'] == oid] == [('imp', str(row['upload_id']))], held
assert held['states'] == {oid: 'imp'}
others = client.call('/operator/queue/folder', {'early': True, 'held': []}, operator=True)
assert not [f for f in others['files'] if f['order'] == oid], others['files']
# A folder chosen before this order was paid catches up on it, printing or
# not, as a computer that was off does when it comes back; one chosen
# after it does not.
earlier = client.call('/operator/queue/folder', {'early': True, 'held': [], 'since': '2000-01-01T00:00:00Z'},
operator=True)
assert [(f['state'], f['upload_id']) for f in earlier['files'] if f['order'] == oid] == [('imp', str(row['upload_id']))]
later = client.call('/operator/queue/folder', {'early': True, 'held': [], 'since': '2999-01-01T00:00:00Z'},
operator=True)
assert not [f for f in later['files'] if f['order'] == oid], later['files']
# Once queued for printing, the final set can no longer change. # Once queued for printing, the final set can no longer change.
client.call('/operator/orders/' + oid + '/final-files', client.call('/operator/orders/' + oid + '/final-files',
{'version': version, 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}], {'version': version, 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],

View File

@@ -54,6 +54,19 @@ class Client:
if exc.code!=expected:raise AssertionError((path,exc.code,exc.read().decode())) from exc if exc.code!=expected:raise AssertionError((path,exc.code,exc.read().decode())) from exc
return json.load(exc) return json.load(exc)
def register(client, customer, password):
"""Create an account as the Site does: with e-mail on, the code sent to the
address (kept readable on the local stack) confirms it."""
started=client.call('/account/register',{'customer':customer,'password':password})
if 'verify' not in started:
return started
from app.core import db
with db.connect() as c:
body=c.execute("SELECT body FROM dtf_local.mail_queue WHERE kind='code' AND to_addr=%s ORDER BY id DESC LIMIT 1",
(customer['mail'].strip().lower(),)).fetchone()['body']
code=next(word for word in body.split() if word.isdigit() and len(word)==6)
return client.call('/account/register/verify',{'signup':started['verify'],'code':code})
def wait_scan(client, uid, operator=False, expected='clean'): def wait_scan(client, uid, operator=False, expected='clean'):
prefix='/operator/uploads' if operator else '/uploads' prefix='/operator/uploads' if operator else '/uploads'
deadline=time.monotonic()+150 deadline=time.monotonic()+150
@@ -80,7 +93,7 @@ def upload_bytes(client, content, name='LOCAL-TEST.cdr', order_id=None, expected
return uid return uid
def item_spec(mode, metres, grade, uid): def item_spec(mode, metres, grade, uid):
film_width=28.5 if mode in ('uvfile','uv') else 57 film_width=27 if mode in ('uvfile','uv') else 57
length_cm=float(metres)*100 length_cm=float(metres)*100
return {'mode':mode,'metres':str(metres),'grade':grade,'uploads':[uid], return {'mode':mode,'metres':str(metres),'grade':grade,'uploads':[uid],
'production':{'version':2,'film_width_cm':film_width,'height_cm':length_cm, 'production':{'version':2,'film_width_cm':film_width,'height_cm':length_cm,
@@ -104,8 +117,8 @@ def run():
client=Client();other=Client() client=Client();other=Client()
config=client.call('/session');other.call('/session') config=client.call('/session');other.call('/session')
assert client.call('/health')['integrations']=='fake' assert client.call('/health')['integrations']=='fake'
# Sheets of several GB are the normal order: 5 GB per file. # 4 GB per file (Dropstar, 2026-10-28).
assert config['max_upload_bytes'] == 5 * 1024 ** 3 assert config['max_upload_bytes'] == 4 * 1024 ** 3
client.call('/uploads',{'name':'too-large.cdr', client.call('/uploads',{'name':'too-large.cdr',
'size':config['max_upload_bytes']+1},expected=413) 'size':config['max_upload_bytes']+1},expected=413)
cancelled=client.call('/uploads',{'name':'CANCELLED-PART.cdr','size':3})['id'] cancelled=client.call('/uploads',{'name':'CANCELLED-PART.cdr','size':3})['id']
@@ -153,6 +166,9 @@ def run():
client.call('/quotes',{**draft,'items':[outside]},expected=422) client.call('/quotes',{**draft,'items':[outside]},expected=422)
client.call('/quotes',{**draft,'items':[{**items[0],'metres':'1.00'}]},expected=422) client.call('/quotes',{**draft,'items':[{**items[0],'metres':'1.00'}]},expected=422)
client.call('/quotes',{**draft,'customer':{**draft['customer'],'cnpj':'11111111111111'}},expected=422) client.call('/quotes',{**draft,'customer':{**draft['customer'],'cnpj':'11111111111111'}},expected=422)
# A person buys with a CPF: its check digits count as a CNPJ's do.
client.call('/quotes',{**draft,'customer':{**draft['customer'],'cnpj':'529.982.247-24'}},expected=422)
client.call('/quotes',{**draft,'request_key':str(uuid4()),'customer':{**draft['customer'],'cnpj':'529.982.247-25'}})
quote=client.call('/quotes',draft) quote=client.call('/quotes',draft)
assert quote['status']=='pending_review' assert quote['status']=='pending_review'
assert client.call('/quotes/'+quote['id'])['review_reason']=='Pedido acima de 50 m' assert client.call('/quotes/'+quote['id'])['review_reason']=='Pedido acima de 50 m'
@@ -165,11 +181,16 @@ def run():
altered={**items[0],'production':{**items[0]['production'], altered={**items[0],'production':{**items[0]['production'],
'sources':[{**items[0]['production']['sources'][0],'measurement':'file'}]}} 'sources':[{**items[0]['production']['sources'][0],'measurement':'file'}]}}
client.call('/operator/quotes/'+qid+'/approve',{'items':[altered,*items[1:]]},operator=True,expected=422) client.call('/operator/quotes/'+qid+'/approve',{'items':[altered,*items[1:]]},operator=True,expected=422)
# Nor does the review change the residue the customer accepted (Dropstar, 2026-10-29).
client.call('/operator/quotes/'+qid+'/approve',{'items':[{**items[0],'residue_accepted':2},*items[1:]]},
operator=True,expected=422)
# Reviewer corrects a browser-supplied grade and length. Browser values are proposals. # Reviewer corrects a browser-supplied grade and length. Browser values are proposals.
# One price per product (2026-10-23): the grade is kept, the price ignores it.
corrected=[{**items[0],'metres':'1.01','grade':0},*items[1:]] corrected=[{**items[0],'metres':'1.01','grade':0},*items[1:]]
approved=client.call('/operator/quotes/'+qid+'/approve',{'items':corrected},operator=True) approved=client.call('/operator/quotes/'+qid+'/approve',{'items':corrected},operator=True)
assert approved['items'][0]['total_cents']==2189 assert approved['items'][0]['total_cents']==2189 and approved['items'][0]['grade']==0
assert approved['total_cents']==2189+32370+90870+109070+int(os.environ.get('MOCK_FREIGHT_CENTS','1500')) assert [i['unit_cents'] for i in approved['items'][1:]]==[2190,7990,8990]
assert approved['total_cents']==2189+28470+103870+116870+int(os.environ.get('MOCK_FREIGHT_CENTS','1500'))
assert approved['destination']=={**draft['destination'],'complement':''} assert approved['destination']=={**draft['destination'],'complement':''}
client.call('/operator/quotes/'+qid+'/approve',{'items':items},operator=True,expected=409) client.call('/operator/quotes/'+qid+'/approve',{'items':items},operator=True,expected=409)
assert not client.call('/quotes/'+qid)['auto_approved'] assert not client.call('/quotes/'+qid)['auto_approved']
@@ -184,15 +205,23 @@ def run():
assert auto['status']=='approved' assert auto['status']=='approved'
seen=client.call('/quotes/'+auto['id']) seen=client.call('/quotes/'+auto['id'])
assert seen['auto_approved'] and seen['review_reason'] is None assert seen['auto_approved'] and seen['review_reason'] is None
assert seen['approved']['total_cents']==6972+int(os.environ.get('MOCK_FREIGHT_CENTS','1500')) assert seen['approved']['total_cents']==6132+int(os.environ.get('MOCK_FREIGHT_CENTS','1500'))
assert client.call('/quotes',small)['status']=='approved' assert client.call('/quotes',small)['status']=='approved'
client.call('/operator/quotes/'+auto['id']+'/approve',{'items':small['items']},operator=True,expected=409) client.call('/operator/quotes/'+auto['id']+'/approve',{'items':small['items']},operator=True,expected=409)
# The Site grades only art it analysed; a discount on unanalysed art waits for a person. # The residue dots the customer accepted printing stay with the item.
accepted={**small,'request_key':str(uuid4()),'items':[{**item_spec('avulsa','2.75',90,graded),'residue_accepted':3}]}
client.call('/quotes',{**accepted,'items':[{**accepted['items'][0],'residue_accepted':-1}]},expected=422)
kept=client.call('/quotes',accepted)
assert kept['status']=='approved'
assert client.call('/quotes/'+kept['id'])['approved']['items'][0]['residue_accepted']==3
# The Site grades only art it analysed. A grade on art it did not analyse
# is checked against the file like any other, and this one cannot be.
claimed={**item_spec('avulsa','2.75',0,uid),'grade':90} claimed={**item_spec('avulsa','2.75',0,uid),'grade':90}
held=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[claimed]}) held=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[claimed]})
assert held['status']=='pending_review' assert held['status']=='pending_review'
assert client.call('/quotes/'+held['id'])['review_reason']=='Nota informada sem análise da arte' assert client.call('/quotes/'+held['id'])['review_reason']=='Nota não conferida no servidor'
# A better grade than the file supports, or one the server cannot check, waits too. # A better grade than the file supports, or one the server cannot check, waits too:
# the price ignores the grade, but the order shows it.
inflated=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',100,graded)]}) inflated=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',100,graded)]})
assert inflated['status']=='pending_review' assert inflated['status']=='pending_review'
assert client.call('/quotes/'+inflated['id'])['review_reason']=='Nota 100 maior que a do arquivo (90)' assert client.call('/quotes/'+inflated['id'])['review_reason']=='Nota 100 maior que a do arquivo (90)'
@@ -212,23 +241,29 @@ def run():
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':0},operator=True,expected=409) client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':0},operator=True,expected=409)
client.call('/operator/orders/'+oid+'/move',{'state':'cor','version':0},operator=True,expected=422) client.call('/operator/orders/'+oid+'/move',{'state':'cor','version':0},operator=True,expected=422)
version=0 version=0
for state in ('cor','rec','tra','fil','imp','fin'): # Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão comes before Finalizado.
if state=='fil': for state in ('cor','rec','tra','imp','rev','fin'):
client.call('/operator/orders/'+oid+'/move',{'state':'fil','version':version},operator=True,expected=409) if state=='tra':
# The queue takes approved final files only.
client.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
files=[{'item_index':i,'upload_id':upload_bytes(client,b'LOCAL FINAL FIXTURE '+str(i).encode(),order_id=oid)} for i in range(4)] files=[{'item_index':i,'upload_id':upload_bytes(client,b'LOCAL FINAL FIXTURE '+str(i).encode(),order_id=oid)} for i in range(4)]
result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True) result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True)
version=result['version'] version=result['version']
if state=='fin':
# Above 10 m the proof comes first: no Finalizado before Prova OK (app/proof.py).
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':version},operator=True,expected=409)
version=client.call('/operator/orders/'+oid+'/proof',{},operator=True)['version']
moved=client.call('/operator/orders/'+oid+'/move',{'state':state,'version':version,'reason':'Local test correction' if state=='cor' else ''},operator=True) moved=client.call('/operator/orders/'+oid+'/move',{'state':state,'version':version,'reason':'Local test correction' if state=='cor' else ''},operator=True)
version+=1;assert moved['version']==version version+=1;assert moved['version']==version
client.call('/operator/orders/'+oid+'/move',{'state':'rec','version':0},operator=True,expected=409) client.call('/operator/orders/'+oid+'/move',{'state':'rec','version':0},operator=True,expected=409)
assert len(client.call('/operator/orders/'+oid+'/history',operator=True))==6 assert len(client.call('/operator/orders/'+oid+'/history',operator=True))==6
# A mistaken move can be undone one stage at a time, with an internal # A mistaken move can be undone one stage at a time, with an internal
# reason. The customer is not told again: going back and forward once more # reason. The customer is not told again: going back and forward once more
# adds no messages (the outbox count below stays 8). # adds no messages (the outbox count below stays 4).
client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version},operator=True,expected=422) client.call('/operator/orders/'+oid+'/move',{'state':'rev','version':version},operator=True,expected=422)
client.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409) client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version},operator=True,expected=409)
back=client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version,'reason':'Movido por engano'},operator=True) back=client.call('/operator/orders/'+oid+'/move',{'state':'rev','version':version,'reason':'Movido por engano'},operator=True)
assert back['state']=='imp';version+=1 assert back['state']=='rev';version+=1
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':version},operator=True);version+=1 client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':version},operator=True);version+=1
history=client.call('/operator/orders/'+oid+'/history',operator=True) history=client.call('/operator/orders/'+oid+'/history',operator=True)
assert len(history)==8 and history[-2]['back'] and history[-2]['reason']=='Movido por engano' and not history[-1]['back'] assert len(history)==8 and history[-2]['back'] and history[-2]['reason']=='Movido por engano' and not history[-1]['back']
@@ -242,16 +277,15 @@ def run():
deadline=time.monotonic()+30 deadline=time.monotonic()+30
while time.monotonic()<deadline: while time.monotonic()<deadline:
events=[e for e in client.call('/operator/events?order='+str(order['number']),operator=True)['events'] if e['payload']['order_id']==oid] events=[e for e in client.call('/operator/events?order='+str(order['number']),operator=True)['events'] if e['payload']['order_id']==oid]
if len(events)==8 and all(e['delivered_at'] and e['receipt'] for e in events):break if len(events)==4 and all(e['delivered_at'] and e['receipt'] for e in events):break
time.sleep(1) time.sleep(1)
else:raise AssertionError('Mock outbox did not drain') else:raise AssertionError('Mock outbox did not drain')
assert len({e['event_key'] for e in events})==8 assert len({e['event_key'] for e in events})==4 and {e['provider'] for e in events}=={'tiny'}
# Tiny sets the pickup situação from the order it is sent; the fake sale # Tiny sets the pickup situação from the order it is sent; the fake sale
# has no Tiny id, so the real adapter would search for it. # has no Tiny id, so the real adapter would search for it.
ready={e['provider']:e['payload'] for e in events if e['payload']['event']=='ready'} ready={e['provider']:e['payload'] for e in events if e['payload']['event']=='ready'}
assert ready['tiny']['order']['freight']==order['snapshot']['freight'] and 'tiny_id' in ready['tiny'] assert ready['tiny']['order']['freight']==order['snapshot']['freight'] and 'tiny_id' in ready['tiny']
assert 'order' not in ready['whatsapp'] print(f"PASS: 4 durable fake receipts. Local test order #{order['number']} retained in Finalizado.")
print(f"PASS: 8 durable fake receipts. Local test order #{order['number']} retained in Finalizado.")
return oid return oid
if __name__=='__main__':run() if __name__=='__main__':run()

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