Compare commits

..

45 Commits

Author SHA1 Message Date
Cauê Faleiros
4219db8215 feat: Números per machine, month by month (front 1b)
All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 5m58s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m4s
A new Números section, "Máquinas, mês a mês", one column per machine
and a month at a time: metres printed, metres per hour and hours
running (time shared by two orders counted once), hours stopped with
their reasons; metres per film roll, ink per 100 m by colour, powder
per 100 m; supplies, parts and total cost per metre; what the printed
orders sold, the month's contribution and since installation; and the
return in % and months to pay back once Gestão types the price.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:59:37 -03:00
105 changed files with 10878 additions and 2262 deletions

View File

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

View File

@@ -18,6 +18,8 @@ OPERATOR_EMAIL=operator@example.test
OPERATOR_PASSWORD=local-operator-only
APP_ENV=local
PAYMENT_ADAPTER=fake
# Designer treatment, fixed per order in cents; 0 hides the option.
TREATMENT_CENTS=0
FREIGHT_ADAPTER=fake
TINY_ADAPTER=fake
# Sandbox only (see docs/LOCAL_SETUP.md, "Provider sandboxes"):

View File

@@ -73,7 +73,7 @@ jobs:
# one a developer exercises on localhost.
- name: API and workflow regressions
run: |
for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test mail_test thumbnail_backfill_test launch_reset_test; do
for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test; do
echo "--- $suite"
$COMPOSE exec -T \
-e SITE_BASE_URL=http://site \
@@ -86,7 +86,7 @@ jobs:
# the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration.
- name: Print-file geometry and provider adapters
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_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
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats -v
- name: Runtime and retention regressions
run: |

View File

@@ -205,6 +205,8 @@ class ObjectStorage(Protocol):
def store(self, key: str, path: str, content_type: str): ...
def health(self): ...
def discard(self, key: str, upload_id: str, complete: bool): ...
def discard_prefix(self, prefix: str): ...
def view(self, key: str, content_type: str, expires: int = 3600) -> str: ...
class LocalS3Storage:
def __init__(self):
@@ -222,7 +224,7 @@ class LocalS3Storage:
raise
self.client.create_bucket(Bucket=self.bucket)
self.client.put_bucket_lifecycle_configuration(Bucket=self.bucket, LifecycleConfiguration={
'Rules': [{'ID': 'local-artwork-retention', 'Status': 'Enabled', 'Filter': {'Prefix': ''},
'Rules': [{'ID': 'local-artwork-retention', 'Status': 'Enabled', 'Filter': {'Prefix': 'originals/'},
'Expiration': {'Days': 30}, 'AbortIncompleteMultipartUpload': {'DaysAfterInitiation': 1}}]})
def health(self):
@@ -266,6 +268,25 @@ class LocalS3Storage:
'ResponseContentDisposition': "attachment; filename*=UTF-8''" + quote(name, safe=''),
'ResponseContentType': 'application/octet-stream'}, ExpiresIn=300)
def view(self, key, content_type, expires=3600):
"""A link to show an object in the page, not download it: the Kanban's
viewer reads a film's pieces for as long as it is open (item 7)."""
return self.public.generate_presigned_url('get_object', Params={
'Bucket': self.bucket, 'Key': key, 'ResponseContentType': content_type}, ExpiresIn=expires)
def discard_prefix(self, prefix):
"""Delete every object under `prefix`, such as a print file's pieces."""
token = None
while True:
page = self.client.list_objects_v2(Bucket=self.bucket, Prefix=prefix,
**({'ContinuationToken': token} if token else {}))
keys = [{'Key': item['Key']} for item in page.get('Contents', [])]
if keys:
self.client.delete_objects(Bucket=self.bucket, Delete={'Objects': keys, 'Quiet': True})
if not page.get('IsTruncated'):
return
token = page['NextContinuationToken']
def discard(self, key, upload_id, complete):
if not complete:
try:

View File

@@ -8,6 +8,7 @@ from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException
from ..core import db
from .. import proof
from ..artwork import submit_files
from ..core.auth import can, operator
from ..core.models import ArtworkSubmission, UploadStart
@@ -18,9 +19,15 @@ router = APIRouter()
@router.post('/api/operator/orders/{oid}/uploads')
def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
if not body.name.lower().endswith('.png'):
raise HTTPException(422, 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.')
with db.connect() as c:
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
row = c.execute('SELECT id,state,parent_id,proof_ok_at FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
if not row: raise HTTPException(404, 'Order not found')
if row['parent_id']:
raise HTTPException(409, 'A prova recebe o PNG final automaticamente.')
if not proof.manual_source_needed(c, row):
proof.require_unlocked(c, row)
if row['state'] not in ('rec','cor'): raise HTTPException(409, 'Order is not in artwork review')
return begin_upload(body, session_id=operator_identity(user))
@@ -52,4 +59,8 @@ def final_files(oid: UUID, body: ArtworkSubmission, user=Depends(can('produce'))
with db.connect() as c:
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (oid,)).fetchone()
if not order: raise HTTPException(404, 'Order not found')
if order['parent_id']:
raise HTTPException(409, 'O arquivo final da prova é gerado automaticamente. Use Gerar de novo se falhar.')
if not proof.manual_source_needed(c, order):
proof.require_unlocked(c, order)
return submit_files(c,order,body,operator_identity(user),'final',user)

View File

@@ -501,10 +501,18 @@ def detail(oid: UUID, identity=Depends(owner)):
# only a correction's reason is written for the customer.
history = c.execute('''SELECT from_state,to_state,CASE WHEN to_state='cor' THEN reason ELSE '' END AS reason,
created_at FROM dtf_local.movements WHERE order_id=%s AND NOT back ORDER BY id''', (oid,)).fetchall()
# The review photos only once the order is Finalizado; a video stays
# on the Kanban card (app/reviews.py).
photos = c.execute('''SELECT r.id,u.name,r.created_at FROM dtf_local.order_reviews r
JOIN dtf_local.uploads u ON u.id=r.upload_id
WHERE r.order_id=%s AND r.kind='photo' ORDER BY r.seq''', (oid,)).fetchall() \
if row['state'] == 'fin' else []
return {'id': row['id'], 'number': row['number'], 'code': order_code(row['id']),
'state': row['state'], 'version': row['version'],
'created_at': row['created_at'], 'snapshot': row['snapshot'], 'history': history,
'files': file_rows(c,oid)}
'files': file_rows(c,oid),
'reviews': [{'id': photo['id'], 'name': photo['name'], 'created_at': photo['created_at']}
for photo in photos]}
@router.post('/api/customer/orders/{oid}/corrections')
def correction(oid: UUID, body: ArtworkSubmission, identity=Depends(owner)):

View File

@@ -9,7 +9,7 @@ from ..core import db
from .. import mail
from ..core.auth import client_ip, owner, new_session, rate_limit
from ..core.limits import upload_limit_bytes
from ..core.pricing import manual_extra_cents
from ..core.pricing import manual_extra_cents, treatment_cents
from ..core.models import FreightAsk, FreightEstimate
from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, delivery_services, freight, payment,
require_delivery_available, storage)
@@ -43,6 +43,7 @@ def session(request: Request, response: Response):
'password_recovery': mail.configured(),
# Per metre on a finished sheet someone opens by hand (app/core/pricing.py).
'manual_extra_cents': manual_extra_cents(),
'treatment_cents': treatment_cents(),
# Public by design: Mercado Pago's card form needs it in the browser.
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
# The delivery options the cart quotes, or none: pickup only.

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

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

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,7 @@
"""Quotes: the customer's cart, approved at once when it can be (app/quote_review.py)."""
import hashlib
import json
from datetime import datetime, timezone
from decimal import Decimal
from uuid import UUID, uuid4
@@ -13,7 +14,7 @@ from ..core.auth import owner
from ..core.models import QuoteRequest
from ..core.pricing import price
from .. import quote_review
from ..grade_check import Files, mismatch
from ..grade_check import Files, mismatch, resolution_issue, source_dpi
from ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
from ..scanning import require_clean
@@ -27,6 +28,12 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
require_delivery_available(body.freight.service)
draft = body.model_dump(mode='json', exclude={'request_key'})
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
accepted_at = datetime.now(timezone.utc).isoformat()
for item in draft['items']:
if item.get('residue_accepted'):
item['residue_accepted_at'] = accepted_at
if item.get('stroke_choice'):
item['stroke_choice_at'] = accepted_at
reason = quote_review.review_reason(draft)
if reason is not None:
# Waits for review: check the delivery now, priced at approval.
@@ -51,7 +58,21 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
# The grade came from the browser and is shown with the order (it no
# longer sets the price): before a cart is approved at checkout, the
# server works it out from the files.
note = mismatch(Files(storage), draft['items'], rows) if reason is None else None
files = Files(storage)
# Record the lowest source resolution for the Prumo report (front 6).
for draft_item, item in zip(draft['items'], body.items):
dpis = []
for source in item.production.sources:
row = rows.get(str(source.upload_id))
dpi = source_dpi(files, row, source.model_dump(mode='json')) if row else None
if dpi:
dpis.append(dpi)
if dpis:
draft_item['source_dpi'] = round(min(dpis))
issue = resolution_issue(files, draft['items'], rows)
if issue:
raise HTTPException(422, issue)
note = mismatch(files, draft['items'], rows) if reason is None else None
reason = reason or note
uid = uuid4()
c.execute('INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,review_note) VALUES(%s,%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING',

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

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

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

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

View File

@@ -41,9 +41,9 @@ def begin_upload(body: UploadStart, session_id=Depends(owner)):
audit('upload_quota_rejected')
raise HTTPException(429, 'Limite de armazenamento ou de envios pendentes atingido. Tente de novo mais tarde.')
multipart = storage.begin(key)
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,expires_at)
VALUES(%s,%s,%s,%s,%s,%s,now()+interval '1 hour')''',
(uid, session_id, body.name, body.size, key, multipart))
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,original_name,size,object_key,multipart_id,expires_at)
VALUES(%s,%s,%s,%s,%s,%s,%s,now()+interval '1 hour')''',
(uid, session_id, body.name, body.name, body.size, key, multipart))
return {'id': uid, 'part_bytes': PART_BYTES}
@router.get('/api/uploads/{uid}')

View File

@@ -129,7 +129,10 @@ def change_password(body: PasswordChange, request: Request):
def user_rows(c):
"""Every account, with the machines its open sessions are on now (item 12)."""
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at,
COALESCE(array_agg(DISTINCT s.machine_id) FILTER (WHERE s.machine_id IS NOT NULL), '{}') AS machines
COALESCE(array_agg(DISTINCT s.machine_id) FILTER (WHERE s.machine_id IS NOT NULL), '{}') AS machines,
-- The last use of any open session: "Ativo agora" in Usuários.
(SELECT max(x.seen_at) FROM dtf_local.operator_sessions x
WHERE x.username=o.email AND x.expires_at>now()) AS seen_at
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_sessions s
ON s.username=o.email AND s.expires_at>now() AND s.machine_id IS NOT NULL
GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()
@@ -228,7 +231,6 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
raise HTTPException(409, 'Já existe uma máquina com este nome.')
c.execute('INSERT INTO dtf_local.machines(id,name,products,active,limit_metres) VALUES(%s,%s,%s,%s,%s)',
(mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres))
machines.route(c)
audit('machine_created', operator=user, machine=body.name)
return {'id': str(mid)}
@@ -245,20 +247,21 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
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)
return {'ok': True}
@router.post('/api/operator/machines/{mid}/delete')
def delete_machine(mid: UUID, user=Depends(can('users'))):
"""Its orders go back to the automatic choice; its operators lose it."""
"""Its orders lose that machine; its operators lose the session choice."""
with db.connect() as c:
if c.execute("SELECT 1 FROM dtf_local.orders WHERE machine_id=%s AND state='imp' AND cancelled_at IS NULL LIMIT 1",
(mid,)).fetchone():
raise HTTPException(409, 'Há pedido imprimindo nesta máquina. Termine ou mova o pedido antes de excluí-la.')
release_sessions(c, mid)
row = c.execute('DELETE FROM dtf_local.machines WHERE id=%s RETURNING name', (mid,)).fetchone()
if not row:
raise HTTPException(404, 'Máquina não encontrada.')
machines.route(c)
audit('machine_deleted', operator=user, machine=row['name'])
return {'ok': True}

View File

@@ -13,7 +13,7 @@ from starlette.middleware.trustedhost import TrustedHostMiddleware
from .core import db
from .core.auth import audit, client_ip
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage
from .api import artwork, customer, health, operator, orders, payments, quotes, uploads, users
from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_videos, uploads, users
@asynccontextmanager
@@ -45,5 +45,5 @@ async def safe_headers(request, call_next):
# Order is not significant: no two routers declare the same path.
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users):
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, reviews, machine_log):
app.include_router(module.router)

View File

@@ -9,7 +9,8 @@ from uuid import UUID, uuid4
from fastapi import HTTPException
from .runtime import upload_row
from .runtime import upload_row, storage
from .printpng_validate import require_final_png
from .scanning import require_clean
@@ -20,8 +21,9 @@ def generated_owner(c, order, ref, kind):
from, and only while that item still has its original artwork: after a
customer correction it reproduces a layout nobody wants printed.
"""
generated = c.execute('''SELECT item_index FROM dtf_local.print_files
WHERE order_id=%s AND upload_id=%s AND status='ready' ''', (order['id'], ref.upload_id)).fetchone()
generated = c.execute('''SELECT p.item_index FROM dtf_local.print_parts p JOIN dtf_local.print_files f
ON f.order_id=p.order_id AND f.item_index=p.item_index
WHERE p.order_id=%s AND p.upload_id=%s AND f.status='ready' ''', (order['id'], ref.upload_id)).fetchone()
if not generated:
return None
if kind != 'final' or generated['item_index'] != ref.item_index:
@@ -29,7 +31,6 @@ def generated_owner(c, order, ref, kind):
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1",
(order['id'],)).fetchone():
raise HTTPException(409, 'O cliente enviou uma correção depois que este arquivo foi gerado. Use a correção ou envie outro arquivo.')
# A large sheet's print file is its original, owned by the customer.
return c.execute('SELECT owner FROM dtf_local.uploads WHERE id=%s', (ref.upload_id,)).fetchone()['owner']
@@ -84,6 +85,8 @@ def submit_files(c, order, body, identity, kind, actor):
if not upload['complete']:
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar.')
require_clean(upload)
if kind == 'final':
require_final_png(storage, upload)
# Attached once, except a correction approved as its own final.
if c.execute('SELECT id FROM dtf_local.order_files WHERE upload_id=%s'+(" AND kind<>'correction'" if corrected else ''),
(ref.upload_id,)).fetchone():

View File

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

View File

@@ -114,8 +114,11 @@ def login_failed(email):
"""Count a failed sign-in (or registration attempt) against the account."""
rate_limit('auth-account', email, 1_000_000)
# What each Kanban profile may do. "view" is reading; "produce" moves cards and
# handles artwork; "print" is the print room's side of it (the machine, the
# What each Kanban profile may do. "view" is reading; "produce" handles the
# artwork: approving the final files, the contraction, "Tratar a arte", the
# contact wait. "The designer approves every file" (Dropstar's rule D-16), so
# the operator does not: they pull and print. "print" is the print room's side
# of it (the machine, the
# queue's order, its files and folder); "manage" covers quotes, cancellations
# and payments; "users" is the Usuários page; "integrations" is everything in
# Integrações but the print room's folder (connecting Tiny, the checks, the
@@ -125,7 +128,7 @@ def login_failed(email):
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro')
CAPABILITIES = {
'view': set(ROLES),
'produce': {'superadmin', 'admin', 'gestao', 'designer', 'operador'},
'produce': {'superadmin', 'admin', 'gestao', 'designer'},
'print': {'superadmin', 'admin', 'gestao', 'operador'},
'manage': {'superadmin', 'admin', 'gestao'},
# Registering an order paid outside the system, from its Site quote (D-35).
@@ -142,10 +145,16 @@ CAPABILITIES = {
# file. Resolving a payment stays with "manage".
'payments': {'superadmin', 'admin', 'gestao', 'financeiro'},
'cancel': {'superadmin', 'admin', 'gestao', 'financeiro'},
# Prova OK or reprovada, on the proof card only (Dropstar, 2026-11-03): the
# seller, who otherwise only views, Gestão and the administrators.
'proof': {'superadmin', 'admin', 'gestao', 'vendedor'},
# "Retirado" at the counter (Dropstar's third round, item 14): everyone
# but the seller, who only views (D-30). It includes everyone who produces,
# so an operator upload (artwork.py) takes it for its parts.
# and the operator, so an operator upload (artwork.py) takes it for its parts.
'deliver': {'superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor'},
# The photo or video of the printed sheet in Revisão (Fase 2, front 2): who
# releases to Finalizado, and Gestão, which may stand in for them.
'inspect': {'superadmin', 'admin', 'gestao', 'revisor'},
}
# Who moves which card (Dropstar's flow, 2026-10-23, and their rules of
@@ -203,6 +212,11 @@ def signed_in(request: Request):
JOIN dtf_local.operators o ON o.email=s.username AND o.active
LEFT JOIN dtf_local.machines m ON m.id=s.machine_id
WHERE s.token_hash=%s AND s.expires_at>now()''', (digest,)).fetchone()
if row:
# When the session was last used, for "Ativo agora" in Usuários:
# written at most once a minute, not on every request.
c.execute('''UPDATE dtf_local.operator_sessions SET seen_at=now()
WHERE token_hash=%s AND (seen_at IS NULL OR seen_at<now()-interval '1 minute')''', (digest,))
if not row:
raise HTTPException(401, 'Sua sessão expirou. Entre de novo.')
# The machine this session works on (item 12), or None.

View File

@@ -1,4 +1,5 @@
import re
from datetime import date
from decimal import Decimal
from typing import Literal
from uuid import UUID
@@ -150,6 +151,28 @@ class ProductionSpec(StrictModel):
sources: list[ProductionSource] = Field(min_length=1, max_length=20)
placements: list[ProductionPlacement] = Field(min_length=1, max_length=4000)
class Split(StrictModel):
"""One sheet of loose art the Site split by contraction class (item 17,
Dropstar 2026-10-30): fine lines (C1, C2) on one sheet, thick (C3) on
another, each its own item and print file, billed together."""
group: str = Field(pattern=r'^[a-z0-9]{1,16}$')
part: int = Field(ge=1, le=10, strict=True)
of: int = Field(ge=2, le=10, strict=True)
def check_splits(items):
"""Every split group has each of its parts once, of one product."""
groups = {}
for item in items:
if item.split:
groups.setdefault(item.split.group, []).append(item)
for parts in groups.values():
of = parts[0].split.of
if sorted(item.split.part for item in parts) != list(range(1, of + 1)) or \
any(item.split.of != of or item.mode != parts[0].mode for item in parts):
raise ValueError('Split sheets must list each part once, of one product')
class Item(StrictModel):
mode: Literal['file','avulsa','uvfile','uv']
metres: Decimal = Field(gt=0, le=12000)
@@ -161,9 +184,25 @@ class Item(StrictModel):
# Residue dots under 2 mm the customer accepted printing on a ready sheet,
# rather than erasing them (Dropstar, 2026-10-29): 0 when none.
residue_accepted: int = Field(default=0, ge=0, le=1000000, strict=True)
# The thinnest stroke the browser measured, in pixels at 300 DPI, and its
# contraction class (Dropstar, 2026-10-30): up to 4 C1, 5 to 19 C2, 20+ C3.
stroke_px: int | None = Field(default=None, ge=1, le=10000, strict=True)
stroke_class: Literal['C1', 'C2', 'C3'] | None = None
# A sheet with fine lines and solid areas (item 16): the customer kept the
# measure (protect the fine lines) or chose to protect the solid areas (C3).
stroke_choice: Literal['measured', 'client_c3'] | None = None
# Where the thinnest stroke sits in the assembled film, from 0 (top) to 1
# (bottom): the proof card crops a 15 cm window around it (Dropstar, 05/11).
proof_y_fraction: Decimal | None = Field(default=None, ge=0, le=1)
# The lowest source resolution the server measured, for the Prumo report
# (Dropstar, 05/11). None when the format cannot be measured.
source_dpi: int | None = Field(default=None, ge=0, le=1000000)
split: Split | None = None
@model_validator(mode='after')
def production_matches_uploads(self):
if self.split and (self.mode not in ('avulsa', 'uv') or self.split.part > self.split.of):
raise ValueError('Only loose artwork is split into sheets')
if [source.upload_id for source in self.production.sources] != self.uploads:
raise ValueError('Production sources must match uploaded files in order')
is_sheet = self.mode in ('file', 'uvfile')
@@ -205,6 +244,19 @@ class Item(StrictModel):
raise ValueError('Resolution warning must be acknowledged')
return self
class ClientTimings(StrictModel):
"""What the browser measured on the way to a quote (item 0.12).
They are only numbers for Números; a cart may send none of them, and the
server never uses them to price or accept an order.
"""
page_ms: int | None = Field(default=None, ge=0, le=600000)
upload_ms: int | None = Field(default=None, ge=0, le=3600000)
upload_bytes: int | None = Field(default=None, ge=0, le=10**12)
analysis_ms: int | None = Field(default=None, ge=0, le=3600000)
montage_ms: int | None = Field(default=None, ge=0, le=3600000)
class QuoteRequest(StrictModel):
request_key: UUID
customer: Customer
@@ -213,6 +265,15 @@ class QuoteRequest(StrictModel):
destination: Destination | None = None
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
proof: bool = False
# "Quero o tratamento pelo designer": a fixed service line, when priced (front 5).
treatment: bool = False
# What the browser measured while the customer built the cart (item 0.12).
timings: ClientTimings | None = None
@model_validator(mode='after')
def splits_complete(self):
check_splits(self.items)
return self
@model_validator(mode='after')
def destination_matches_freight(self):
@@ -228,6 +289,11 @@ class QuoteRequest(StrictModel):
class Review(StrictModel):
items: list[Item] = Field(min_length=1, max_length=30)
@model_validator(mode='after')
def splits_complete(self):
check_splits(self.items)
return self
class Pay(StrictModel):
quote_id: UUID
@@ -264,6 +330,32 @@ class Move(StrictModel):
state: Literal['rec','tra','imp','cor','rev','fin']
version: int = Field(ge=0)
reason: str = Field(default='', max_length=1000)
# Pulled into Imprimindo onto a machine's lane: the machine it prints on.
machine_id: UUID | None = None
class MachineEntry(StrictModel):
"""One thing entered into a machine (Fase 2, front 1a, app/machine_log.py)."""
kind: Literal['supply', 'part', 'event']
item: str = Field(min_length=1, max_length=40)
quantity: Decimal | None = Field(default=None, gt=0, le=999999, decimal_places=3)
cost_cents: int | None = Field(default=None, ge=0, le=10**12, strict=True)
serial: str | None = Field(default=None, max_length=200)
note: str | None = Field(default=None, max_length=1000)
stop_minutes: int | None = Field(default=None, gt=0, le=100000, strict=True)
from_alert: bool = False
class MachineSheet(StrictModel):
"""The machine's own data, typed by Gestão: cost, start and supply minimums."""
price_cents: int | None = Field(default=None, ge=0, le=10**12, strict=True)
installed_on: date | None = None
minimums: dict[str, Decimal | None] = Field(default_factory=dict)
class Contraction(StrictModel):
item_index: int = Field(ge=0, le=100)
# None returns the item to the class the browser measured.
value: Literal['C1', 'C2', 'C3'] | None = None
class Resolution(StrictModel):
note: str = Field(min_length=3, max_length=1000)

View File

@@ -24,6 +24,18 @@ def manual_extra_cents() -> int:
return value
def treatment_cents() -> int:
"""The designer's treatment, a fixed amount per order (front 5).
Zero keeps the option hidden: the price is the client's decision, and the
server and the Site read the same `TREATMENT_CENTS`.
"""
value = int(os.environ.get('TREATMENT_CENTS', '0') or 0)
if not 0 <= value <= 1000000:
raise ValueError('TREATMENT_CENTS must be between 0 and 1000000')
return value
def is_manual(item, names) -> bool:
"""Whether a finished-sheet item has a file someone must open by hand: one
the customer measured, or one in a format the Site cannot read."""
@@ -32,15 +44,16 @@ def is_manual(item, names) -> bool:
for source in item['production']['sources'])
def price(mode: str, metres: str, grade: int, extra_cents: int = 0) -> dict:
def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Decimal = Decimal('1')) -> dict:
"""The item's charge. The grade is validated and kept with the item; the
price does not depend on it."""
price does not depend on it. A split sheet has no minimum of its own: its
group has one (bill_splits)."""
length = Decimal(str(metres))
if mode not in PRICES or not length.is_finite() or not 0 < length <= 12000:
raise ValueError('Invalid product or length')
if isinstance(grade, bool) or not isinstance(grade, int) or not 0 <= grade <= 100:
raise ValueError('Grade must be an integer between 0 and 100')
billed = max(Decimal('1'), (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10)
billed = max(minimum, (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10)
if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
raise ValueError('Invalid extra charge')
unit = PRICES[mode] + extra_cents
@@ -50,3 +63,22 @@ def price(mode: str, metres: str, grade: int, extra_cents: int = 0) -> dict:
if extra_cents:
priced['manual_extra_cents'] = extra_cents
return priced
def bill_splits(priced: list) -> list:
"""The order minimum of 1 m once per split group, on its first sheet: the
customer did not choose the split (item 17), so it never costs a metre more."""
for group in dict.fromkeys(i['split']['group'] for i in priced if i.get('split')):
parts = [i for i in priced if (i.get('split') or {}).get('group') == group]
short = Decimal('1') - sum(Decimal(i['billed_metres']) for i in parts)
if short > 0:
first = min(parts, key=lambda i: i['split']['part'])
billed = Decimal(first['billed_metres']) + short
first.update(billed_metres=str(billed), total_cents=int(billed * first['unit_cents']))
return priced
def sheet_label(item: dict) -> str:
"""' · folha 1 de 2' on a split sheet (item 17), for the customer's lists."""
split = item.get('split')
return f" · folha {split['part']} de {split['of']}" if split else ''

View File

@@ -23,7 +23,9 @@ import os
import struct
import tempfile
DPI_IDEAL = 300
DPI_IDEAL = 200
DPI_REFUSE = 96
PDF_VECTOR_DPI = 300
# The Site analyses PDFs up to 150 MB (GRANDE_BYTES); above that it does not
# grade them, so neither does this.
PDF_MAX_BYTES = 150 * 1048576
@@ -123,7 +125,7 @@ def pdf_dpi(path):
return None
found = [(dpi, area) for dpi, area in found if dpi > 0]
if not found:
return DPI_IDEAL
return PDF_VECTOR_DPI
total = sum(area for _, area in found) or 1
return js_round(sum(dpi * area for dpi, area in found) / total)
@@ -133,18 +135,29 @@ class Files:
def __init__(self, storage):
self.storage = storage
# A PDF is read once per quote: source_dpi, resolution_issue and
# mismatch all ask for the same files.
self._heads = {}
self._dpis = {}
def head(self, row):
return self.storage.client.get_object(Bucket=self.storage.bucket, Key=row['object_key'],
Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read()
key = row['object_key']
if key not in self._heads:
self._heads[key] = self.storage.client.get_object(
Bucket=self.storage.bucket, Key=key, Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read()
return self._heads[key]
def pdf_dpi(self, row):
if row['size'] > PDF_MAX_BYTES:
return None
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
self.storage.client.download_fileobj(self.storage.bucket, row['object_key'], handle)
handle.flush()
return pdf_dpi(handle.name)
key = row['object_key']
if key not in self._dpis:
if row['size'] > PDF_MAX_BYTES:
self._dpis[key] = None
else:
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
self.storage.client.download_fileobj(self.storage.bucket, key, handle)
handle.flush()
self._dpis[key] = pdf_dpi(handle.name)
return self._dpis[key]
def source_dpi(files, row, source):
@@ -178,6 +191,31 @@ def item_grade(files, item, rows):
return js_round(sum(grade_of(d) for d in dpis) / len(dpis))
def resolution_issue(files, items, rows):
"""Refuse sub-96 DPI and require recorded consent for measurable 96–199 DPI.
Unknown formats remain for manual review; they cannot be treated as a
measured zero DPI or silently called high-resolution artwork.
"""
for index, item in enumerate(items, 1):
dpis = []
for source in item['production']['sources']:
row = rows.get(str(source['upload_id']))
dpi = source_dpi(files, row, source) if row else None
if dpi is None:
dpis = []
break
dpis.append(dpi)
if not dpis:
continue
lowest = min(dpis)
if lowest < DPI_REFUSE:
return f'Item {index}: resolução de {js_round(lowest)} DPI abaixo do mínimo de {DPI_REFUSE} DPI.'
if lowest < DPI_IDEAL and (item['quality_status'] != 'warning' or not item['quality_acknowledged']):
return f'Item {index}: confirme a ressalva de resolução entre {DPI_REFUSE} e {DPI_IDEAL - 1} DPI.'
return None
def mismatch(files, items, rows):
"""Why a cart's grades cannot be approved at checkout, or None."""
for item in items:

136
app/hotfolder.py Normal file
View File

@@ -0,0 +1,136 @@
"""Each machine's hot folders (Dropstar's third round, item 10, 2026-10-29/30).
FlexiPRINT watches 3. Imprimindo/<máquina>/<C1|C2|C3>/ and takes a file out
of it when it rips. When the operator pulls a card to Imprimindo, its files
go, as a copy, into its machine's folder for the item's contraction class;
the order's own file stays in its stage folder. A film over 15 m is several
parts (item 13): all on the same machine, in order, never more than two in
the folder at once. The third is written when Flexi takes the first.
Only the server knows what each folder should get, and the Kanban's
computers write it: a part is claimed by one computer, so two never write
the same file and Flexi never prints it twice. A claim that did not finish
goes back to the queue. A written part that is gone from its folder was
taken by Flexi, and is never written again. A card that leaves Imprimindo
(Revisão, Correção, a step back, a cancellation) withdraws what Flexi has not
taken yet, and its computer deletes it.
Each part's life is one row of dtf_local.hot_parts:
queued -> claimed -> written -> consumed, or withdraw -> gone.
"""
from datetime import timedelta
# The machines' folders, inside the Kanban's main folder (Dropstar, 2026-10-30).
PRINTING_FOLDER = '3. Imprimindo'
# Two parts at most in a machine's folder (Dropstar, 2026-10-30).
IN_FOLDER = 2
# A computer that claimed a part and never said it was written.
CLAIM_TIMEOUT = timedelta(minutes=10)
CLASSES = ('C1', 'C2', 'C3')
def contraction(order, index):
"""The item's class for the folder: the one chosen in the Kanban, or what
the Site measured (C3 when the customer protected the solid areas)."""
chosen = (order.get('contraction') or {}).get(str(index)) or {}
if chosen.get('class') in CLASSES:
return chosen['class']
item = order['snapshot']['items'][index]
if item.get('stroke_choice') == 'client_c3':
return 'C3'
return item.get('stroke_class') if item.get('stroke_class') in CLASSES else None
def start(c, order_id):
"""The order entered Imprimindo: its approved finals queue for its
machine's folder, item by item, part by part."""
files = c.execute('''SELECT f.item_index, f.upload_id, u.name FROM dtf_local.order_files f
JOIN dtf_local.uploads u ON u.id=f.upload_id
WHERE f.order_id=%s AND f.kind='final' AND f.active ORDER BY f.item_index, u.name''', (order_id,)).fetchall()
round_ = c.execute('SELECT COALESCE(max(round), 0) + 1 AS r FROM dtf_local.hot_parts WHERE order_id=%s',
(order_id,)).fetchone()['r']
for seq, row in enumerate(files, 1):
c.execute('''INSERT INTO dtf_local.hot_parts(order_id,round,seq,item_index,upload_id,name)
VALUES(%s,%s,%s,%s,%s,%s)''', (order_id, round_, seq, row['item_index'], row['upload_id'], row['name']))
def stop(c, order_id):
"""The order left Imprimindo or was cancelled: what is not written stays
unwritten, and what Flexi has not taken is withdrawn from the folder."""
c.execute('''UPDATE dtf_local.hot_parts SET state=CASE WHEN state IN ('claimed','written') THEN 'withdraw' ELSE 'gone' END,
done_at=CASE WHEN state IN ('claimed','written') THEN NULL ELSE now() END
WHERE order_id=%s AND state IN ('queued','claimed','written')''', (order_id,))
def claim(c, user):
"""The parts due in the folders now, claimed for this computer to write:
for each machine, the next parts of its orders in Imprimindo, in the order
they entered it, until the machine has two in its folder."""
c.execute('''UPDATE dtf_local.hot_parts SET state='queued', claimed_at=NULL, claimed_by=NULL
WHERE state='claimed' AND claimed_at < now() - %s''', (CLAIM_TIMEOUT,))
rows = c.execute('''SELECT h.*, o.machine_id, o.contraction, o.snapshot, m.name AS machine_name,
(SELECT max(v.id) FROM dtf_local.movements v WHERE v.order_id=o.id AND v.to_state='imp') AS entered
FROM dtf_local.hot_parts h JOIN dtf_local.orders o ON o.id=h.order_id
JOIN dtf_local.machines m ON m.id=o.machine_id
WHERE h.state IN ('queued','claimed','written') AND o.state='imp' AND o.cancelled_at IS NULL
ORDER BY m.name, entered, h.order_id, h.seq FOR UPDATE OF h''').fetchall()
due, busy, blocked = [], {}, set()
for row in rows:
machine = row['machine_id']
if row['state'] != 'queued':
busy[machine] = busy.get(machine, 0) + 1
for row in rows:
machine, order = row['machine_id'], row['order_id']
if row['state'] != 'queued' or order in blocked:
continue
cls = contraction(row, row['item_index'])
# A part without its class waits, and the parts after it with it.
if busy.get(machine, 0) >= IN_FOLDER or not cls:
blocked.add(order)
continue
folder = f"{row['machine_name']}/{cls}"
c.execute('''UPDATE dtf_local.hot_parts SET state='claimed', claimed_at=now(), claimed_by=%s, folder=%s
WHERE id=%s''', (user, folder, row['id']))
busy[machine] = busy.get(machine, 0) + 1
due.append({**row, 'folder': folder})
return due
def watched(c):
"""The parts written and not yet taken by Flexi, and those to delete."""
return c.execute('''SELECT id, order_id, name, folder, state FROM dtf_local.hot_parts
WHERE state IN ('written','withdraw') AND folder IS NOT NULL ORDER BY id''').fetchall()
# What a computer reports about a part, and from which states it may.
REPORTS = {'written': ('claimed',), 'released': ('claimed',), 'consumed': ('written',), 'gone': ('withdraw',)}
def report(c, part_id, what, user):
"""A computer wrote the part, could not, saw Flexi take it, or deleted a
withdrawn one. Returns whether the report applied."""
if what == 'written':
sql = '''UPDATE dtf_local.hot_parts SET state='written', written_at=now() WHERE id=%s AND state='claimed'
AND claimed_by=%s RETURNING id'''
return bool(c.execute(sql, (part_id, user)).fetchone())
if what == 'released':
sql = '''UPDATE dtf_local.hot_parts SET state='queued', claimed_at=NULL, claimed_by=NULL, folder=NULL
WHERE id=%s AND state='claimed' AND claimed_by=%s RETURNING id'''
return bool(c.execute(sql, (part_id, user)).fetchone())
new = {'consumed': 'consumed', 'gone': 'gone'}[what]
return bool(c.execute(f'''UPDATE dtf_local.hot_parts SET state='{new}', done_at=now() WHERE id=%s
AND state=ANY(%s) RETURNING id''', (part_id, list(REPORTS[what]))).fetchone())
def progress(c, order_ids):
"""For each order in parts, where its film is (Dropstar, 2026-10-30):
"parte 3/7 imprimindo · 4/7 ripando". Flexi rips the part it took last
while the one before it prints."""
rows = c.execute('''SELECT h.order_id, count(*) AS parts,
max(h.seq) FILTER (WHERE h.state='consumed') AS taken,
count(*) FILTER (WHERE h.state IN ('claimed','written')) AS waiting
FROM dtf_local.hot_parts h
WHERE h.order_id=ANY(%s) AND h.round=(SELECT max(round) FROM dtf_local.hot_parts x WHERE x.order_id=h.order_id)
GROUP BY h.order_id''', (order_ids,)).fetchall()
return {row['order_id']: {'parts': row['parts'], 'taken': row['taken'] or 0, 'waiting': row['waiting']}
for row in rows}

250
app/machine_log.py Normal file
View File

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

281
app/machine_stats.py Normal file
View File

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

View File

@@ -1,20 +1,10 @@
"""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.
"""
"""The print machines, their load and the two printing places on each one."""
from decimal import Decimal
from . import machine_log
# Not finished: the work still ahead of a machine.
OPEN = ('rec', 'tra', 'imp', 'cor')
# 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.
@@ -44,49 +34,6 @@ def loads(c):
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
@@ -107,7 +54,8 @@ def rows(c, with_operators=False):
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']}
'open_metres': float(used['metres']), 'open_orders': used['orders'], 'states': used['states'],
'alerts': machine_log.alerts(c, m['id'])}
if with_operators:
row['operators'] = operators.get(key, [])
result.append(row)

View File

@@ -23,6 +23,8 @@ import ssl
from email.message import EmailMessage
from email.utils import formataddr, formatdate, make_msgid, parseaddr
from .core.pricing import sheet_label
ADAPTER = os.environ.get('MAIL_ADAPTER', 'off')
RESET_MINUTES = 60
CODE_MINUTES = 15
@@ -70,7 +72,7 @@ def order_paid(c, order, origin):
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'))} · "
rows = [('Itens', '\n'.join(f"{PRODUCTS.get(i.get('mode'), i.get('mode'))}{sheet_label(i)} · "
f"{str(i.get('billed_metres') or i.get('metres')).replace('.', ',')} m"
for i in snapshot.get('items', []))),
('Entrega', delivery),
@@ -90,6 +92,29 @@ PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · ar
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
def quote_expired(c, quote, origin):
"""The customer's notice that an approved, unpaid order expired after 24 h
(Fase 2, front 9): its files were deleted and they can send it again on
the Site. Returns whether it was queued (False without an e-mail)."""
customer = (quote.get('draft') or {}).get('customer') or {}
if not customer.get('mail'):
return False
from . import mail_html
link = f'{origin}/'
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
'Seu pedido não foi pago em 24 horas e expirou. Os arquivos que você enviou foram apagados.', '',
f'Quando quiser, é só montar de novo no site: {link}'])
html = mail_html.layout('Seu pedido não foi pago em 24 horas e expirou.', 'Seu pedido', [
mail_html.pill('Pedido expirado', 'info'),
mail_html.title('Seu pedido expirou'),
mail_html.para(f'{mail_html.greeting(customer.get("name"))} Seu pedido não foi pago em 24 horas e '
'expirou. Os arquivos que você enviou foram apagados.'),
mail_html.button('Montar de novo', link),
mail_html.small(f'Quando quiser, é só montar de novo no site: {link}'),
])
return queue(c, 'notice', customer['mail'], 'Seu pedido expirou · DTF Dropstar', text, html)
def money(cents):
whole, cents = divmod(int(cents), 100)
return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}'

View File

@@ -16,7 +16,7 @@ from uuid import UUID, uuid4
from psycopg.types.json import Jsonb
from . import machines, mail, proof
from . import mail, proof
from .core.auth import audit
from .core.models import PRODUCTION_VERSIONS
from .printjobs import queue as queue_print_files
@@ -63,9 +63,10 @@ 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)
"""Whether the order goes to Tiny: every order but a test or a proof card
(app/proof.py), which is no sale. A Dropflow order goes in its own revenue
category (app/tiny.py, CATEGORIES)."""
return not is_test(order) and not order.get('parent_id')
# How long a file is kept while nothing has been paid for it. A cart's files
@@ -88,6 +89,29 @@ def hold_uploads(c, upload_ids, interval):
WHERE id=ANY(%s) AND purged_at IS NULL''', (interval, [str(u) for u in upload_ids]))
def release_files(c, uploads):
"""Expire these uploads now, except any another order or an open quote
still uses: a customer can buy the same file again. Returns how many."""
free = []
for upload in uploads:
used = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.print_files WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.print_parts WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i
WHERE i->'uploads' ? %s
UNION ALL SELECT 1 FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i
WHERE q.discarded_at IS NULL AND q.expired_at IS NULL
AND NOT EXISTS (SELECT 1 FROM dtf_local.orders x WHERE x.quote_id=q.id)
AND i->'uploads' ? %s
LIMIT 1''', (upload,) * 5).fetchone()
if not used:
free.append(upload)
if free:
c.execute('''UPDATE dtf_local.uploads SET expires_at=now() WHERE id=ANY(%s::uuid[])
AND purged_at IS NULL''', (free,))
return len(free)
def create_order(c, quote, payment, origin):
"""Create the order for a reviewed quote, or return the one already there.
`origin` is where it came from (D-21): each way in names its own.
@@ -118,7 +142,8 @@ def create_order(c, quote, payment, origin):
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)
# An order with a proof gets its proof card (app/proof.py).
proof.create_child(c, order)
if is_test(order):
return order, True
mail.order_paid(c, order, PUBLIC_ORIGIN)

View File

@@ -380,13 +380,14 @@ def open_source(path, name):
return SourceImage(path, name)
def check_layout(item, sizes, vector=()):
def check_layout(item, sizes, vector=(), proof=False):
"""Refuse a layout the file cannot reproduce faithfully. Returns the lowest
DPI of the raster sources (vector pages have none)."""
DPI of the raster sources (vector pages have none). A proof is free of
charge, so its zero billed metres must not reject the item's full sheet."""
production = item['production']
height = Decimal(str(production['height_cm']))
billed = Decimal(str(item['billed_metres'])) * 100
if height > billed + HEIGHT_TOLERANCE_CM:
if not proof and height > billed + HEIGHT_TOLERANCE_CM:
raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados')
lowest = None
for placement in production['placements']:

View File

@@ -5,65 +5,141 @@ claim, and renders outside any transaction, so a long render never holds a row
lock or a database connection. A claim older than CLAIM_TIMEOUT is assumed to
belong to a worker that died and is taken again.
The result is an ordinary upload row owned by an identity derived from the
order, already marked clean: its only inputs are artwork that passed the
malware scan, and the bytes are written here. The operator still decides
whether it becomes the final file; generation never approves anything.
The result is a 300 DPI PNG (item 13, app/printpng.py), or its parts for a
film over 15 m: ordinary upload rows owned by an identity derived from the
order, already marked clean, since their only inputs are artwork that passed
the malware scan and the bytes are written here. dtf_local.print_parts lists
them in order. The operator still decides whether they become the final
file; generation never approves anything.
Sheets of several GB are the normal order, and decoding one would take more
memory than the worker has. A source above LARGE_SOURCE_BYTES is never
opened: a finished sheet placed whole on the film is already its own print
file, so the original becomes the print file; any other layout is prepared
by hand from the original.
Sheets of several GB are the normal order: a PNG or a PDF is read band by
band, so its size does not matter. Any other file above LARGE_SOURCE_BYTES
is prepared by hand from the original.
"""
import io
import logging
import multiprocessing
import os
import shutil
import tempfile
import time
from queue import Empty
from datetime import timedelta
from decimal import Decimal
from zoneinfo import ZoneInfo
from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
from psycopg.types.json import Jsonb
from PIL import Image
from .core.auth import audit
from .core.db import connect
from .printfile import Unsupported, render
from .printfile import Unsupported
from .printpng import render
from .proof import PROOF_SHEET_CM
from .tiny import purchase_order
LOCAL = ZoneInfo('America/Sao_Paulo')
CLAIM_TIMEOUT = timedelta(minutes=15)
# A 15 m part takes minutes to write; a long film, several parts.
RENDER_SECONDS = int(os.environ.get('PRINT_RENDER_TIMEOUT_SECONDS', '900'))
CLAIM_TIMEOUT = timedelta(minutes=18)
MAX_ATTEMPTS = 3
LARGE_SOURCE_BYTES = int(os.environ.get('PRINT_DECODE_MAX_BYTES', str(300 * 1024 * 1024)))
# Formats the operator can import as they are.
PRINTABLE_ORIGINAL = ('.png', '.jpg', '.jpeg', '.tif', '.tiff', '.pdf')
# Read band by band, whatever their size.
STREAMED = ('.png', '.pdf')
def generated_identity(order_id):
return uuid5(NAMESPACE_URL, f'dtf-print-file:{order_id}')
def proof_part(heights_cm, original_height_cm, fraction):
"""Which part of a split final holds the finest stroke, and where inside it.
`heights_cm` are the parts' heights in order, `fraction` the stroke's
position on the original film (0 at the top, 1 at the bottom). A single
part returns the same fraction, as before.
"""
heights = [float(height) for height in heights_cm]
if not heights:
return 0, 0.0
position = min(1.0, max(0.0, float(fraction or 0))) * float(original_height_cm)
start = 0.0
for index, height in enumerate(heights):
end = start + height
if position <= end or index == len(heights) - 1:
inside = (position - start) / height if height > 0 else 0.0
return index, min(1.0, max(0.0, inside))
start = end
return len(heights) - 1, 1.0
def png_height_cm(storage, row):
"""A PNG's height in cm at 300 DPI, from its header alone (a Range read)."""
head = storage.client.get_object(Bucket=storage.bucket, Key=row['object_key'],
Range='bytes=0-65535')['Body'].read()
with Image.open(io.BytesIO(head)) as image:
height_px = image.size[1]
return float(Decimal(height_px) * Decimal('2.54') / Decimal(300))
def queue(c, order_id, items, only_missing=False):
"""Queue (or re-queue) generation for every item of an order."""
for index in range(items):
if only_missing:
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0,
claimed_at=NULL, finished_at=NULL, detail='{}'
WHERE dtf_local.print_files.status IN ('failed','manual')''',
(uuid4(), order_id, index))
claimed_at=NULL, claim_token=NULL, finished_at=NULL, upload_id=NULL, detail='{}'
WHERE dtf_local.print_files.status IN ('failed','manual') OR
(dtf_local.print_files.status='rendering' AND dtf_local.print_files.claimed_at<now()-%s)''',
(uuid4(), order_id, index, CLAIM_TIMEOUT))
else:
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
ON CONFLICT(order_id,item_index) DO NOTHING''', (uuid4(), order_id, index))
def claim(c):
return c.execute('''SELECT p.*, o.snapshot, o.number, o.created_at AS ordered_at FROM dtf_local.print_files p
return c.execute('''SELECT p.*, o.snapshot, o.number, o.parent_id, o.created_at AS ordered_at FROM dtf_local.print_files p
JOIN dtf_local.orders o ON o.id=p.order_id
WHERE p.status='pending' OR (p.status='rendering' AND p.claimed_at < now()-%s)
ORDER BY p.created_at FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
ORDER BY CASE WHEN o.parent_id IS NOT NULL THEN 0 ELSE 1 END, p.created_at
FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
def _render_child(result_queue, job, item, uploads):
"""Render in a killable process: a stuck image decoder cannot hold a card forever."""
from .adapters import LocalS3Storage
try:
result_queue.put(('ready', produce(LocalS3Storage(), job, item, uploads)))
except Unsupported as reason:
result_queue.put(('manual', str(reason)))
except BaseException as exc:
logging.exception('Print file generation failed')
result_queue.put(('error', type(exc).__name__))
def render_with_timeout(job, item, uploads):
ctx = multiprocessing.get_context('spawn')
result_queue = ctx.Queue()
process = ctx.Process(target=_render_child, args=(result_queue, job, item, uploads))
process.start()
try:
process.join(RENDER_SECONDS)
if process.is_alive():
process.terminate()
process.join(5)
if process.is_alive():
process.kill()
process.join()
return 'timeout', None
try:
return result_queue.get(timeout=5)
except Empty:
return 'error', f'processo encerrou com código {process.exitcode}'
finally:
result_queue.close()
result_queue.join_thread()
def render_one(storage):
@@ -71,75 +147,123 @@ def render_one(storage):
job = claim(c)
if not job:
return False
token = uuid4()
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
attempts=attempts+1 WHERE id=%s''', (job['id'],))
attempts=attempts+1,claim_token=%s WHERE id=%s''', (token, job['id']))
job['claim_token'] = token
item = job['snapshot']['items'][job['item_index']]
source_ids = [UUID(u) for u in item['uploads']]
# A format such as CDR needs a human to prepare the full-size final on
# the parent. The child still generates its own 15 cm proof from that PNG,
# or from the part of it that holds the finest stroke when the film was
# cut into parts (item 13).
if job['parent_id']:
finals = c.execute('''SELECT u.id,u.object_key FROM dtf_local.order_files f
JOIN dtf_local.uploads u ON u.id=f.upload_id
LEFT JOIN dtf_local.print_parts p ON p.order_id=f.order_id
AND p.item_index=f.item_index AND p.upload_id=f.upload_id
WHERE f.order_id=%s AND f.item_index=%s AND f.kind='final' AND f.active
AND u.purged_at IS NULL AND u.expires_at>now()
ORDER BY p.part NULLS LAST, f.created_at''',
(job['parent_id'], item['proof_parent_item_index'])).fetchall()
if finals:
source = finals[0]
if len(finals) > 1:
heights = [png_height_cm(storage, row) for row in finals]
index, fraction = proof_part(heights, item['production']['height_cm'],
item.get('proof_y_fraction'))
source = finals[index]
job['proof_fraction'] = fraction
source_ids = [source['id']]
item = {**item, 'uploads': [str(source['id'])]}
job['proof_fallback'] = True
elif job['snapshot'].get('treatment'):
job['wait_for_treatment'] = True
uploads = c.execute('''SELECT id,name,size,object_key,scan_state,purged_at,expires_at,
(expires_at<=now()) AS expired FROM dtf_local.uploads WHERE id=ANY(%s)''',
([UUID(u) for u in item['uploads']],)).fetchall()
(source_ids,)).fetchall()
# Every generated file shares its order's artwork retention deadline.
expiry = c.execute('SELECT min(created_at)+interval \'30 days\' AS e FROM dtf_local.uploads WHERE id=ANY(%s)',
([UUID(u) for u in item['uploads']],)).fetchone()['e']
(source_ids,)).fetchone()['e']
by_id = {str(row['id']): row for row in uploads}
if any(row['size'] > LARGE_SOURCE_BYTES for row in uploads):
original = whole_sheet(item, by_id)
if original:
with connect() as c:
c.execute('''UPDATE dtf_local.print_files SET status='ready', upload_id=%s, detail=%s,
finished_at=now(), claimed_at=NULL WHERE id=%s''',
(original['id'], Jsonb({'source': 'original', 'name': original['name']}), job['id']))
audit('print_file_original', order=str(job['order_id']), item=job['item_index'])
else:
finish(job, 'manual', {'reason': f'arquivo acima de {LARGE_SOURCE_BYTES // 1048576} MB: '
'monte a folha a partir do original'})
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
if job.get('wait_for_treatment'):
finish(job, 'manual', {'reason': 'Tratamento pago: prepare e aprove o PNG completo no pedido pai para gerar a prova.'})
return True
try:
result = produce(storage, job, item, by_id)
except Unsupported as reason:
finish(job, 'manual', {'reason': str(reason)})
if any(row['size'] > LARGE_SOURCE_BYTES and not row['name'].lower().endswith(STREAMED) for row in uploads):
finish(job, 'manual', {'reason': f'arquivo acima de {LARGE_SOURCE_BYTES // 1048576} MB que não é PNG nem PDF: '
'monte a folha a partir do original'})
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
return True
except Exception as exc:
logging.exception('Print file generation failed')
final = job['attempts'] + 1 >= MAX_ATTEMPTS
finish(job, 'failed' if final else 'pending', {'error': type(exc).__name__})
outcome, result = render_with_timeout(job, item, by_id)
if outcome == 'manual':
finish(job, 'manual', {'reason': result})
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
return True
path, name, size, detail = result
if outcome == 'timeout':
finish(job, 'failed', {'reason': f'Tempo limite de {RENDER_SECONDS // 60} min excedido. Gere de novo.'})
audit('print_file_timeout', order=str(job['order_id']), item=job['item_index'])
return True
if outcome == 'error':
final = job['attempts'] + 1 >= MAX_ATTEMPTS
finish(job, 'failed' if final else 'pending', {'error': result,
'reason': 'A geração falhou. Gere de novo.' if final else ''})
return True
scratch, parts, detail = result
stored = []
try:
uid = uuid4()
key = f'originals/{uid}'
storage.store(key, path, 'application/pdf')
for path, name in parts:
uid = uuid4()
key = f'originals/{uid}'
storage.store(key, path, 'image/png')
stored.append((uid, name, os.path.getsize(path), key))
store_tiles(storage, os.path.join(scratch, 'tiles', name), uid)
except Exception as exc:
# Storage failing is an attempt like any other, not a claim held for an hour.
logging.exception('Storing the print file failed')
finish(job, 'failed' if job['attempts'] + 1 >= MAX_ATTEMPTS else 'pending', {'error': type(exc).__name__})
return True
finally:
os.unlink(path)
shutil.rmtree(scratch, ignore_errors=True)
for part, (uid, _, size, _) in zip(detail['parts'], stored):
part.update(upload_id=str(uid), size=size)
with connect() as c:
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state,scan_reason,scanned_at)
VALUES(%s,%s,%s,%s,%s,'',true,%s,'clean','generated from scanned artwork',now())''',
(uid, generated_identity(job['order_id']), name, size, key, expiry))
current = c.execute('''SELECT 1 FROM dtf_local.print_files WHERE id=%s AND claim_token=%s
AND status='rendering' FOR UPDATE''', (job['id'], job['claim_token'])).fetchone()
if not current:
return True
for uid, name, size, key in stored:
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state,scan_reason,scanned_at)
VALUES(%s,%s,%s,%s,%s,'',true,%s,'clean','generated from scanned artwork',now())''',
(uid, generated_identity(job['order_id']), name, size, key, expiry))
# claimed_at stays: the Prumo report measures generation from the claim.
c.execute('''UPDATE dtf_local.print_files SET status='ready', upload_id=%s, detail=%s,
finished_at=now() WHERE id=%s''', (uid, Jsonb(detail), job['id']))
audit('print_file_ready', order=str(job['order_id']), item=job['item_index'])
finished_at=now(),claim_token=NULL WHERE id=%s''', (stored[0][0], Jsonb(detail), job['id']))
c.execute('DELETE FROM dtf_local.print_parts WHERE order_id=%s AND item_index=%s',
(job['order_id'], job['item_index']))
for number, (uid, _, _, _) in enumerate(stored, 1):
c.execute('INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id) VALUES(%s,%s,%s,%s)',
(job['order_id'], job['item_index'], number, uid))
if job['snapshot'].get('proof_of'):
c.execute('''UPDATE dtf_local.order_files SET active=false
WHERE order_id=%s AND item_index=%s AND kind='final' ''',
(job['order_id'], job['item_index']))
c.execute('''INSERT INTO dtf_local.order_files
(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,%s,'final','Prova gerada automaticamente pelo Prumo','Prumo')''',
(uuid4(), job['order_id'], stored[0][0], job['item_index']))
audit('print_file_ready', order=str(job['order_id']), item=job['item_index'], parts=len(stored))
return True
def whole_sheet(item, uploads):
"""The original, when the item is one finished sheet placed whole, once,
unrotated and unmirrored, across the film: then it is the print file."""
spec = item.get('production') or {}
sources, placements = spec.get('sources') or [], spec.get('placements') or []
if len(item['uploads']) != 1 or len(sources) != 1 or len(placements) != 1:
return None
source, place = sources[0], placements[0]
row = uploads.get(item['uploads'][0])
if (not row or row['scan_state'] != 'clean' or row['purged_at'] or row['expired']
or source.get('kind') != 'sheet' or int(source.get('copies', 1)) != 1
or not row['name'].lower().endswith(PRINTABLE_ORIGINAL)):
return None
if (float(place['x_cm']) != 0 or float(place['y_cm']) != 0 or int(place['rotation_degrees']) != 0
or place['mirrored'] or abs(float(source['width_cm']) - float(spec['film_width_cm'])) > 0.5):
return None
return row
def store_tiles(storage, folder, upload_id):
"""A part's pieces for the Kanban's viewer (item 7), beside the files the
storage policy lets the service write: originals/tiles/<upload>/<level>/<index>.png."""
if not os.path.isdir(folder):
return
for level in sorted(os.listdir(folder)):
for strip in sorted(os.listdir(os.path.join(folder, level))):
storage.store(f'originals/tiles/{upload_id}/{level}/{strip}', os.path.join(folder, level, strip), 'image/png')
def file_prefix(number, item_index):
@@ -156,6 +280,10 @@ def footer(job, item):
count = len(job['snapshot']['items'])
day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y')
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',')
proof_of = job['snapshot'].get('proof_of')
if proof_of:
return ' · '.join(['DROPSTAR', f'PROVA do #{proof_of}',
f'Classe {item.get("stroke_class") or "C3"}', day])
fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}',
f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m']
# A mirrored artwork (UV only) is named on the sheet, for the room to see
@@ -166,37 +294,63 @@ def footer(job, item):
def produce(storage, job, item, uploads):
"""Fetch the item's artwork and render it. Returns (pdf path, name, size, evidence)."""
"""Fetch the item's artwork and render it. Returns (folder, [(png path,
name)], evidence); the caller removes the folder."""
if not (item.get('production') or {}).get('placements'):
raise Unsupported('o item não tem montagem: prepare o arquivo à mão')
for upload_id in item['uploads']:
row = uploads.get(upload_id)
if not row or row['scan_state'] != 'clean':
raise Unsupported('um arquivo original está ausente ou não foi liberado pelo antivírus')
if row['purged_at'] or row['expired']:
raise Unsupported('um arquivo original passou do prazo de guarda')
number = job['number']
name = f'{file_prefix(number, job["item_index"])}.pdf'
with tempfile.TemporaryDirectory(prefix='print-') as scratch:
files = {}
for index, upload_id in enumerate(item['uploads']):
local = os.path.join(scratch, f'source-{index}')
storage.fetch(uploads[upload_id]['object_key'], local)
files[index] = (local, uploads[upload_id]['name'])
handle, output = tempfile.mkstemp(prefix='print-', suffix='.pdf')
try:
with os.fdopen(handle, 'wb') as out:
detail = render(item, files, out, f'Pedido {number} - item {job["item_index"] + 1}',
footer=footer(job, item))
except BaseException:
os.unlink(output)
raise
return output, name, os.path.getsize(output), detail
output = tempfile.mkdtemp(prefix='print-')
try:
with tempfile.TemporaryDirectory(prefix='print-') as scratch:
files = {}
for index, upload_id in enumerate(item['uploads']):
local = os.path.join(scratch, f'source-{index}')
storage.fetch(uploads[upload_id]['object_key'], local)
files[index] = (local, uploads[upload_id]['name'])
if job.get('proof_fallback'):
with Image.open(files[0][0]) as final:
width_px, height_px = final.size
width_cm = float(Decimal(width_px) * Decimal('2.54') / Decimal(300))
height_cm = float(Decimal(height_px) * Decimal('2.54') / Decimal(300))
if job.get('proof_fraction') is not None:
# Already relative to the chosen part (proof_part).
fraction = float(job['proof_fraction'])
else:
original_height = float(item['production']['height_cm'])
fraction = min(1, float(item.get('proof_y_fraction') or 0) * original_height / height_cm)
source = {'kind': 'sheet', 'width_cm': width_cm, 'length_cm': height_cm,
'copies': 1, 'rotation_degrees': 0, 'mirrored': False, 'measurement': 'file'}
item = {**item, 'proof_y_fraction': fraction,
'production': {'version': 3, 'film_width_cm': width_cm,
'height_cm': height_cm, 'sources': [source],
'placements': [{'source_index': 0, 'copy_index': 0,
'x_cm': 0, 'y_cm': 0, 'width_cm': width_cm,
'length_cm': height_cm, 'rotation_degrees': 0,
'mirrored': False}]}}
proof_of = job['snapshot'].get('proof_of')
# The child owns its final file; the class names its proof.
prefix = (f'DTF-{job["number"]}-prova-{item.get("stroke_class") or "C3"}' if proof_of
else file_prefix(job['number'], job['item_index']))
parts, detail = render(item, files, output, prefix, footer=footer(job, item), tiles=True,
limit_cm=PROOF_SHEET_CM if proof_of else None,
proof_fraction=item.get('proof_y_fraction') if proof_of else None)
except BaseException:
shutil.rmtree(output, ignore_errors=True)
raise
return output, parts, detail
def finish(job, status, detail):
with connect() as c:
c.execute('''UPDATE dtf_local.print_files SET status=%s, detail=%s,
finished_at=CASE WHEN %s='pending' THEN NULL ELSE now() END,
claimed_at=NULL WHERE id=%s''', (status, Jsonb(detail), status, job['id']))
claimed_at=NULL,claim_token=NULL WHERE id=%s AND claim_token=%s AND status='rendering' ''',
(status, Jsonb(detail), status, job['id'], job['claim_token']))
def render_loop(storage):

539
app/printpng.py Normal file
View File

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

58
app/printpng_validate.py Normal file
View File

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

102
app/printtiles.py Normal file
View File

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

View File

@@ -1,7 +1,7 @@
"""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
without stopping the order. Dropstar's current rule: up to 15 cm, from
the part with the thinnest lines, a piece of each different artwork, at most
three proofs per order, never billed. On an order above 10 m the customer
may also ask for a proof at checkout (below 10 m there is none, Dropstar
@@ -11,6 +11,10 @@ marks "Prova OK" once the proof is checked, and without it the order does not
reach Finalizado.
"""
from decimal import Decimal
from uuid import NAMESPACE_URL, uuid4, uuid5
from psycopg.types.json import Jsonb
from fastapi import HTTPException
PROOF_ABOVE_METRES = Decimal('10')
CUSTOMER_NOTE = ('O cliente pediu uma prova antes de imprimir: mande a foto da prova pelo WhatsApp '
@@ -24,3 +28,78 @@ def billed_metres(snapshot):
def needs_proof(snapshot):
"""Whether the order prints a proof first: asked for, or above 10 m."""
return bool(snapshot.get('proof')) or billed_metres(snapshot) > PROOF_ABOVE_METRES
# ---- The proof card (Dropstar's third round, 2026-10-30 and 2026-11-03) -----
#
# An order with a proof becomes a parent and a child. The child, the card
# "Prova", is an order of its own (orders.parent_id) with a pre-built proof
# sheet of up to 15 cm per contraction class, and follows the normal flow up
# to Revisão. The parent waits outside the queue, "Aguardando prova". On the
# child, the Vendedor (Gestão and the Administrador too) marks Prova OK, and
# the parent enters the queue; or Prova reprovada, with its reason, and the
# parent goes back to Arte recebida and the child closes. The child is no
# sale: it is not in Tiny, Números, the customer's account or their e-mails.
PROOF_SHEET_CM = Decimal('15')
# Three proofs at most per order, one per item (Dropstar, 2026-10-23).
MAX_PROOFS = 3
PROVIDER = 'prova'
def proof_identity(order_id):
return uuid5(NAMESPACE_URL, f'dtf-proof:{order_id}')
def create_child(c, parent):
"""The parent's proof card, in Arte recebida, its proof sheets queued to be
generated. Returns it, or None when the order needs no proof."""
if parent.get('parent_id') or not needs_proof(parent['snapshot']):
return None
from .printjobs import queue
# A class has one proof. When several items share it, use the one with the
# finest measured line; no metre or product value is sold on this card.
classes = {}
for index, item in enumerate(parent['snapshot']['items']):
kind = item.get('stroke_class') or 'C3'
width = item.get('stroke_px') or 10000
if kind not in classes or width < classes[kind][0]:
classes[kind] = (width, index, item)
selected = [classes[kind] for kind in ('C1', 'C2', 'C3') if kind in classes][:MAX_PROOFS]
proof_items = [{**item, 'billed_metres': '0', 'total_cents': 0, 'unit_cents': 0,
'proof_parent_item_index': index} for _, index, item in selected]
freight = {**parent['snapshot'].get('freight', {}), 'total_cents': 0}
snapshot = {**parent['snapshot'], 'items': proof_items, 'total_cents': 0,
'freight': freight, 'proof_of': parent['number']}
child = c.execute('''INSERT INTO dtf_local.orders(id,owner,snapshot,payment,origin,parent_id,machine_id,machine_chosen)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
(uuid4(), proof_identity(parent['id']), Jsonb(snapshot), Jsonb({'provider': PROVIDER}),
parent['origin'], parent['id'], parent.get('machine_id'), parent.get('machine_chosen', False))).fetchone()
queue(c, child['id'], len(snapshot['items']))
return child
def open_child(c, parent_id):
"""The parent's proof card still waiting for its answer, if any."""
return c.execute('''SELECT * FROM dtf_local.orders WHERE parent_id=%s AND proof_result IS NULL
AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (parent_id,)).fetchone()
def waiting(c, order):
"""Whether the order waits for its proof: it has a proof card without an OK."""
return not order.get('parent_id') and not order.get('proof_ok_at') and bool(open_child(c, order['id']))
def manual_source_needed(c, order):
"""A proof child cannot decode an original; prepare the full parent PNG first."""
if order.get('parent_id') or order['state'] != 'rec':
return False
child = open_child(c, order['id'])
return bool(child and c.execute('''SELECT 1 FROM dtf_local.print_files
WHERE order_id=%s AND status='manual' LIMIT 1''', (child['id'],)).fetchone())
def require_unlocked(c, order):
"""A parent cannot enter production or have its final changed before the proof answer."""
if waiting(c, order):
child = open_child(c, order['id'])
raise HTTPException(409, f'Aguardando prova do #{child["number"]}: responda no card da prova.')

150
app/prumo.py Normal file
View File

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

View File

@@ -22,7 +22,7 @@ from psycopg.types.json import Jsonb
from . import payments
from .proof import PROOF_ABOVE_METRES
from .core.models import PRODUCTION_VERSIONS
from .core.pricing import is_manual, manual_extra_cents, price
from .core.pricing import bill_splits, is_manual, manual_extra_cents, price, treatment_cents
from .runtime import freight, upload_row
from .scanning import require_clean
@@ -64,7 +64,7 @@ def approve(c, row, items, reviewer):
for item, original in zip(items, draft['items']):
if item.mode != original['mode'] or list(map(str, item.uploads)) != original['uploads']:
raise HTTPException(422, 'O produto e os arquivos não podem mudar na revisão.')
if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged'] or item.residue_accepted != original.get('residue_accepted', 0):
if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged'] or item.residue_accepted != original.get('residue_accepted', 0) or item.stroke_class != original.get('stroke_class') or item.stroke_px != original.get('stroke_px') or item.stroke_choice != original.get('stroke_choice') or (item.split and item.split.model_dump()) != original.get('split'):
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:
@@ -72,22 +72,40 @@ def approve(c, row, items, reviewer):
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),
priced.append({**price(item.mode, str(item.metres), item.grade, extra,
minimum=Decimal('0') if item.split else Decimal('1')),
'uploads': original['uploads'], 'production': original['production'],
'quality_status': original['quality_status'],
'quality_acknowledged': original['quality_acknowledged'],
'residue_accepted': original.get('residue_accepted', 0)})
'residue_accepted': original.get('residue_accepted', 0),
**({'residue_accepted_at': original['residue_accepted_at']}
if original.get('residue_accepted_at') else {}),
**({'stroke_px': original['stroke_px'], 'stroke_class': original['stroke_class']}
if original.get('stroke_class') else {}),
**({'stroke_choice': original['stroke_choice']} if original.get('stroke_choice') else {}),
**({'stroke_choice_at': original['stroke_choice_at']}
if original.get('stroke_choice_at') else {}),
**({'proof_y_fraction': original['proof_y_fraction']}
if original.get('proof_y_fraction') is not None else {}),
**({'source_dpi': original['source_dpi']} if original.get('source_dpi') else {}),
**({'split': original['split']} if original.get('split') else {})})
bill_splits(priced)
metres = sum(Decimal(i['billed_metres']) for i in priced)
try:
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
metres, sum(i['total_cents'] for i in priced))
except ValueError as exc:
raise HTTPException(422, str(exc))
treatment = treatment_cents() if draft.get('treatment') else 0
approved = {'customer': draft['customer'], 'items': priced, 'freight': quoted_freight,
'destination': draft.get('destination'),
# The customer's proof only above 10 m (Dropstar, 2026-10-28).
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents']}
# Designer treatment is one fixed service line (front 5).
**({'treatment': {'cents': treatment, 'hours': 24}} if treatment else {}),
# Browser timings are kept for Números, never for the price (0.12).
**({'timings': draft['timings']} if draft.get('timings') else {}),
'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents'] + treatment}
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
(Jsonb(approved), reviewer, row['id']))
# Approved and payable now: the files wait for the payment, not for ever.

View File

@@ -11,6 +11,7 @@ import io
import unicodedata
from datetime import datetime
from .core.pricing import sheet_label
from .printfile import Name, PdfWriter, deflate, serialize, _HELVETICA, _HELVETICA_BOLD
from .printjobs import LOCAL, file_prefix
@@ -95,7 +96,7 @@ def lines(order, paid_with, issued):
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 += [(part, 9.5, False, 2) for part in wrap(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))}{sheet_label(item)} — {metres} m", 9.5)]
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),

131
app/reviews.py Normal file
View File

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

View File

@@ -32,6 +32,8 @@ if os.environ.get('FREIGHT_ADAPTER') == 'jadlog':
from .jadlog import JadlogFreight
_carriers.append(JadlogFreight())
from . import correios as _correios
from . import prumo
from .core.pricing import treatment_cents
if _correios.configured():
_carriers.append(_correios.CorreiosFreight())
freight = FreightOptions(_carriers or [FakeFreight()])
@@ -103,21 +105,49 @@ def order_code(order_id):
return str(order_id).replace('-', '')[:8].upper()
def quote_view(c, row):
def quote_views(c, rows):
"""quote_view for a list of quotes, in two queries whatever its length: the
board shows up to 240 quotes, and asking per quote made 480 queries."""
ids = [row['id'] for row in rows]
if not ids:
return []
orders = {r['quote_id']: {k: r[k] for k in ('id', 'number', 'state')} for r in c.execute(
'SELECT quote_id,id,number,state FROM dtf_local.orders WHERE quote_id=ANY(%s)', (ids,)).fetchall()}
attempts = {r['quote_id']: {k: r[k] for k in ('method', 'status', 'status_detail', 'expires_at', 'created_at')}
for r in c.execute('''SELECT DISTINCT ON (quote_id) quote_id,method,status,
response->>'status_detail' AS status_detail, response->>'expires_at' AS expires_at, created_at
FROM dtf_local.payment_intents WHERE quote_id=ANY(%s) ORDER BY quote_id, created_at DESC''', (ids,)).fetchall()}
return [quote_view(c, row, order=orders.get(row['id']), attempt=attempts.get(row['id']), known=True) for row in rows]
def quote_view(c, row, order=None, attempt=None, known=False):
from .quote_review import review_reason # it imports this module
order = c.execute('SELECT id,number,state FROM dtf_local.orders WHERE quote_id=%s', (row['id'],)).fetchone()
# The latest payment attempt, so the payment page can tell a refused card
# (the notification updates it) from one still waiting.
# Its PIX expiry and time let the Kanban tell "tried to pay" from "never tried".
attempt = c.execute('''SELECT method,status,response->>'status_detail' AS status_detail,
response->>'expires_at' AS expires_at, created_at
FROM dtf_local.payment_intents WHERE quote_id=%s ORDER BY created_at DESC LIMIT 1''', (row['id'],)).fetchone()
from .payments import QUOTE_VALID_HOURS # it imports this module too
if not known:
order = c.execute('SELECT id,number,state FROM dtf_local.orders WHERE quote_id=%s', (row['id'],)).fetchone()
# The latest payment attempt, so the payment page can tell a refused card
# (the notification updates it) from one still waiting.
# Its PIX expiry and time let the Kanban tell "tried to pay" from "never tried".
attempt = c.execute('''SELECT method,status,response->>'status_detail' AS status_detail,
response->>'expires_at' AS expires_at, created_at
FROM dtf_local.payment_intents WHERE quote_id=%s ORDER BY created_at DESC LIMIT 1''', (row['id'],)).fetchone()
if attempt and attempt['status'] == 'rejected':
from .payment_messages import rejection
attempt = {**attempt, 'message': rejection(attempt['status_detail'])}
expired = row['approved_at'] and row['approved_at'] < datetime.now(timezone.utc)-timedelta(hours=24)
expires_at = (row['approved_at'] + timedelta(hours=QUOTE_VALID_HOURS)
if row['approved_at'] else None)
expired = (bool(row.get('expired_at')) or
bool(row['approved_at'] and row['approved_at'] <
datetime.now(timezone.utc)-timedelta(hours=QUOTE_VALID_HOURS)))
items = (row['approved'] or row['draft']).get('items') or []
treatment = (row['approved'] or {}).get('treatment')
if not treatment and (row['draft'] or {}).get('treatment') and treatment_cents():
treatment = {'cents': treatment_cents(), 'hours': 24}
return {'id': row['id'], 'created_at': row['created_at'],
'draft': row['draft'], 'approved': row['approved'],
'expires_at': expires_at.isoformat() if expires_at else None,
'expired_at': row['expired_at'].isoformat() if row.get('expired_at') else None,
'prumo': prumo.customer_summary(items), 'treatment': treatment,
'status': 'paid' if order else 'discarded' if row.get('discarded_at') else 'expired' if expired
else 'approved' if row['approved'] else 'pending_review',
'auto_approved': row.get('reviewed_by') == 'auto',

View File

@@ -80,6 +80,8 @@ CREATE TABLE IF NOT EXISTS dtf_local.security_events (
);
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS expires_at timestamptz;
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS purged_at timestamptz;
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS original_name text;
UPDATE dtf_local.uploads SET original_name=name WHERE original_name IS NULL;
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_state text NOT NULL DEFAULT 'pending';
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_reason text;
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scanned_at timestamptz;
@@ -136,6 +138,7 @@ CREATE TABLE IF NOT EXISTS dtf_local.print_files (
created_at timestamptz NOT NULL DEFAULT now(), finished_at timestamptz,
UNIQUE(order_id,item_index)
);
ALTER TABLE dtf_local.print_files ADD COLUMN IF NOT EXISTS claim_token uuid;
-- Each run of the off-server database backup (ops/db_backup.py), which the
-- Kanban shows so a backup that stopped working does not go unnoticed.
@@ -203,8 +206,40 @@ CREATE INDEX IF NOT EXISTS payment_events_unprocessed ON dtf_local.payment_event
CREATE INDEX IF NOT EXISTS print_files_open ON dtf_local.print_files(created_at)
WHERE status IN ('pending','rendering');
-- The generated files of each item (item 13, 2026-10-29): one PNG, or the parts
-- of a film over 15 m, in order. print_files.upload_id stays the first.
CREATE TABLE IF NOT EXISTS dtf_local.print_parts (
order_id uuid NOT NULL, item_index integer NOT NULL, part integer NOT NULL CHECK(part >= 1),
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id) ON DELETE CASCADE,
PRIMARY KEY(order_id,item_index,part),
FOREIGN KEY(order_id,item_index) REFERENCES dtf_local.print_files(order_id,item_index) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS print_parts_upload ON dtf_local.print_parts(upload_id);
-- What each machine's hot folder gets (item 10, app/hotfolder.py): one row per
-- file or part, per entry into Imprimindo (round), written by one computer.
CREATE TABLE IF NOT EXISTS dtf_local.hot_parts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
round integer NOT NULL, seq integer NOT NULL, item_index integer NOT NULL,
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id) ON DELETE CASCADE,
name text NOT NULL, folder text,
state text NOT NULL DEFAULT 'queued'
CHECK(state IN ('queued','claimed','written','consumed','withdraw','gone')),
claimed_at timestamptz, claimed_by text, written_at timestamptz, done_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE(order_id, round, seq)
);
CREATE INDEX IF NOT EXISTS hot_parts_open ON dtf_local.hot_parts(order_id)
WHERE state IN ('queued','claimed','written','withdraw');
INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id)
SELECT order_id,item_index,1,upload_id FROM dtf_local.print_files WHERE upload_id IS NOT NULL
ON CONFLICT DO NOTHING;
-- A movement that undid an earlier one (a mistaken move), shown as such.
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS back boolean NOT NULL DEFAULT false;
CREATE INDEX IF NOT EXISTS movements_finished_latest ON dtf_local.movements(order_id, created_at DESC)
WHERE to_state='fin' AND NOT back;
-- The Kanban lists payment events a person must act on (money without an
-- order, or a reversed payment on an existing order) until resolved.
@@ -254,11 +289,9 @@ ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFA
ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro'));
-- The print machines, and which products each prints. An order keeps the
-- machine someone chose (machine_chosen) or the one given automatically: the
-- 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.
-- Print machines and which products each prints. An order gets its machine
-- when someone pulls it into Imprimindo; no machine is assigned at payment.
-- limit_metres remains the load shown for a machine.
CREATE TABLE IF NOT EXISTS dtf_local.machines (
id uuid PRIMARY KEY, name text UNIQUE NOT NULL, products text[] NOT NULL DEFAULT '{}',
active boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now()
@@ -273,6 +306,44 @@ DO $$ BEGIN
INSERT INTO dtf_local.migrations VALUES('machine-chosen-v1');
END IF;
END $$;
-- Remove the old automatic suggestions before printing. Keep real choices
-- and machines already printing, whose hot-folder files may be in flight.
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='machine-pull-only-v1') THEN
UPDATE dtf_local.orders SET machine_id=NULL, machine_chosen=false
WHERE NOT machine_chosen AND state IN ('rec','tra','cor');
INSERT INTO dtf_local.migrations VALUES('machine-pull-only-v1');
END IF;
END $$;
-- Acceptable time per stage (front 11): Gestão edits these; a card past the
-- limit turns yellow, at twice the limit red. `responsible` is who the board
-- names for that column. The final stage counts days without pickup.
CREATE TABLE IF NOT EXISTS dtf_local.stage_limits (
state text PRIMARY KEY CHECK (state IN ('rec','tra','imp','rev','fin')),
hours numeric NOT NULL CHECK (hours > 0),
responsible text NOT NULL DEFAULT '',
updated_by text NOT NULL DEFAULT 'sistema',
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Videos are uploaded by Gestão; the Site reads only enabled, scanned files.
CREATE TABLE IF NOT EXISTS dtf_local.site_videos (
id text PRIMARY KEY CHECK (id IN ('subindo','nota','png','avulsas','retirada','sala')),
upload_id uuid REFERENCES dtf_local.uploads(id),
captions_id uuid REFERENCES dtf_local.uploads(id),
video_key text,
captions_key text,
product text CHECK (product IN ('file','avulsa','uvfile','uv')),
enabled boolean NOT NULL DEFAULT false,
updated_by text NOT NULL DEFAULT 'sistema',
updated_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE dtf_local.site_videos ADD COLUMN IF NOT EXISTS video_key text;
ALTER TABLE dtf_local.site_videos ADD COLUMN IF NOT EXISTS captions_key text;
INSERT INTO dtf_local.stage_limits(state,hours,responsible) VALUES
('rec',2,'Designer'), ('tra',6,'Operador'), ('imp',4,'Operador'),
('rev',2,'Revisor'), ('fin',72,'Atendimento')
ON CONFLICT (state) DO NOTHING;
-- The machines an operator works on; none means every machine.
CREATE TABLE IF NOT EXISTS dtf_local.operator_machines (
operator_id uuid NOT NULL REFERENCES dtf_local.operators(id) ON DELETE CASCADE,
@@ -423,6 +494,90 @@ ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_photo uuid REFER
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_id uuid REFERENCES dtf_local.machines(id) ON DELETE SET NULL;
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_at timestamptz;
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_answered boolean NOT NULL DEFAULT false;
-- The contraction class chosen per item (item 9), keyed by item index, with
-- who chose it and when; the measured class stays in the order's snapshot.
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contraction jsonb NOT NULL DEFAULT '{}'::jsonb;
-- The proof card (Dropstar, 2026-10-30, app/proof.py): an order of its own,
-- child of the order it proves, with no quote of its own; its answer, Prova OK
-- or reprovada with its reason, by whom and when.
ALTER TABLE dtf_local.orders ALTER COLUMN quote_id DROP NOT NULL;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS parent_id uuid REFERENCES dtf_local.orders(id) ON DELETE CASCADE;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_result text CHECK (proof_result IN ('ok','rejected'));
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_decided_at timestamptz;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_decided_by text;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_reason text;
CREATE INDEX IF NOT EXISTS orders_parent ON dtf_local.orders(parent_id) WHERE parent_id IS NOT NULL;
-- An order's own rows go with it, so deleting an order takes its proof cards
-- and theirs too. Done once: a constraint already cascading is left alone.
DO $$
DECLARE r record;
BEGIN
FOR r IN SELECT c.conname, c.conrelid::regclass AS tbl FROM pg_constraint c
WHERE c.contype='f' AND c.confrelid='dtf_local.orders'::regclass AND c.confdeltype<>'c'
AND c.conrelid IN ('dtf_local.movements'::regclass, 'dtf_local.order_files'::regclass,
'dtf_local.print_files'::regclass)
LOOP
EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I', r.tbl, r.conname);
EXECUTE format('ALTER TABLE %s ADD CONSTRAINT %I FOREIGN KEY (order_id) REFERENCES dtf_local.orders(id) ON DELETE CASCADE',
r.tbl, r.conname);
END LOOP;
END $$;
-- When the session was last used (Usuários: who is on the system now).
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS seen_at timestamptz;
-- The machine of whoever moved a card, as it was named then: "Imprimindo ·
-- Thales · máquina2".
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS machine text;
-- An approved quote nobody paid in 24 h expires (Fase 2, front 9, app/unpaid.py).
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS expired_at timestamptz;
-- The Revisor's photo or short video of the printed sheet (Fase 2, front 2,
-- app/reviews.py): DTF-<n>-revisao-<seq>, the record of when and by whom it
-- was checked. A photo is required to finish an order above 1 m.
CREATE TABLE IF NOT EXISTS dtf_local.order_reviews (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
seq integer NOT NULL CHECK(seq >= 1),
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id) ON DELETE CASCADE,
kind text NOT NULL CHECK(kind IN ('photo','video')),
width integer, height integer,
created_by text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE(order_id, seq)
);
CREATE INDEX IF NOT EXISTS order_reviews_order ON dtf_local.order_reviews(order_id);
-- Each machine's sheet (Fase 2, front 1, app/machine_log.py): what it cost and
-- when it started, typed once by Gestão; what goes into it, entered by the
-- room; and the minimum of each supply that raises the alert.
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS price_cents bigint CHECK (price_cents >= 0);
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS installed_on date;
-- When the counters start: a machine with no cleaning on record counts from
-- here, not from everything it printed before the sheet existed.
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS log_since timestamptz NOT NULL DEFAULT now();
CREATE TABLE IF NOT EXISTS dtf_local.machine_entries (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
kind text NOT NULL CHECK(kind IN ('supply','part','event')),
item text NOT NULL,
quantity numeric(12,3) CHECK (quantity > 0),
cost_cents bigint CHECK (cost_cents >= 0),
serial text, note text,
stop_minutes integer CHECK (stop_minutes > 0),
from_alert boolean NOT NULL DEFAULT false,
created_by text NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS machine_entries_machine ON dtf_local.machine_entries(machine_id, created_at);
CREATE TABLE IF NOT EXISTS dtf_local.machine_minimums (
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
item text NOT NULL, minimum numeric(12,3) NOT NULL CHECK (minimum >= 0),
PRIMARY KEY(machine_id, item)
);
-- "Adiar uma vez": an alert postponed lets one more card be pulled, once per
-- cycle (the cycle starts at the event that resets its counter).
CREATE TABLE IF NOT EXISTS dtf_local.machine_snoozes (
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
alert text NOT NULL, cycle_from timestamptz NOT NULL,
snoozed_by text NOT NULL, snoozed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(machine_id, alert, cycle_from)
);

View File

@@ -51,6 +51,8 @@ from urllib.parse import urlencode
import httpx
from .core.pricing import treatment_cents
API = 'https://api.tiny.com.br/public-api/v3'
AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect'
# Not TINY_PRODUCT_<MODE>: app/core/secrets.py reads any variable ending in
@@ -166,8 +168,13 @@ def configured():
def required_settings():
"""The OAuth application, and a product id for each mode not sold by SKU."""
return ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'] + [
required = ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'] + [
setting for mode, setting in PRODUCT_SETTINGS.items() if not (sku_prefix(mode) or step_sku(mode))]
# A paid treatment is a line of its own: missing, every treated order would
# fail at the Tiny, so ask for it with the rest of the settings.
if treatment_cents() > 0:
required.append('TINY_PRODUCT_TREATMENT')
return required
# The stack passes every setting, empty when unset, so empty means "the
@@ -489,6 +496,14 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
'quantidade': float(Decimal(item['billed_metres'])),
'valorUnitario': money(item['unit_cents']),
'infoAdicional': note})
treatment = order.get('treatment') or {}
if treatment.get('cents'):
setting = os.environ.get('TINY_PRODUCT_TREATMENT', '')
if not setting.isdigit():
raise TinyError('TINY_PRODUCT_TREATMENT must be the Tiny product id')
items.append({'produto': {'id': int(setting)}, 'quantidade': 1,
'valorUnitario': money(treatment['cents']),
'infoAdicional': 'Tratamento da arte pelo designer · +24 h'})
freight = order['freight']
service = freight.get('service')
pickup = service == 'pickup'
@@ -506,7 +521,8 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
# The carrier's time already counts production; a pickup is ready after it.
days = freight.get('days') if not pickup else int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0)
if days is not None:
pedido['dataPrevista'] = business_days_after(day, int(days)).isoformat()
days = int(days) + (1 if treatment.get('cents') else 0)
pedido['dataPrevista'] = business_days_after(day, days).isoformat()
# Paid at once, in full, as the store's orders: one parcel on the day.
pedido['pagamento'] = {'categoria': {'id': CATEGORIES.get(payload.get('origin'), CATEGORY)}}
received = RECEIPT_METHODS.get((payload.get('payment') or {}).get('method'))

72
app/unpaid.py Normal file
View File

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

View File

@@ -6,7 +6,7 @@ import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from psycopg.types.json import Jsonb
from . import mail
from . import mail, unpaid
from .adapters import FakeTiny, LocalS3Storage, require_runtime
from .core.secrets import load as load_secret_files
from .core.db import connect
@@ -39,6 +39,9 @@ def cleanup():
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 50""").fetchall()
for row in rows:
storage.discard(row['object_key'],row['multipart_id'],row['complete'])
# A generated PNG's pieces for the Kanban's viewer go with it (item 7).
if row['name'].lower().endswith('.png'):
storage.discard_prefix(f"originals/tiles/{row['id']}/")
c.execute('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s', (row['id'],))
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (row['id'],))
c.execute('DELETE FROM dtf_local.sessions WHERE expires_at<=now()')
@@ -118,6 +121,9 @@ def loop():
tick()
if time.monotonic()-last_cleanup > 60:
cleanup()
# Approved quotes unpaid for 24 h expire on their own (front 9).
with connect() as c:
unpaid.expire(c, os.environ.get('PUBLIC_ORIGIN', 'http://localhost'))
last_cleanup = time.monotonic()
mail.send_pending(connect)
tiny_keepalive()

View File

@@ -58,6 +58,8 @@ x-app: &app
QUOTE_AUTO_APPROVE: ${QUOTE_AUTO_APPROVE:-true}
QUOTE_AUTO_MAX_METRES: ${QUOTE_AUTO_MAX_METRES:-50}
MANUAL_FILE_EXTRA_CENTS: ${MANUAL_FILE_EXTRA_CENTS:-0}
# Fixed price of the designer's treatment per order; 0 hides the option.
TREATMENT_CENTS: ${TREATMENT_CENTS:-0}
TINY_ADAPTER: ${TINY_ADAPTER:-fake}
TINY_CLIENT_ID: ${TINY_CLIENT_ID:-}
TINY_CLIENT_SECRET: ${TINY_CLIENT_SECRET:-}
@@ -66,6 +68,7 @@ x-app: &app
TINY_PRODUCT_TEXTIL_AVULSA: ${TINY_PRODUCT_TEXTIL_AVULSA:-}
TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-}
TINY_PRODUCT_UV_AVULSA: ${TINY_PRODUCT_UV_AVULSA:-}
TINY_PRODUCT_TREATMENT: ${TINY_PRODUCT_TREATMENT:-}
TINY_SKU_TEXTIL_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-}
TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-}
TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-}

View File

@@ -37,10 +37,12 @@ TINY_ADAPTER=TBD
# redirect URL registered there must equal TINY_REDIRECT_URI.
TINY_CLIENT_ID=TBD
TINY_REDIRECT_URI=https://<KANBAN_DOMAIN>/api/operator/tiny/callback
TREATMENT_CENTS=0
TINY_PRODUCT_TEXTIL_FOLHA=TBD
TINY_PRODUCT_TEXTIL_AVULSA=TBD
TINY_PRODUCT_UV_FOLHA=TBD
TINY_PRODUCT_UV_AVULSA=TBD
TINY_PRODUCT_TREATMENT=TBD
TINY_FORMA_ENVIO_RETIRADA=TBD
# true only at go-live, after the n8n DTFIMP designer branch is removed.
TINY_STATUS_UPDATES=false

View File

@@ -75,6 +75,8 @@ x-app-environment: &app-environment
# (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}
# Fixed price of the designer's treatment per order, in cents; 0 hides it.
TREATMENT_CENTS: ${TREATMENT_CENTS:-0}
# 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.
@@ -96,6 +98,7 @@ x-app-environment: &app-environment
TINY_PRODUCT_TEXTIL_AVULSA: ${TINY_PRODUCT_TEXTIL_AVULSA:-}
TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-}
TINY_PRODUCT_UV_AVULSA: ${TINY_PRODUCT_UV_AVULSA:-}
TINY_PRODUCT_TREATMENT: ${TINY_PRODUCT_TREATMENT:-}
TINY_SKU_TEXTIL_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-}
TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-}
TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-}

View File

@@ -0,0 +1,90 @@
# Roadmap da 3ª rodada e Fase 2 — Kanban turbinado
Base: PDF de Marcus Fernandes, 05/11/2026, versão 2; leitura do repositório em 06/11/2026. Este plano ordena **entregas por esforço crescente**, preservando duas travas do documento: a correção **0.1 começa imediatamente e bloqueia a divulgação do site**, e **nenhuma frente da Fase 2 entra em produção antes da bateria de testes da seção 0**. Horas são faixas preliminares de engenharia, incluindo implementação e validação local; não são prazo corrido nem promessa de implantação. Uma pessoa pode tocar itens rápidos enquanto a correção 0.1 avança.
**Execução em 06/11:** a Etapa 0 está implementada no código e validada localmente. A prova 0.1 passou a recortar os 15 cm no trecho de traço mais fino de cada classe, gera o PNG final do filho, limpa o contato ao responder a prova e mantém pai e filho na mesma máquina. A 0.11 foi ensaiada no reset local com o `ops.launch_reset` (sem reiniciar a numeração) e a 0.12 passou a registrar tempos do site/Prumo em Números. A bateria local passou: unitários (o de preços no host, porque o container da API não tem Node), smoke, workflow, pagamento, impressão/prova, usuários, Kanban, cotações, segurança, retenção, backup e os dois testes de navegador. Nada foi implantado em produção; a 0.11 em dados reais continua dependendo de autorização, backup e janela.
## O que o código já comprova
- O pagamento cria o pedido e dispara a geração do arquivo e o card de prova; há caminhos separados para pedido de teste e pagamento registrado pelo balcão ([`app/payments.py`](../app/payments.py), [`app/api/operator.py`](../app/api/operator.py)). A correção 0.10 exige teste de ponta a ponta em ambiente controlado para confirmar que **pedido real do site** não usa esses caminhos.
- O pagamento cria o pedido e o card de prova. O card filho gera seu próprio PNG final, o pai fica bloqueado até a resposta e os dois compartilham a máquina; a prova usa uma janela de 15 cm em volta do traço mais fino de cada classe ([`app/proof.py`](../app/proof.py), [`app/printjobs.py`](../app/printjobs.py), [`app/printpng.py`](../app/printpng.py)).
- A máquina não é mais atribuída ao pagamento: quem puxa o card escolhe a máquina da sessão, e o histórico guarda operador e hora ([`app/machines.py`](../app/machines.py), [`app/api/operator.py`](../app/api/operator.py)).
- A folha pronta aceita resíduo e traço fino com o mesmo aceite das avulsas; a régua é 96/200 DPI e 287–293 DPI passam como 300 ([`web/site-quality.js`](../web/site-quality.js), [`web/site-config.js`](../web/site-config.js), [`app/grade_check.py`](../app/grade_check.py)).
- A geração tem timeout de 15 minutos, aviso de falha com hora no card e “Gerar de novo” ([`app/printjobs.py`](../app/printjobs.py), [`app/api/operator.py`](../app/api/operator.py)).
- O download do original agora usa `DTF-<n>-original-<i>`, e o arquivo final só entra como PNG RGBA 8 bits a 300 DPI ([`app/api/operator.py`](../app/api/operator.py), [`app/printpng_validate.py`](../app/printpng_validate.py)).
- A 0.12 passou a registrar em Números a página, o upload (MB/s), a conferência do Prumo, a montagem, a geração por 10 m e o tempo do evento de pagamento até o card, com média e p95 ([`app/api/operator.py`](../app/api/operator.py), [`web/checkout.js`](../web/checkout.js), [`web/kanban.js`](../web/kanban.js)).
Esses achados são **verificação estática do repositório**, não prova de que a versão implantada tem exatamente o mesmo comportamento. O PDF traz evidências visuais dos pedidos #14 e #15; a confirmação de correção precisa repetir cenários equivalentes em homologação.
## Etapa 0 — correções antes da Fase 2
**Começar 0.1 no primeiro dia**, em paralelo aos primeiros itens abaixo. Os itens estão na ordem aproximada de menor esforço para entregar. A sequência de publicação deve preservar as dependências indicadas.
| Ordem de entrega | PDF | Trabalho e critério de aceite | Estimativa | Dependência |
|---|---|---|---:|---|
| 1 | 0.7 | Finalizados do mais novo ao mais antigo; colunas de trabalho continuam FIFO. | 2–4 h | Nenhuma. |
| 2 | 0.6 | “Abrir arquivo” na frente do card em todas as colunas, sem expandir. | 3–6 h | Nenhuma. |
| 3 | 0.10 | Provar que pedido real do site só nasce com pagamento confirmado; manter exceções explícitas de teste e balcão. Corrigir apenas se o teste achar furo. | 3–8 h | Acesso a homologação e um fluxo de pagamento de teste. |
| 4 | 0.8 | Nova régua: `<96` recusa; `96–199` exige ciência; `>=200` passa sem ressalva. Aplicar no navegador e na aprovação do servidor; conferir 287–293 DPI. | 6–12 h | Arquivos de amostra. |
| 5 | 0.9 | Arquivo final exclusivamente PNG 300 DPI transparente. Validar no servidor, no upload e na aprovação; mensagem clara para PDF/TIFF ou conversão definida. | 8–16 h | Decidir **rejeitar** PDF/TIFF ou convertê-los; sugerido rejeitar e orientar o designer, por ser a via menor e mais segura. |
| 6 | 0.5 + limpeza da máquina | Eliminar máquina automática na criação; atribuir a máquina da sessão que puxa; gravar operador/hora; contar o limite e mandar à pasta certa. Pai e filho não podem divergir. | 10–20 h | Regra de prova 0.1 para a vinculação pai/filho. |
| 7 | 0.4 | Timeout visível, horário da falha, recuperação de job preso e “Gerar de novo” funcional para falha/timeout. | 10–18 h | Definir timeout inicial por tamanho; medir com 0.12. |
| 8 | 0.3 | PNG alto: medir dimensões no servidor ou rejeitar com limite explícito **antes de cobrar**; `0 DPI` nunca passa como medida. Testar 57 × 1600 cm. | 12–24 h | Definir limite aceito para arquivo alto caso a análise no servidor não seja viável. |
| 9 | 0.2 | Aceite explícito e persistido de resíduo e traço fino na folha pronta **e** nas avulsas; sem aceite, trava; fundo chapado e `<96 DPI` continuam sem exceção. | 14–28 h | Texto final de aceite já está no PDF. |
| 10 | 0.1 **urgente** | Prova criada no pagamento: até 15 cm por classe do trecho de menor traço, PNG final aprovado no filho, custo/metragem zero, topo da fila, uma máquina para pai/filho, travas do pai até resposta do vendedor, motivo na reprovação. | 36–72 h | 0.5 integra a parte de máquina; usar amostras #14/#15. **Bloqueia divulgação.** |
| 11 | “O que tirar” | Remover “Contato feito”, agrupar Originais, mover Manifesto para Arquivos e ocultar nota do cliente. A remoção da máquina automática está em 0.5. | 6–12 h | “Contato feito” depende de 0.1; demais independentes. |
| 12 | 0.12 | Medir média e p95 das seis etapas no Números; ETA de upload e andamento legível das etapas no site; converter violações dos limites do PDF em correções com número. | 24–40 h | Instrumentar antes da bateria final para medir casos reais. |
| 13 | 0.11 | **Só depois de 0.1–0.10:** backup verificável, limpeza de pedidos/cards/histórico/pastas e recibos, preservar cadastros/integrações e sequência de números Tiny; repetir toda a bateria. | 8–16 h de operação | Autorização expressa do dono dos dados, janela, backup/restauração, lista de números já usados no Tiny; cliente cancela testes no Tiny. |
**Gate de saída da Etapa 0:** repetir no site e no Kanban os cenários do PDF, inclusive #14/#15 equivalentes, PNG alto, 96/199/200/293 DPI, resíduo/traço fino nos dois caminhos, timeout e retomada, máquina puxada, saída em PNG, pedido não pago, e medição de tempos. Divulgar o site somente após a prova 0.1 e os demais bloqueios comerciais estarem validados. O “zerar” é destrutivo: preparar e ensaiar restauração antes de executar em qualquer ambiente com dados reais.
## Fase 2 — entregas menores primeiro, respeitando dependências
O PDF numera as frentes pela prioridade do cliente; esta tabela muda **apenas a ordem de implementação sugerida por tempo**. A documentação da frente 12 acompanha cada entrega e fecha a rodada.
| Sequência | Frente | Entrega | Estimativa | Entrada necessária / dependência |
|---|---|---|---:|---|
| 1 | 6 | Nome Prumo e relatório ordenado das ações no card e no resumo antes do pagamento. | 12–24 h | Itens prévios 9/13/16 citados no PDF; persistir eventos reais, não inferir do resultado final. |
| 2 | 4 | Área de vídeos, player flutuante e vínculo por produto. | 12–24 h | Estrutura independe da gravação; **Dropstar fornece seis vídeos** para publicar. A edição pelo Kanban entra na frente 8. |
| 3 | 5 | Tratamento pelo designer como opcional, item pago, etiqueta e prazo adicional de 24 h. | 12–24 h | **Dropstar define R$ X** e confirma capacidade/SLA; reutilizar fluxo existente de envio do final. |
| 4 | 9 | Evoluir cotações/tentativas para aba “Aguardando pagamento”, idade, contato, expiração e abandono. | 16–32 h | Decisões de expiração, aviso, cancelamento e arquivo; vide quadro abaixo. Não tratar cotação pendente de revisão como pedido criado. |
| 5 | 11 | Limites editáveis por etapa, cores, lista Atrasados e comparação no Números. | 18–32 h | Limites iniciais no PDF: 2 h, 6 h, 4 h, 2 h, 3 dias; confirmar dono de cada etapa. |
| 6 | 3 | Premium: produto, preço, classe/pasta PREMIUM, SKU Tiny e comparação no site. | 28–52 h | **Bloqueado para publicação** até preset Spot OK Premium no Flexi, hot folder, contração e três folhas de teste aprovadas pela Dropstar; SKU Tiny. |
| 7 | 2 | Foto/vídeo da revisão, câmera/upload, pasta `Revisões/`, bloqueio de Finalizado acima de 1 m e foto no aviso. | 36–64 h | Dropstar instala pedestal/celular e aprova exemplo de foto; integrar ao fluxo de avisos do n8n/Tiny já usado pelo cliente. |
| 8 | 1 | Ficha de máquinas, insumos/peças/eventos, contadores, alertas e custo/ROI no Números. | 64–112 h | Hot folders existentes; **Dropstar fornece** preço/data de instalação, custos/lotes, mínimos e registro operacional. Confirmar como detectar “entre um arquivo e outro” sem sinal de impressão do Flexi. |
| 9 | 7a | Montador no Kanban com `Estampas/`, tabela de tamanhos, lista, montagem e card faturado. | 72–128 h | Prumo 6; **Dropstar fornece** PNGs/códigos, tabela de tamanhos e regra de faturamento/Tiny; criar perfil Expedição. |
| 10 | 7b | QR no impresso e preenchimento automático do lote. | 72–128 h | 7a em uso; **Dropstar fornece** origem e formato dos pedidos do lote e validação física do QR. |
| 11 | 8 | Aba Site administrável: produtos, preços/faixas, cupons, vídeos e nota da arte, com vigência e auditoria. | 96–160 h | Modelo comercial e permissões aprovados pela Gestão; frente 4 para vídeos; migrar preço autoritativo do código para banco sem alterar pedidos pagos. |
| 12 | 10 | Vetorizar/ampliar separado, lote, prévia, créditos/packs, cupom e chamada ao motor. | 120–220 h | Frente 8; **Wagner mede custo/qualidade por imagem e escolhe motor**, Dropstar aprova pack e política grátis. Fazer piloto antes de fixar preço. |
| Transversal | 12 | Documentação macro, por perfil e implantação; atualizar ao concluir cada rodada. | 16–32 h | Acesso aos fluxos reais de Flexi, Tiny, pagamento e n8n; revisão operacional da Dropstar. |
## Dependências que precisam vir deles
**Dropstar/Marcus (decisões e material):**
1. Autorizar e agendar o reset 0.11 **somente quando a correção estiver validada**; confirmar backup, dados a preservar, sequência dos números e cancelamento manual dos testes no Tiny.
2. Fornecer massa de homologação equivalente aos pedidos #14/#15 e aos arquivos de DPI, resíduo, traço e PNG alto; confirmar os tempos aceitáveis já propostos no PDF após a medição 0.12.
3. Informar preço do tratamento; preços de compra e datas das máquinas; lançamentos históricos, custos, mínimos e responsáveis por alimentar insumos/eventos.
4. Gravar/entregar seis vídeos; fornecer pedestal/celular para revisão e aprovar se foto pode seguir pelo fluxo de aviso existente.
5. Configurar e testar o Premium no Flexi (8 passadas, branco máximo, contração, hot folder), imprimir três folhas, dar o “ok, testado” e cadastrar/confirmar SKU no Tiny.
6. Entregar biblioteca `Estampas/` (PNG transparente 300 DPI por código), tabela de larguras, exceções por tamanho, regra de faturamento e origem dos lotes/QR.
7. Definir preços iniciais, faixas, cupons, responsáveis e vigência da aba Site; validar se a nota da arte deve sair da tela até ter ação definida.
8. Com Wagner, comparar motor próprio e API para vetorizar: custo real, fotos/degradês, volume esperado e política dos packs/grátis antes de ativar cobrança.
**Respostas operacionais necessárias, mas parcialmente verificadas no código:**
| Pergunta do PDF | Achado no repositório | Confirmação externa |
|---|---|---|
| Onde fica pedido criado e não pago? | Cotações sem pedido aparecem na aba Cotações; tentativas têm registros separados. O card de produção surge ao confirmar pagamento, teste ou pagamento de balcão. | Definir se a futura aba une cotação aprovada e tentativa pendente; manter cotações aguardando revisão separadas. |
| Quanto duram Pix/cartão e o arquivo? | Pix: 30 min configurados. Cotação aprovada: 24 h; arquivos têm retenção própria. Não há uma regra única de 24 h de pedido não pago. | Confirmar política de cartão pendente/3DS, contato, expiração de 24 h, mensagem e exclusão do arquivo em conformidade com pagamento tardio. |
| “Original 1” baixa com qual nome? | Hoje o download individual usa o nome do upload. | O PDF já decide: renomear para nome do pedido; não precisa de nova decisão. |
| Menor traço é medido quando? | Nas avulsas, a medida é recalculada para a largura escolhida em 300 DPI. | Validar a folha pronta com arquivo de teste; a regra final deve ser a dimensão impressa, não o original. |
| Tiny avisa a cada etapa? | O código envia eventos de pagamento, entrada na fila e Finalizado; atualização de status Tiny depende de configuração. | **Dropstar verifica n8n/Tiny real:** quais estados disparam WhatsApp e texto aprovado. |
| “Pedir novamente” reutiliza final? | Não foi localizada implementação dessa ação no site/portal do repositório. | Se existe fora deste código, demonstrar; se entrar no escopo, decidir reaproveitamento de PNG válido, retenção e nova conferência. |
## Decisões de interpretação do PDF
- Em 0.5, o texto diz que a máquina automática é sugestão; em “O que tirar”, Marcus manda retirar a atribuição automática e deixar toda a fila sem máquina até alguém puxar. **Adotar a segunda regra**, que é explícita e resolve a separação pai/filho. Se uma sugestão visual ainda for desejada, ela não pode gravar `machine_id` nem dividir a prova.
- O quadro “Ordem e dependências” chama a frente 9 de “Aba Cotações”; o texto da frente 9 pede **aba Aguardando pagamento**. Tratar como evolução da aba existente e mostrar apenas oportunidades realmente pagáveis, sem misturar revisão de orçamento.
- Na frente 5, “item 8 no ar” se refere ao envio de arquivo final da rodada anterior, não necessariamente à frente 8 da Fase 2. O fluxo já existe no código; o preço do serviço é o bloqueio principal.
- A proposta de 24 h para pedido não pago não substitui os 30 min do Pix. O sistema precisa distinguir vencimento da tentativa de pagamento, prazo de recuperação comercial e retenção do arquivo, para não apagar uma compra paga tardiamente.

View File

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

View File

@@ -579,6 +579,31 @@ pydantic-core==2.46.5 \
--hash=sha256:fc8515076c11f3cfdf4fb142dcca0fe384b1230a3b5415458ac84f3e0903ec13 \
--hash=sha256:ff218293c9c806138dca139765e3b067621be52bcd93cdc14c7711be7ddc90a9
# via pydantic
pypdfium2==5.14.0 \
--hash=sha256:09b99c8f0cb427eb17fec13c0862ed598bba34b4843df153f70fff806a2820bc \
--hash=sha256:11f281613fa22313d9c7ab89947665e84eccf8ebe40e1198a84a88352305648d \
--hash=sha256:149fd5c6397b8df8bf7911a93506eff0be874f877afe7ac936cf5d37d21a6a06 \
--hash=sha256:1951f0aed469150b13c62eabd501a9839e608ab9983ca8579be9eb73213b72b6 \
--hash=sha256:2de384df66ba55fcaab0775f30f28ec1090af3dfa60276a07821efc96d993118 \
--hash=sha256:382de7fe20d32c42993a274d7b6c555a5623a97570dfc1d2f5e0a16fe0d5d482 \
--hash=sha256:51d9e9b64ebc34effaf57f9b6d4511b3f66ad3744bd1690d2cc6700853173dcf \
--hash=sha256:593f2c952ae3ffdca0efcbb3d9464fbccb876254386114ff900cabef21157c3f \
--hash=sha256:605ab9d0d4c5e223599c9065b88d16b2c1f131c807c80dea8adbb16f1433e95b \
--hash=sha256:790e2cac1641a65912b73bd7243f45195d36f1663c85a3e1a126a8f5867c82a3 \
--hash=sha256:9f4d77db5232826dd03a63481f32164331b96c21fd68f0667b2e43dbae141a93 \
--hash=sha256:9fd5cc94a389d50298e4d8cb79af6b9b8e0d785606e2a937725dc6e271c9c6e6 \
--hash=sha256:b40a0913196a1483f0fdc22a53f8719c3aef87f1c4d8d9c38d2ad4e207500fdf \
--hash=sha256:bed597b2cea3990164e43f9003f71db18959d0abd5d73adc9c176e7be2d84b98 \
--hash=sha256:c5f009b3157f10e97dceb55963f5910eff92feb00587ba10a76f12b87ce1a4b6 \
--hash=sha256:c73be14076bedebd9bcaf9b062579c95c668580043bccd29eb0db502101d5716 \
--hash=sha256:d436ee9e024f981e68f5775f5a9d115f93ea14ee6c2c6efd35dd17d83edf4942 \
--hash=sha256:dbfd6deff68cc46b134acd6be380d98d694a9f018fbb622c07229225c85db389 \
--hash=sha256:e4e203ea9710fd00e5448edb6f1615dc8587035357f75f40b432dde0c33e8da1 \
--hash=sha256:e70d87cb0577eab38f2106f9c9606b458930beef612a1b5f298772ed259f5ec0 \
--hash=sha256:eb8aeca157808f323e39ea298cc6d6c8e080c192ea2efb1ca81daa0f0ff4d095 \
--hash=sha256:f1b696e6901e16f114a2ec6332e5e3f8f5033a901614ead28499ab18ca6024f5 \
--hash=sha256:f6f13bbcc5f4adabc2676e52f662c6cb375de86b314790b0ae08f3ab62eb116a
# via -r infra/requirements.txt
python-dateutil==2.9.0.post0 \
--hash=sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3 \
--hash=sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427

View File

@@ -6,3 +6,4 @@ boto3==1.38.23
httpx==0.28.1
pillow==13.0.0
pikepdf==10.13.0.post1
pypdfium2==5.14.0

View File

@@ -1 +1 @@
{"Rules":[{"ID":"local-artwork-retention","Status":"Enabled","Filter":{"Prefix":""},"Expiration":{"Days":30},"AbortIncompleteMultipartUpload":{"DaysAfterInitiation":1}}]}
{"Rules":[{"ID":"local-artwork-retention","Status":"Enabled","Filter":{"Prefix":"originals/"},"Expiration":{"Days":30},"AbortIncompleteMultipartUpload":{"DaysAfterInitiation":1}}]}

View File

@@ -2,6 +2,6 @@
"Version": "2012-10-17",
"Statement": [
{"Effect":"Allow","Action":["s3:ListBucket","s3:ListBucketMultipartUploads","s3:GetBucketLocation"],"Resource":["arn:aws:s3:::dtf-local-artwork"]},
{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":["arn:aws:s3:::dtf-local-artwork/originals/*"]}
{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":["arn:aws:s3:::dtf-local-artwork/originals/*","arn:aws:s3:::dtf-local-artwork/videos/*"]}
]
}

View File

@@ -1,32 +1,43 @@
"""Clear the test orders before the Site opens to customers, once, by hand.
"""Clear the test board before the Site opens to customers, once, by hand.
Run from the worker's console (Portainer > Containers > worker > Console):
python -m ops.launch_reset shows what would be removed
python -m ops.launch_reset --confirmar APAGAR removes it
python -m ops.launch_reset --confirmar APAGAR --contas also customer accounts
python -m ops.launch_reset --root /srv/Kanban --confirmar APAGAR
also empties the flow folders
Removes every order with its moves, files and notices, every quote, payment
attempt and payment notification, and the artwork pictures. The artwork
files are marked expired, so the worker deletes them from storage within a
minute. Operators, the Tiny connection and the backups are kept.
Removes every order with its moves, files, notices and history, every quote,
payment attempt and payment notification, and the artwork pictures. The
artwork files are marked expired, so the worker deletes them from storage
within a minute. Operators, machines, prices, the Tiny connection and the
backups are kept.
It refuses if any payment was made with real money (Mercado Pago's
live_mode): those are customers' orders, not tests.
Order numbers start again at #1. A database set up before the worker could
do that prints the one command to run in the database container's console.
The order numbering is **not** reset (Dropstar, 2026-11-05): DTF-1…DTF-15
already exist as Tiny order numbers. DELETE keeps the identity sequence, so
the next card continues from where it stopped.
"""
import argparse
import shutil
import sys
from pathlib import Path
from app.core import db
TABLES = [ # in an order the foreign keys allow
('hot_parts', 'peças nas pastas das máquinas'),
('print_parts', 'partes dos arquivos de impressão'),
('reworks', 'retrabalhos'),
('contact_waits', 'esperas de contato'),
('movements', 'movimentos de etapa'),
('order_files', 'arquivos finais e correções'),
('print_files', 'arquivos de impressão gerados'),
('outbox', 'envios ao Tiny e avisos'),
('order_reviews', 'fotos e vídeos de revisão'),
('orders', 'pedidos'),
('payment_intents', 'tentativas de pagamento'),
('payment_events', 'avisos de pagamento'),
@@ -34,20 +45,38 @@ TABLES = [ # in an order the foreign keys allow
('upload_thumbnails', 'miniaturas das artes'),
]
ACCOUNTS = [('sessions', 'sessões de clientes'), ('accounts', 'contas de clientes')]
FLOW_FOLDERS = ('1. Arte recebida', '2. Arte conferida', '3. Imprimindo',
'4. Revisão', '5. Finalizado', 'Recibos', 'Revisões')
CONFIRM = 'APAGAR'
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):
return {table: c.execute(f'SELECT count(*) AS n FROM dtf_local.{table}').fetchone()['n'] for table, _ in tables}
def clean_folders(root, dry_run=True):
"""Empty the flow folders under `root`, recreating them; keep Estampas/."""
root = Path(root)
if not any((root / name).exists() for name in FLOW_FOLDERS):
raise SystemExit(f'{root} does not look like the Kanban root: no flow folders found.')
if dry_run:
return [str(root / name) for name in FLOW_FOLDERS if (root / name).exists()]
cleaned = []
for name in FLOW_FOLDERS:
path = root / name
if path.is_dir():
shutil.rmtree(path)
path.mkdir(parents=True, exist_ok=True)
cleaned.append(str(path))
return cleaned
def main(argv=None, out=print, connect=db.connect):
parser = argparse.ArgumentParser(prog='python -m ops.launch_reset')
parser.add_argument('--confirmar', default='', help=f'escreva {CONFIRM} para apagar')
parser.add_argument('--contas', action='store_true', help='apagar também as contas de clientes')
parser.add_argument('--root', type=Path, help='raiz Kanban, a pasta com "1. Arte recebida"')
parser.add_argument('--keep-files', action='store_true', help='não mexer nas pastas do Kanban')
args = parser.parse_args(argv)
tables = TABLES + (ACCOUNTS if args.contas else [])
with connect() as c:
@@ -61,22 +90,20 @@ def main(argv=None, out=print, connect=db.connect):
for table, label in tables:
out(f'{before[table]:>7} {label}')
out(f'{files:>7} arquivos de arte (o worker apaga do armazenamento)')
if args.root and not args.keep_files:
out('Pastas que serão esvaziadas:')
for folder in clean_folders(args.root, dry_run=True):
out(f' {folder}')
if args.confirmar != CONFIRM:
out(f'Nada foi apagado. Repita com --confirmar {CONFIRM} para apagar.')
return 0
for table, _ in tables:
c.execute(f'DELETE FROM dtf_local.{table}')
c.execute('UPDATE dtf_local.uploads SET expires_at=now() WHERE purged_at IS NULL')
out('Apagado.')
try:
with connect() as c:
c.execute(RENUMBER)
out('A numeração dos pedidos recomeça em #1.')
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():
raise
out('Para a numeração recomeçar em #1, rode no console do container do banco (db):')
out(f' psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "{RESTART}"')
if args.root and not args.keep_files:
for folder in clean_folders(args.root, dry_run=False):
out(f'esvaziada {folder}')
out('Apagado. A numeração dos pedidos continua de onde parou.')
return 0

View File

@@ -116,6 +116,19 @@ try{
await call('Emulation.setDeviceMetricsOverride',{width:1440,height:1100,deviceScaleFactor:1,mobile:false});
await call('Page.navigate',{url:`http://127.0.0.1:${server.address().port}/`});
await waitFor(()=>evaluate(`typeof sel==='function' && typeof pintaEntrega==='function'`),'Site scripts');
await evaluate('window.siteVideosReady');
assert.equal(await evaluate(`document.querySelectorAll('#videosGrid .videoCard').length`),0);
assert.equal(await evaluate(`document.querySelector('#videos').hidden`),true);
await evaluate(`VIDEOS[0].src='/preview.mp4';videosSection()`);
await evaluate(`document.querySelector('#videosGrid .videoCard').focus()`);
await click('#videosGrid .videoCard');
assert.deepEqual(await evaluate(`({dialog:document.querySelector('.videoModal').getAttribute('role'),
focus:document.activeElement.className,open:!document.querySelector('.videoModal').hidden})`),
{dialog:'dialog',focus:'vmClose',open:true});
await call('Input.dispatchKeyEvent',{type:'keyDown',key:'Escape',code:'Escape',windowsVirtualKeyCode:27});
assert.equal(await evaluate(`document.querySelector('.videoModal').hidden &&
document.activeElement.classList.contains('videoCard')`),true);
await evaluate(`VIDEOS[0].src=null;videosSection()`);
// Observe the actual engine, without replacing its placement or rendering.
await evaluate(`(()=>{
const original=encaixar;
@@ -159,7 +172,30 @@ try{
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});
// Item 9: the thinnest stroke at 300 DPI as Dropstar measures it, an odd
// width being 2d - 1, and ink specks under 30 px left out (2026-10-30).
assert.deepEqual(await evaluate(`(async()=>{
const medir=async(...rects)=>{const c=document.createElement('canvas');c.width=900;c.height=700;
const g=c.getContext('2d');g.fillStyle='#000';for(const r of rects)g.fillRect(...r);
return analisarMapa(await mapaDaImagem(await createImageBitmap(c),900/300*2.54)).traco;};
const linhas=w=>[[50,50,800,w],[50,400,800,40]];
const ciscos=Array.from({length:300},(_,i)=>[60+(i%30)*25,200+Math.floor(i/30)*15,3,3]);
return [(await medir(...linhas(2))).px,(await medir(...linhas(5))).px,(await medir(...linhas(6))).px,
(await medir(...linhas(20))).classe,(await medir(...linhas(20),...ciscos)).classe];})()`),[2,5,6,'C3','C3']);
await click('[data-modo="file"]');
// A ready sheet with two source files stores the finest stroke's position
// on the combined film, not its position within the second file.
assert.deepEqual(await evaluate(`(()=>{
const old=folhas,oldLayout=montagemLayout;
folhas=[{an:{traco:{px:9,classe:'C2',proofYFraction:0.2}}},
{an:{traco:{px:3,classe:'C1',proofYFraction:0.5}}}];
montagemLayout=null;
try{return tracoDoItem(null,{height_cm:100,placements:[
{source_index:0,y_cm:0,length_cm:50,rotation_degrees:0},
{source_index:1,y_cm:50,length_cm:50,rotation_degrees:0}]});}
finally{folhas=old;montagemLayout=oldLayout;}
})()`),{strokePx:3,strokeClass:'C1',strokeChoice:null,
proofSourceIndex:1,proofYFraction:0.75});
// Opening a product paints on the next frame; on a busy runner the check
// must wait for it rather than race it.
await waitFor(()=>evaluate(`!$('tipoEnvio').hidden`),'by-metre product open');
@@ -170,14 +206,13 @@ try{
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('4 GB')`),true,
'files beyond the 4 GB upload limit are rejected before browser analysis');
// 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.
// A PNG above the browser's ~32k-pixel height limit cannot be checked here:
// it is refused with a clear message instead of being accepted as 0 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]);
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:900*1048576});return sel([f]);})()`);
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})`),
{grande:true,dpi:300,alt:300,preview:false});
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].measurementError`),'tall sheet refused');
assert.equal(await evaluate(`folhas[0].measurementError.includes('PNG alto')`),true);
await evaluate(`folhas=[];pintaFolha()`);
await evaluate(`pickTipo('avulsa')`);
assert.equal(await evaluate('modo'),'avulsa');
@@ -295,13 +330,13 @@ try{
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.
// One price per product (Dropstar, 2026-10-23): the sheet is still graded
// internally, but the customer's screen no longer shows the /100 score.
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',
assert.deepEqual(await evaluate(`({unit:itemAtual.unit,total:itemAtual.total,hidden:!document.getElementById('cNota'),
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});
{unit:19.9,total:19.9,hidden: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);
@@ -340,13 +375,13 @@ try{
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');
// A ready sheet now offers the same acceptance as loose art (Dropstar,
// 2026-11-05): the dots may be part of the art; the customer can take them.
assert.deepEqual(await evaluate(`({box:!!document.querySelector('[data-residuo]'),
text:$('lista').textContent.includes('Li e concordo'),stopped:itemAtual===null})`),{box:true,text:true,stopped:true});
await evaluate(`(()=>{const el=document.querySelector('[data-residuo]');el.checked=true;
el.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await waitFor(()=>evaluate('itemAtual!==null'),'accepted residue lets the sheet through');
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');

View File

@@ -65,6 +65,11 @@ try{
// The check above can still pass on the page being replaced; wait for the new one's cards.
await waitFor(()=>site.eval(`!!document.querySelector('[data-modo="file"]') && document.readyState==='complete'`),'product cards after reload');
await site.click('[data-modo="file"]');
const treatmentCents = await site.eval('(async()=> (await dtfSessionReady).treatment_cents)()');
if (treatmentCents > 0) {
assert.equal(await site.eval(`!$('tratamentoBox').hidden`), true);
assert.equal(await site.eval(`$('tratamentoPreco').textContent`), 'R$ '+(treatmentCents/100).toFixed(2).replace('.',','));
}
// Each product has its own page; the home's parts are not on it.
assert.deepEqual(await site.eval(`({path:location.pathname,page:document.documentElement.dataset.rota,
cards:getComputedStyle($('cards')).display,cart:getComputedStyle($('carr')).display})`),
@@ -160,6 +165,13 @@ try{
await waitFor(()=>kanban.eval('!document.getElementById("app").hidden'),'Kanban sign-in');
assert.equal(await kanban.eval('sessionStorage.getItem("dtf-operator")'),null);
assert.equal(await kanban.eval('document.getElementById("password").value'),'');
await kanban.click('[data-tab="integrations"]');
await waitFor(()=>kanban.eval('document.querySelectorAll("#site-videos-list .siteVideoRow").length===6'),
'six video slots in Gestão');
assert.equal(await kanban.eval('document.querySelectorAll("#site-videos-list input[type=file]").length'),12);
await mkdir('output/local',{recursive:true});
await kanban.eval('document.getElementById("site-videos-panel").scrollIntoView()');
await kanban.screenshot('output/local/kanban-videos.png');
await kanban.click('[data-tab="quotes"]');
await waitFor(()=>kanban.eval('document.querySelectorAll("#quote-filters button").length===2'),'quote filters');
await kanban.eval('document.querySelectorAll("#quote-filters button")[1].click()');
@@ -205,8 +217,17 @@ try{
// Open the order's panel from its card, then click the real transition
// buttons there, including the rerender after each move.
await kanban.click('[data-tab="board"]');
assert.equal(await kanban.eval(`!!document.querySelector('[data-card="${oid}"] .card-open')`),true);
await kanban.click(`[data-card="${oid}"]`);
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel');
// The Prumo report is on the card before the designer opens the file.
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] .prumo')`),'Prumo report');
// No machine at payment (Dropstar, 2026-11-05): the pull chooses one.
await waitFor(()=>kanban.eval(`board.machines.some(m=>m.active&&m.products.includes('textil'))`),'a textile machine');
const machineId=await kanban.eval(`board.machines.find(m=>m.active&&m.products.includes('textil')).id`);
await kanban.eval(`(()=>{const s=document.querySelector('[data-order="${oid}"] select[aria-label="Máquina do pedido"]');
s.value=${JSON.stringify(machineId)};s.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').machine?.id===${JSON.stringify(machineId)}`),'machine chosen');
// Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão before Finalizado.
for(const [title,state] of [['Arte conferida','tra'],['Imprimindo','imp'],['Revisão','rev'],['Finalizado','fin']]){
if(state==='tra'){
@@ -219,7 +240,7 @@ try{
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 input=await kanban.call('DOM.querySelector',{nodeId:doc.root.nodeId,selector:`[data-order="${oid}"] [data-final-item]`});
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/final-300.png')]});
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 waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').version===1`),'final file approval');
@@ -229,10 +250,35 @@ try{
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);
}
if(state==='fin'){
// Above 1 m Finalizado needs the review photo (app/reviews.py). Take one
// with a canvas in the page and send it as the Revisor's dialog does.
const metres=await kanban.eval(`board.orders.find(o=>o.id==='${oid}').snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0)`);
if(metres>1){
await kanban.eval(`(async()=>{
const order=board.orders.find(o=>o.id==='${oid}');
const canvas=document.createElement('canvas');canvas.width=2000;canvas.height=1500;
const ctx=canvas.getContext('2d');ctx.fillStyle='#c04030';ctx.fillRect(0,0,2000,1500);
const blob=await new Promise(ok=>canvas.toBlob(ok,'image/jpeg',0.9));
const file=new File([blob],'revisao.jpg',{type:'image/jpeg'});
const uid=await dtfUpload(file,{api,startPath:'/orders/'+order.id+'/reviews/uploads',scope:'operator:review:'+order.id+':browser',progress:()=>{}});
await api('/orders/'+order.id+'/reviews',{upload_id:uid});
await load();
})()`);
await waitFor(()=>kanban.eval(`(board.orders.find(o=>o.id==='${oid}').reviews||[]).some(r=>r.kind==='photo')`),'review photo attached');
}
}
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 waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state);
if(state==='tra'){
// The file opens from the card itself, without first expanding the order.
await kanban.eval('closePanel()');
await kanban.click(`[data-card="${oid}"] .card-open`);
await waitFor(()=>kanban.eval(`!!document.querySelector('.viewer[open]')`),'file viewer from the card');
assert.equal(await kanban.eval(`$('drawer').hidden`),true);
await kanban.click('.viewer .vbtn.pri');
await kanban.click(`[data-card="${oid}"]`);
// 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);
@@ -268,7 +314,7 @@ try{
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'])
for(const name of ['1. Arte recebida','2. Arte conferida','3. Imprimindo','4. Revisão','5. Finalizado','Recibos','Revisões'])
assert.ok(tree.includes(name),name+' missing from '+tree.join(', '));
}
}

View File

@@ -0,0 +1,54 @@
"""Finalizado sorts by completion, including when an older order finishes last.
Run against the local stack: python3 -m tests.finished_order_test
"""
from urllib.parse import urlencode
from uuid import uuid4
from psycopg.types.json import Jsonb
from app.core import db
from tests.smoke_test import Client
def run():
client = Client()
owner = uuid4()
older_quote, newer_quote = uuid4(), uuid4()
older_order, newer_order = uuid4(), uuid4()
snapshot = {'customer': {'mail': 'finished-order@example.test', 'cnpj': '11222333000181'},
'items': [{'mode': 'file', 'billed_metres': '1.00'}]}
try:
with db.connect() as c:
for quote_id in (older_quote, newer_quote):
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft)
VALUES(%s,%s,%s,'finished-order-test',%s)''',
(quote_id, owner, uuid4(), Jsonb(snapshot)))
for order_id, quote_id, age in ((older_order, older_quote, 2), (newer_order, newer_quote, 1)):
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin,state,created_at)
VALUES(%s,%s,%s,%s,%s,'site','fin',now()-%s*interval '1 day')''',
(order_id, quote_id, owner, Jsonb(snapshot), Jsonb({'provider': 'teste'}), age))
# The older purchase finishes later; it must be first in Finalizado.
for order_id, minutes in ((older_order, 2), (newer_order, 1)):
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
VALUES(%s,'rev','fin','finished-order-test','',false,now()+%s*interval '1 minute')''',
(order_id, minutes))
board = client.call('/operator/board', operator=True)['orders']
finished = [o for o in board if o['state'] == 'fin']
ids = [o['id'] for o in finished]
assert ids.index(str(older_order)) < ids.index(str(newer_order)), ids
page = client.call('/operator/orders/finished?limit=2', operator=True)['orders']
assert [o['id'] for o in page] == [str(older_order), str(newer_order)], page
cursor = urlencode({'before_finished_at': page[0]['finished_at'], 'before_id': page[0]['id']})
next_page = client.call('/operator/orders/finished?' + cursor + '&limit=1', operator=True)['orders']
assert [o['id'] for o in next_page] == [str(newer_order)], next_page
print('PASS: Finalizado and its cursor use completion time, not order creation time')
finally:
with db.connect() as c:
c.execute('DELETE FROM dtf_local.movements WHERE order_id=ANY(%s)', ([older_order, newer_order],))
c.execute('DELETE FROM dtf_local.orders WHERE id=ANY(%s)', ([older_order, newer_order],))
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([older_quote, newer_quote],))
if __name__ == '__main__':
run()

BIN
tests/fixtures/final-300.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 B

View File

@@ -47,7 +47,8 @@ def session_upload(client, name):
def run():
tag = secrets.token_hex(4)
mail = f'kanban-{tag}@example.test'
cnpj = '11.222.333/0001-81'
cnpj_digits = '11222333' + f'{int(tag, 16) % 1000000:06d}'
cnpj = f'{cnpj_digits[:2]}.{cnpj_digits[2:5]}.{cnpj_digits[5:8]}/{cnpj_digits[8:12]}-{cnpj_digits[12:]}'
customer = {'mail': mail, 'cnpj': cnpj, 'zap': '(16) 98765-' + str(4000 + int(tag[:3], 16) % 1000)}
client = Client()
client.call('/session')
@@ -170,33 +171,33 @@ def run():
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']
assert day['stages']['tra'] == {'orders': 1, 'passages': 2, 'average_hours': 2.0}, day['stages']
assert day['stages']['rec']['average_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']
assert day['stages']['tra']['average_hours'] == 1.5, day['stages']
assert day['stages']['rec']['average_hours'] == 1.0, day['stages']
# The company's name from the registry: on the board, and found by the search.
from app import cnpj as registry
# Even after a failed try (the worker may have had no internet), a lookup stores the names.
registry.company('11222333000181', db.connect, transport=httpx.MockTransport(lambda request: httpx.Response(
registry.company(cnpj_digits, db.connect, transport=httpx.MockTransport(lambda request: httpx.Response(
200, json={'razao_social': f'KANBAN {tag} COMERCIO LTDA', 'nome_fantasia': f'Loja {tag}'})))
board = client.call('/operator/board', operator=True)
assert board['names']['11222333000181'] == {'legal': f'KANBAN {tag} COMERCIO LTDA', 'trade': f'Loja {tag}'}
assert board['names'][cnpj_digits] == {'legal': f'KANBAN {tag} COMERCIO LTDA', 'trade': f'Loja {tag}'}
found = client.call('/operator/search?' + urlencode({'q': f'loja {tag}'}), operator=True)
assert str(order_id) in {o['id'] for o in found['orders']}, found
# A failed lookup is kept and not repeated within the day.
with db.connect() as c:
c.execute("DELETE FROM dtf_local.cnpj_names WHERE cnpj='11222333000181'")
c.execute('DELETE FROM dtf_local.cnpj_names WHERE cnpj=%s', (cnpj_digits,))
registry.resolve(db.connect, limit=200, transport=httpx.MockTransport(lambda request: httpx.Response(503)))
with db.connect() as c:
row = c.execute("SELECT fetched_at,failed_at FROM dtf_local.cnpj_names WHERE cnpj='11222333000181'").fetchone()
row = c.execute('SELECT fetched_at,failed_at FROM dtf_local.cnpj_names WHERE cnpj=%s', (cnpj_digits,)).fetchone()
assert row['fetched_at'] is None and row['failed_at'] is not None
assert '11222333000181' not in registry.pending(c, 500)
assert cnpj_digits not in registry.pending(c, 500)
Client().call('/operator/stats', expected=401)
# "Fazer backup agora": recorded for the backup service, shown as asked.
with db.connect() as c:
@@ -216,7 +217,7 @@ def run():
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.uploads WHERE id=%s', (uid,))
c.execute("DELETE FROM dtf_local.cnpj_names WHERE cnpj='11222333000181'")
c.execute('DELETE FROM dtf_local.cnpj_names WHERE cnpj=%s', (cnpj_digits,))
if __name__ == '__main__':

View File

@@ -3,6 +3,8 @@
It empties the order tables, so it runs last. Run inside the API container:
python -m tests.launch_reset_test
"""
import tempfile
from pathlib import Path
from uuid import uuid4
from psycopg.types.json import Jsonb
@@ -37,6 +39,8 @@ def run():
with db.connect() as c:
assert c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (order,)).fetchone()
with db.connect() as c:
before_number = c.execute('SELECT COALESCE(max(number),0) AS n FROM dtf_local.orders').fetchone()['n']
lines.clear()
assert launch_reset.main(['--confirmar', 'APAGAR'], out=lines.append) == 0, lines
with db.connect() as c:
@@ -45,8 +49,8 @@ def run():
assert not c.execute('''SELECT 1 FROM dtf_local.uploads WHERE purged_at IS NULL
AND expires_at>now()''').fetchone()
assert c.execute('SELECT count(*) AS n FROM dtf_local.operators').fetchone()['n'] >= 1
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.
assert any('Apagado.' in line for line in lines) and 'continua de onde parou' in lines[-1], lines
# The numbering is not reset: DTF-1…DTF-15 already exist in Tiny.
with db.connect() as c:
quote = uuid4()
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
@@ -55,10 +59,25 @@ def run():
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
assert first > before_number, (first, before_number)
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')
# The Kanban folders: only the flow folders are emptied; Estampas stays.
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
for name in ('1. Arte recebida', '2. Arte conferida', '3. Imprimindo',
'4. Revisão', '5. Finalizado', 'Recibos', 'Revisões'):
(root / name).mkdir()
(root / name / 'card.txt').write_text('x')
(root / 'Estampas').mkdir()
(root / 'Estampas' / '1001.png').write_bytes(b'art')
lines.clear()
assert launch_reset.main(['--root', temp, '--confirmar', 'APAGAR'], out=lines.append) == 0, lines
for name in ('1. Arte recebida', '2. Arte conferida', '3. Imprimindo',
'4. Revisão', '5. Finalizado', 'Recibos', 'Revisões'):
assert list((root / name).iterdir()) == [], name
assert (root / 'Estampas' / '1001.png').read_bytes() == b'art'
print('PASS: launch cleanup refuses real payments, counts first, then removes test orders and quotes, keeping the numbering and the art library')
if __name__ == '__main__':

122
tests/machine_log_test.py Normal file
View File

@@ -0,0 +1,122 @@
"""The machine sheet against the local stack (Fase 2, front 1a).
Run inside the API container: python -m tests.machine_log_test
"""
from uuid import uuid4
from app.core import db
from tests.smoke_test import Client
from tests.users_test import PASSWORD, order_fixture
def final_stub(c, oid, owner):
uid = uuid4()
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,'machine-log-test.png',1,%s,'',true,now()+interval '1 day','clean')''',
(uid, owner, f'machine-log-test/{uid}'))
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,0,'final','machine log test','test')''', (uuid4(), oid, uid))
def run():
su = Client()
su.call('/session')
tag = uuid4().hex[:6]
machine = su.call('/operator/machines', {'name': f'Ficha {tag}', 'products': ['textil']},
operator=True)['id']
other = su.call('/operator/machines', {'name': f'Outra {tag}', 'products': ['textil']},
operator=True)['id']
email = f'ficha-{tag}@example.test'
su.call('/operator/users', {'name': 'Ficha', 'email': email, 'role': 'operador', 'password': PASSWORD},
operator=True)
op = Client()
op.call('/session')
op.call('/operator/login', {'email': email, 'password': PASSWORD})
op.call('/operator/me/machine', {'machine_id': machine})
owner = uuid4()
# A clean starts the cycle, then two sheets leave Imprimindo for Revisão:
# 12 m since the last clean, above the 10 m limit.
op.call(f'/operator/machines/{machine}/entries', {'kind': 'event', 'item': 'clean'})
printed = []
with db.connect() as c:
for _ in range(2):
_, oid = order_fixture(c, owner, 'file', metres='6')
c.execute("UPDATE dtf_local.orders SET state='imp', machine_id=%s WHERE id=%s", (machine, oid))
printed.append(str(oid))
for oid in printed:
op.call(f'/operator/orders/{oid}/move', {'state': 'rev', 'version': 0})
board = op.call('/operator/board')
row = next(m for m in board['machines'] if m['id'] == machine)
clean = [a for a in row['alerts'] if a['key'] == 'clean']
assert clean and clean[0]['blocking'], row['alerts']
assert clean[0]['text'].endswith('limpe antes do próximo arquivo'), clean[0]
# The next card into Imprimindo is refused before the server moves it.
with db.connect() as c:
_, first = order_fixture(c, owner, 'file')
final_stub(c, first, owner)
c.execute("UPDATE dtf_local.orders SET state='tra' WHERE id=%s", (first,))
refused = op.call(f'/operator/orders/{first}/move', {'state': 'imp', 'version': 0}, expected=409)
assert refused['detail'].startswith('Antes do próximo arquivo: '), refused
# "Adiar uma vez" lets exactly one card through; the next is refused again,
# and the same alert cannot be postponed twice in one cycle.
op.call(f'/operator/machines/{machine}/alerts/clean/snooze', {})
op.call(f'/operator/orders/{first}/move', {'state': 'imp', 'version': 0})
with db.connect() as c:
_, second = order_fixture(c, owner, 'file')
final_stub(c, second, owner)
c.execute("UPDATE dtf_local.orders SET state='tra' WHERE id=%s", (second,))
refused = op.call(f'/operator/orders/{second}/move', {'state': 'imp', 'version': 0}, expected=409)
assert 'Antes do próximo arquivo' in refused['detail'], refused
op.call(f'/operator/machines/{machine}/alerts/clean/snooze', {}, expected=409)
# Recording the clean resets the counter and releases the queue.
op.call(f'/operator/machines/{machine}/entries', {'kind': 'event', 'item': 'clean', 'from_alert': True})
sheet = op.call(f'/operator/machines/{machine}/sheet')
assert float(sheet['counters']['clean']['metres']) == 0, sheet['counters']
assert not [a for a in sheet['alerts'] if a['key'] == 'clean'], sheet['alerts']
op.call(f'/operator/orders/{second}/move', {'state': 'imp', 'version': 0})
# A supply without cost inherits the last cost of that same item.
first_supply = op.call(f'/operator/machines/{machine}/entries',
{'kind': 'supply', 'item': 'ink_w', 'quantity': 1, 'cost_cents': 18000})
assert first_supply['cost_cents'] == 18000, first_supply
second_supply = op.call(f'/operator/machines/{machine}/entries',
{'kind': 'supply', 'item': 'ink_w', 'quantity': 0.5})
assert second_supply['cost_cents'] == 18000, second_supply
# An operator enters only on the machine of their session; Gestão anywhere.
op.call(f'/operator/machines/{other}/entries', {'kind': 'event', 'item': 'clean'}, expected=403)
gestao_email = f'gestao-{tag}@example.test'
su.call('/operator/users', {'name': 'Gestão', 'email': gestao_email, 'role': 'gestao',
'password': PASSWORD}, operator=True)
gestao = Client()
gestao.call('/session')
gestao.call('/operator/login', {'email': gestao_email, 'password': PASSWORD})
ges = gestao.call(f'/operator/machines/{other}/entries',
{'kind': 'supply', 'item': 'film', 'quantity': 1, 'cost_cents': 0})
assert ges['cost_cents'] == 0, ges
# Preço, data e mínimos are saved and the sheet returns them.
su.call(f'/operator/machines/{machine}/sheet',
{'price_cents': 1234500, 'installed_on': '2026-01-15', 'minimums': {'ink_w': 5}},
operator=True)
sheet = op.call(f'/operator/machines/{machine}/sheet')
assert sheet['machine']['price_cents'] == 1234500, sheet['machine']
assert sheet['machine']['installed_on'] == '2026-01-15', sheet['machine']
assert float(sheet['minimums']['ink_w']) == 5, sheet['minimums']
assert sheet['catalog']['supplies']['ink_w'] == ['Tinta branca', 'L'], sheet['catalog']
su.call(f'/operator/machines/{machine}/sheet',
{'price_cents': 1234500, 'installed_on': '2026-01-15', 'minimums': {'ink_w': None}},
operator=True)
assert 'ink_w' not in op.call(f'/operator/machines/{machine}/sheet')['minimums']
print('PASS: clean alert blocks and releases the pull, one snooze per cycle, '
'supply cost inheritance, operator scope and the machine data')
if __name__ == '__main__':
run()

View File

@@ -0,0 +1,64 @@
"""A card has no machine until pull, and a proof gives its machine to its parent."""
from uuid import uuid4
from psycopg.types.json import Jsonb
from app.core import db
from tests.smoke_test import Client
from tests.users_test import order_fixture
def final_stub(c, oid, owner):
uid = uuid4()
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,'machine-test.png',1,%s,'',true,now()+interval '1 day','clean')''',
(uid, owner, f'machine-test/{uid}'))
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,0,'final','machine test','test')''', (uuid4(), oid, uid))
def run():
client = Client()
client.call('/session')
tag = uuid4().hex[:6]
machine = client.call('/operator/machines', {'name': f'Pull {tag}', 'products': ['textil']}, operator=True)['id']
other = client.call('/operator/machines', {'name': f'Other {tag}', 'products': ['textil']}, operator=True)['id']
owner = uuid4()
with db.connect() as c:
_, oid = order_fixture(c, owner, 'file')
final_stub(c, oid, owner)
c.execute("UPDATE dtf_local.orders SET state='tra' WHERE id=%s", (oid,))
board = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == str(oid))
assert board['machine'] is None, board['machine']
moved = client.call(f'/operator/orders/{oid}/move', {'state': 'imp', 'version': 0,
'machine_id': machine}, operator=True)
assert str(moved['machine_id']) == machine
shown = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == str(oid))
assert shown['machine_pulled']['by'] and shown['machine_pulled']['at'], shown
assert client.call(f'/operator/orders/{oid}/history', operator=True)[-1]['machine'] == f'Pull {tag}'
with db.connect() as c:
_, parent = order_fixture(c, owner, 'file')
parent_row = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (parent,)).fetchone()
child = uuid4()
c.execute('''INSERT INTO dtf_local.orders(id,owner,snapshot,payment,origin,parent_id,state)
VALUES(%s,%s,%s,%s,'site',%s,'tra')''',
(child, owner, Jsonb({**parent_row['snapshot'], 'proof_of': 1}),
Jsonb({'provider': 'prova'}), parent))
final_stub(c, child, owner)
shown = {o['id']: o for o in client.call('/operator/board', operator=True)['orders']}
assert shown[str(parent)]['machine'] is None and shown[str(child)]['machine'] is None
client.call(f'/operator/orders/{child}/move', {'state': 'imp', 'version': 0,
'machine_id': machine}, operator=True)
shown = {o['id']: o for o in client.call('/operator/board', operator=True)['orders']}
assert shown[str(parent)]['machine']['id'] == machine == shown[str(child)]['machine']['id']
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (child,))
client.call(f'/operator/orders/{child}/proof-answer', {'result': 'ok'}, operator=True)
locked = client.call(f'/operator/orders/{parent}/machine', {'machine_id': other}, operator=True, expected=409)
assert 'mesma máquina' in locked['detail'], locked
print('PASS: no machine at creation; pull records operator and time; proof and parent share one machine')
if __name__ == '__main__':
run()

View File

@@ -0,0 +1,92 @@
"""The machine month numbers against the local stack (Fase 2, front 1b).
Run inside the API container: python -m tests.machine_stats_test
"""
from datetime import datetime, timedelta, timezone
from uuid import uuid4
from psycopg.types.json import Jsonb
from app.core import db
from tests.smoke_test import Client
from tests.users_test import PASSWORD, order_fixture
def paid_order(c, owner, machine, metres, total_cents):
"""A real (not test) paid order already in Imprimindo on the machine, with
its item's total_cents set for what it sold."""
_, oid = order_fixture(c, owner, 'file', metres=metres)
snapshot = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()['snapshot']
snapshot['items'][0]['total_cents'] = total_cents
c.execute('''UPDATE dtf_local.orders SET snapshot=%s, payment=%s, state='imp', machine_id=%s
WHERE id=%s''', (Jsonb(snapshot), Jsonb({'provider': 'fake', 'id': str(oid)}), machine, oid))
return str(oid)
def current_month():
return datetime.now(timezone(timedelta(hours=-3))).strftime('%Y-%m')
def run():
su = Client()
su.call('/session')
tag = uuid4().hex[:6]
machine = su.call('/operator/machines', {'name': f'Números {tag}', 'products': ['textil']},
operator=True)['id']
email = f'numeros-{tag}@example.test'
su.call('/operator/users', {'name': 'Números', 'email': email, 'role': 'operador', 'password': PASSWORD},
operator=True)
op = Client()
op.call('/session')
op.call('/operator/login', {'email': email, 'password': PASSWORD})
op.call('/operator/me/machine', {'machine_id': machine})
owner = uuid4()
# What went in this month: one film roll, one litre of white ink and a part.
op.call(f'/operator/machines/{machine}/entries',
{'kind': 'supply', 'item': 'film', 'quantity': 1, 'cost_cents': 30000})
op.call(f'/operator/machines/{machine}/entries',
{'kind': 'supply', 'item': 'ink_w', 'quantity': 1, 'cost_cents': 18000})
op.call(f'/operator/machines/{machine}/entries',
{'kind': 'part', 'item': 'cap', 'cost_cents': 5000, 'serial': f'cap-{tag}'})
with db.connect() as c:
order = paid_order(c, owner, machine, '6', 9000)
op.call(f'/operator/orders/{order}/move', {'state': 'rev', 'version': 0})
month = current_month()
data = su.call('/operator/stats/machines?month=' + month, operator=True)
row = next((m for m in data['machines'] if m['id'] == machine), None)
assert row, data
month_row = row['month']
assert abs(float(month_row['printed_metres']) - 6) < 0.01, month_row
assert abs(float(month_row['metres_per_roll']) - 6) < 0.01, month_row
assert month_row['supplies_cents'] == 48000, month_row
assert month_row['parts_cents'] == 5000, month_row
assert month_row['sold_cents'] > 0, month_row
assert month_row['contribution_cents'] == month_row['sold_cents'] - 53000, month_row
assert row['total']['roi_pct'] is None, row['total']
# Without a purchase price the return is blank; with it, it is a number.
su.call(f'/operator/machines/{machine}/sheet',
{'price_cents': 1234500, 'installed_on': '2020-01-01', 'minimums': {}}, operator=True)
data = su.call('/operator/stats/machines?month=' + month, operator=True)
row = next((m for m in data['machines'] if m['id'] == machine), None)
assert row['total']['roi_pct'] is not None, row['total']
# Números is not the operator's: only management, the seller and finance read it.
designer_email = f'desenho-{tag}@example.test'
su.call('/operator/users', {'name': 'Desenho', 'email': designer_email, 'role': 'designer',
'password': PASSWORD}, operator=True)
designer = Client()
designer.call('/session')
designer.call('/operator/login', {'email': designer_email, 'password': PASSWORD})
designer.call('/operator/stats/machines?month=' + month, expected=403)
# A malformed month is refused before any query.
su.call('/operator/stats/machines?month=2026-13', operator=True, expected=422)
print('PASS: machine month printed, consumption, costs, sold, contribution, ROI, '
'operator refused and a malformed month rejected')
if __name__ == '__main__':
run()

View File

@@ -153,7 +153,8 @@ def run():
assert tester.call('/operator/quotes/' + test_quote + '/test-order', {}, operator=True)['id'] == order['id']
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'])
from tests.smoke_test import final_png_bytes
final = upload_bytes(tester, final_png_bytes('test order'), name='TEST-ORDER-FINAL.png', 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']

View File

@@ -9,30 +9,42 @@ Kanban until someone records what was done.
Run inside the API container (it needs Pillow): python -m tests.print_file_test
"""
import io
import re
import time
from urllib.request import urlopen
from uuid import uuid4
from PIL import Image
from app.core import db
from tests.payment_test import deliver
from tests.smoke_test import Client, approved_quote as approval, upload_bytes
PT_PER_CM = 72 / 2.54
PX_PER_CM = 300 / 2.54
def px(cm):
return int(round(cm * PX_PER_CM))
def download_png(client, upload_id):
link = client.call('/operator/uploads/' + str(upload_id) + '/download', operator=True)
with urlopen(link['url'], timeout=30) as response:
image = Image.open(io.BytesIO(response.read()))
assert image.format == 'PNG' and image.mode == 'RGBA', (image.format, image.mode)
return image
CUSTOMER = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'print-test@example.test'}
def artwork(kind='PNG'):
image = Image.new('RGBA', (600, 300), (0, 0, 0, 0))
for x in range(40, 560):
for y in range(40, 260):
image = Image.new('RGBA', (1600, 800), (0, 0, 0, 0))
for x in range(40, 1560):
for y in range(40, 760):
image.putpixel((x, y), (220, 30, 60, 255))
out = io.BytesIO()
if kind == 'PDF':
image.convert('RGB').save(out, 'PDF', resolution=72)
else:
image.save(out, kind)
image.save(out, kind, dpi=(300, 300))
return out.getvalue()
@@ -81,16 +93,29 @@ def run():
uid = upload_bytes(client, artwork(), name='LOCAL-PRINT-TEST.png')
order = paid_order(client, loose_item(uid))
order, row = wait_print(client, order['id'], 'ready')
assert row['detail']['placements'] == 2 and row['detail']['min_dpi'] == round(600 / (20 / 2.54))
link = client.call('/operator/uploads/' + str(row['upload_id']) + '/download', operator=True)
with urlopen(link['url'], timeout=30) as response:
pdf = response.read()
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())
# The layout's 10 cm and the 1,5 cm footer band, outside the billed length.
assert abs(width - 57 * PT_PER_CM) < 0.01 and abs(height - 11.5 * PT_PER_CM) < 0.01, (width, height)
assert row['detail']['placements'] == 2 and row['detail']['min_dpi'] == round(1600 / (20 / 2.54))
assert any('Prumo levou' in line for line in order['prumo']), order['prumo']
# A 300 DPI PNG on a transparent background (item 13): the layout's 10 cm
# and the 1,5 cm footer band, outside the billed length.
film = download_png(client, row['upload_id'])
assert film.size == (px(57), px(10) + px(1.5)), film.size
assert [p['name'] for p in row['parts']] == ['DTF-%d-item-1.png' % order['number']], row['parts']
for copy in range(2):
assert film.getpixel((px(20 * copy + 10), px(5))) == (220, 30, 60, 255), copy
assert film.getpixel((px(50), px(5)))[3] == 0
assert row['detail']['footer'].startswith('DROPSTAR · Pedido DTF-%d · Item 1/1 · ' % order['number']), row['detail']
print('PASS: paid order generated a 57 x 10 cm print file with both copies and its footer')
print('PASS: paid order generated a 57 x 10 cm PNG print file with both copies and its footer')
# Item 7: "Abrir e conferir" gets the file in pieces, the first of which is
# the top of the film, then the original.
view = client.call('/operator/orders/' + order['id'] + '/view', operator=True)['files']
assert [f['name'] for f in view] == ['DTF-%d-item-1.png' % order['number'], 'Original'], view
manifest = view[0]['manifest']
assert (manifest['width'], manifest['height']) == film.size and manifest['levels'][0]['strips'] >= 1, manifest
with urlopen(manifest['urls'][0][0], timeout=30) as response:
strip = Image.open(io.BytesIO(response.read()))
assert strip.width == film.width and strip.getpixel((px(10), px(3))) == (220, 30, 60, 255)
print('PASS: the viewer gets the print file in pieces')
# The automatic folder, downloading on arrival, gets the generated file
# before anyone approves it; at the queue only, it does not.
@@ -117,8 +142,12 @@ def run():
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)
# it to Finalizado later), and no one else's. The pull chooses the machine.
tag = uuid4().hex[:6]
machine = client.call('/operator/machines', {'name': f'Hot {tag}', 'products': ['textil']},
operator=True)['id']
client.call('/operator/orders/' + oid + '/move', {'state': 'imp', 'version': version,
'machine_id': machine}, 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
@@ -140,16 +169,163 @@ def run():
'note': 'again'}, operator=True, expected=409)
print('PASS: generated file approved as final without re-uploading; order queued for printing')
# A single-page PDF is placed as a vector form, not rasterised.
# Item 10: printing, the file goes once into its machine's hot folder for
# its class; Flexi taking it is reported; leaving Imprimindo withdraws
# what Flexi did not take.
try:
# No class measured or chosen: the part waits for one.
assert not [p for p in client.call('/operator/queue/hot', {}, operator=True)['write'] if p['order'] == oid]
client.call('/operator/orders/' + oid + '/contraction', {'item_index': 0, 'value': 'C2'}, operator=True)
hot = client.call('/operator/queue/hot', {}, operator=True)
due = [p for p in hot['write'] if p['order'] == oid]
assert hot['folder'] == '3. Imprimindo' and [(p['folder'], p['name']) for p in due] == \
[(f'Hot {tag}/C2', 'DTF-%d-item-1.png' % order['number'])], hot
# Claimed by this computer only: asked again, nobody else gets it.
assert not [p for p in client.call('/operator/queue/hot', {}, operator=True)['write'] if p['order'] == oid]
part = due[0]['id']
assert client.call(f'/operator/queue/hot/{part}', {'state': 'written'}, operator=True)['ok']
client.call('/operator/orders/' + oid + '/contraction', {'item_index': 0, 'value': 'C1'}, operator=True,
expected=409)
watch = client.call('/operator/queue/hot', {}, operator=True)['watch']
assert [p['id'] for p in watch if p['order'] == oid] == [part], watch
assert client.call(f'/operator/queue/hot/{part}', {'state': 'consumed'}, operator=True)['ok']
assert not client.call(f'/operator/queue/hot/{part}', {'state': 'consumed'}, operator=True)['ok']
board = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == oid)
assert board['hot'] == {'parts': 1, 'taken': 1, 'waiting': 0}, board['hot']
print('PASS: the printing file goes once into its machine\'s hot folder for its class')
finally:
client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False},
operator=True)
# A single-page PDF is drawn from its vectors at 300 DPI.
pdf_upload = upload_bytes(client, artwork('PDF'), name='LOCAL-PRINT-TEST.pdf')
pdf_order = paid_order(client, loose_item(pdf_upload))
_, pdf_row = wait_print(client, pdf_order['id'], 'ready')
assert pdf_row['detail']['vector_sources'] == 1 and pdf_row['detail']['min_dpi'] is None, pdf_row
link = client.call('/operator/uploads/' + str(pdf_row['upload_id']) + '/download', operator=True)
with urlopen(link['url'], timeout=30) as response:
generated = response.read()
assert b'/Subtype /Form' in generated or b'/Subtype/Form' in generated
print('PASS: PDF artwork generated as a vector print file')
drawn = download_png(client, pdf_row['upload_id'])
red = drawn.getpixel((px(10), px(5)))
assert red[3] == 255 and red[0] > 200 and red[1] < 60, red
print('PASS: PDF artwork drawn into the PNG print file at 300 DPI')
# The proof card (Dropstar, 2026-10-30 and 2026-11-03): an order above
# 10 m gets a child card "Prova"; the order waits outside the queue until
# the card in Revisão gets its answer.
# Artwork the generator refuses at once, so no 10 m file is drawn.
unread = upload_bytes(client, b'LOCAL PRINT TEST - NOT AN IMAGE', name='LOCAL-PROOF-TEST.cdr')
long = loose_item(unread, copies=1)
long['metres'] = '10.5'
long['proof_y_fraction'] = '0.8'
long['production'] = {**long['production'], 'height_cm': 1050,
'placements': [{**long['production']['placements'][0], 'y_cm': 1040}]}
parent = paid_order(client, long)
board = client.call('/operator/board', operator=True)['orders']
mine = next(o for o in board if o['id'] == parent['id'])
card = next(o for o in board if o['id'] == mine['proof_card']['id'])
assert card['proof_parent']['number'] == parent['number'] and card['state'] == 'rec', card
assert card['snapshot']['proof_of'] == parent['number'] and card['payment'] == {'provider': 'prova'}
assert float(card['snapshot']['items'][0]['proof_y_fraction']) == 0.8, card['snapshot']['items'][0]
# The proof answer is the customer contact: the old "Aguardando contato"
# mark must not survive it (item 0.1).
with db.connect() as c:
c.execute("""UPDATE dtf_local.orders SET contact_since=now(), contact_by='Site',
contact_note='Prova pedida no site' WHERE id=%s""", (parent['id'],))
c.execute('INSERT INTO dtf_local.contact_waits(order_id,started_at) VALUES(%s,now())', (parent['id'],))
with db.connect() as c:
assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key LIKE %s', (card['id'] + '%',)).fetchone()
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (card['id'],))
final = str(uuid4())
held = client.call('/operator/orders/' + parent['id'] + '/final-files',
{'version': parent['version'], 'files': [{'item_index': 0, 'upload_id': final}],
'note': 'Local proof test final'}, operator=True, expected=409)
assert 'Aguardando prova' in held['detail'], held
for path, body in [('/move', {'state': 'tra', 'version': parent['version']}),
('/contraction', {'item_index': 0, 'value': 'C1'}),
('/machine', {'machine_id': None}),
('/queue', {'after': card['id']})]:
held = client.call('/operator/orders/' + parent['id'] + path, body, operator=True, expected=409)
assert 'Aguardando prova' in held['detail'], (path, held)
client.call('/operator/orders/' + card['id'] + '/move', {'state': 'fin', 'version': card['version']},
operator=True, expected=409)
# Reprovada needs its reason; the order goes back to Arte recebida.
client.call('/operator/orders/' + card['id'] + '/proof-answer', {'result': 'rejected', 'reason': 'x'},
operator=True, expected=422)
client.call('/operator/orders/' + card['id'] + '/proof-answer',
{'result': 'rejected', 'reason': 'Cor do fundo errada'}, operator=True)
client.call('/operator/orders/' + card['id'] + '/proof-answer', {'result': 'ok'}, operator=True, expected=409)
board = client.call('/operator/board', operator=True)['orders']
mine = next(o for o in board if o['id'] == parent['id'])
assert mine['state'] == 'rec' and mine['proof_card']['proof_result'] == 'rejected', mine['proof_card']
assert mine['proof_card']['proof_reason'] == 'Cor do fundo errada'
assert not mine.get('contact_since'), mine
with db.connect() as c:
assert c.execute('SELECT ended_at FROM dtf_local.contact_waits WHERE order_id=%s',
(parent['id'],)).fetchone()['ended_at']
assert not [o for o in board if o['id'] == card['id']], 'an answered proof card leaves the board'
# Rejection releases the parent for corrected artwork, until a new proof card is opened.
final = upload_bytes(client, artwork(), name='LOCAL-PROOF-FINAL.png', order_id=parent['id'])
version = client.call('/operator/orders/' + parent['id'] + '/final-files',
{'version': mine['version'], 'files': [{'item_index': 0, 'upload_id': final}],
'note': 'Local proof test final'}, operator=True)['version']
# A new card, and Prova OK lets the order into the queue.
again = client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True)
client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True, expected=409)
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (again['id'],))
client.call('/operator/orders/' + again['id'] + '/proof-answer', {'result': 'ok'}, operator=True)
mine = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == parent['id'])
assert mine['proof_ok_at'] and mine['proof_card']['proof_result'] == 'ok' and mine['state'] == 'tra', mine
print('PASS: an order with a proof waits for its proof card, which is answered OK or rejected in Revisão')
# Prova OK is the parent's check: the full print file Prumo already made
# becomes the parent final and the parent enters Arte conferida (0.1).
readable = upload_bytes(client, artwork(), name='LOCAL-PROOF-REAL.png')
long = loose_item(readable, copies=1)
parent = paid_order(client, long)
# A proof card for a small order, as the panel can open one; the parent
# file is only 10 cm tall, so this test does not draw a 10 m film.
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{proof}','true') WHERE id=%s",
(parent['id'],))
client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True)
board = client.call('/operator/board', operator=True)['orders']
mine = next(o for o in board if o['id'] == parent['id'])
card = next(o for o in board if o['id'] == mine['proof_card']['id'])
wait_print(client, parent['id'], 'ready')
wait_print(client, card['id'], 'ready')
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (card['id'],))
client.call('/operator/orders/' + card['id'] + '/proof-answer', {'result': 'ok'}, operator=True)
mine = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == parent['id'])
assert mine['state'] == 'tra' and mine['final_items'] == [0], mine
assert mine['proof_ok_at'] and mine['proof_card']['proof_result'] == 'ok', mine
with db.connect() as c:
final = c.execute('''SELECT note,created_by FROM dtf_local.order_files
WHERE order_id=%s AND kind='final' AND active''', (parent['id'],)).fetchone()
assert final['created_by'] == 'Prumo' and 'prova' in final['note'].lower(), final
print('PASS: Prova OK turns Prumo\'s full file into the parent final and queues it')
# A CDR cannot be decoded by the worker. The designer prepares the full
# parent PNG, then the worker automatically cuts the child's proof from it.
manual_source = upload_bytes(client, b'LOCAL PRINT TEST - NOT AN IMAGE', name='MANUAL-PROOF.cdr')
manual_parent = paid_order(client, loose_item(manual_source, copies=1))
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{proof}','true') WHERE id=%s",
(manual_parent['id'],))
manual_child = client.call('/operator/orders/' + manual_parent['id'] + '/proof-card', {}, operator=True)
wait_print(client, manual_child['id'], 'manual')
retry = client.call('/operator/orders/' + manual_child['id'] + '/print-files', {}, operator=True, expected=409)
assert 'pedido pai' in retry['detail'], retry
prepared = upload_bytes(client, artwork(), name='MANUAL-PROOF-FINAL.png', order_id=manual_parent['id'])
client.call('/operator/orders/' + manual_parent['id'] + '/final-files',
{'version': manual_parent['version'],
'files': [{'item_index': 0, 'upload_id': prepared}],
'note': 'PNG completo para a prova'}, operator=True)
client.call('/operator/orders/' + manual_child['id'] + '/print-files', {}, operator=True)
wait_print(client, manual_child['id'], 'ready')
proof_card = next(o for o in client.call('/operator/board', operator=True)['orders']
if o['id'] == manual_child['id'])
assert proof_card['final_items'] == [0], proof_card
print('PASS: manual parent PNG produces the child proof automatically')
# A customer cannot see or reuse another order's generated file.
other = Client()
@@ -209,7 +385,7 @@ def run():
finished = client.call('/operator/orders/finished?limit=1', operator=True)
if finished['orders']:
last = finished['orders'][-1]
client.call('/operator/orders/finished?before_created_at=' + last['created_at'].replace('+', '%2B')
client.call('/operator/orders/finished?before_finished_at=' + last['finished_at'].replace('+', '%2B')
+ '&before_id=' + last['id'], operator=True)
print('PASS: send log, payment history and finished orders page and filter')

View File

@@ -18,7 +18,12 @@ def run():
with connect() as c:
c.execute('INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,expires_at) VALUES(%s,%s,%s,%s,%s,%s,true,%s)',
(uid,uuid4(),'LOCAL-RETENTION-TEST.txt',len(b'LOCAL RETENTION TEST'),key,upload,expiry))
cleanup()
# Cleanup takes 50 at a time, oldest first: the suites before this one
# leave their own expired files ahead of the fixture.
for _ in range(100):
cleanup()
with connect() as c:
if c.execute('SELECT purged_at FROM dtf_local.uploads WHERE id=%s',(ids[0],)).fetchone()['purged_at']:break
with connect() as c:
assert c.execute('SELECT purged_at FROM dtf_local.uploads WHERE id=%s',(ids[0],)).fetchone()['purged_at']
assert not c.execute('SELECT purged_at FROM dtf_local.uploads WHERE id=%s',(ids[1],)).fetchone()['purged_at']

123
tests/review_media_test.py Normal file
View File

@@ -0,0 +1,123 @@
"""The review photo or video attached to an order in Revisão (Fase 2, front 2).
Run against the local stack:
SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost python -m tests.review_media_test
"""
from io import BytesIO
from urllib.request import Request, urlopen
from uuid import uuid4
from PIL import Image
from tests.smoke_test import (Client, approved_quote, final_png_bytes, item_spec, review_photo,
upload_bytes, wait_scan)
def jpeg(width, height):
out = BytesIO()
Image.new('RGB', (width, height), (190, 60, 50)).save(out, 'JPEG', quality=80)
return out.getvalue()
def run():
customer = Client()
customer.call('/session')
original = upload_bytes(customer, b'LOCAL REVIEW ORIGINAL')
item = item_spec('file', '1.01', 0, original)
profile = {'cnpj': '11222333000181', 'zap': '11999999999',
'mail': 'review-' + uuid4().hex[:8] + '@example.test'}
quote = customer.call('/quotes', {'request_key': str(uuid4()), 'customer': profile,
'items': [item], 'freight': {'service': 'pickup'}})
approved_quote(customer, quote, [item])
order = customer.call('/orders/dev-paid', {'quote_id': quote['id']})
oid, number = order['id'], order['number']
final = upload_bytes(customer, final_png_bytes('review final'), name='LOCAL-REVIEW-FINAL.png', order_id=oid)
version = customer.call('/operator/orders/' + oid + '/final-files',
{'version': 0, 'note': 'Conferido',
'files': [{'item_index': 0, 'upload_id': final}]}, operator=True)['version']
machine = None
def move(state, version):
nonlocal machine
body = {'state': state, 'version': version, 'reason': ''}
if state == 'imp':
if machine is None:
machine = customer.call('/operator/machines',
{'name': 'Review ' + uuid4().hex[:6], 'products': ['textil']},
operator=True)['id']
body['machine_id'] = machine
return customer.call('/operator/orders/' + oid + '/move', body, operator=True)['version']
for state in ('tra', 'imp', 'rev'):
version = move(state, version)
def upload_raw(name, content):
start = customer.call('/operator/orders/' + oid + '/reviews/uploads',
{'name': name, 'size': len(content)}, operator=True)
uid = start['id']
url = customer.call('/operator/uploads/' + uid + '/parts/1', {}, operator=True)['url']
with urlopen(Request(url, data=content, method='PUT'), timeout=30) as response:
assert response.status == 200
customer.call('/operator/uploads/' + uid + '/complete', {}, operator=True)
wait_scan(customer, uid, operator=True)
return uid
def add_raw(uid, expected=200):
return customer.call('/operator/orders/' + oid + '/reviews', {'upload_id': uid},
operator=True, expected=expected)
# Above 1 m without a photo the order does not reach Finalizado.
customer.call('/operator/orders/' + oid + '/move', {'state': 'fin', 'version': version},
operator=True, expected=409)
# A photo below 1600 px on the longer side is refused.
small = upload_raw('LOCAL-SMALL.jpg', jpeg(800, 600))
add_raw(small, expected=422)
# The extension must match the content: a PNG named .jpg is refused.
fake = upload_raw('LOCAL-FAKE.jpg', final_png_bytes('fake'))
add_raw(fake, expected=422)
# A real 2000x1500 JPEG becomes DTF-<n>-revisao-1.jpg.
row = review_photo(customer, oid)
assert row['seq'] == 1 and row['kind'] == 'photo', row
assert row['name'] == 'DTF-%d-revisao-1.jpg' % number, row
board = customer.call('/operator/board', operator=True)
saved = next(o for o in board['orders'] if o['id'] == oid)
assert [(r['seq'], r['kind'], r['name']) for r in saved['reviews']] == [(1, 'photo', row['name'])], saved['reviews']
folder = customer.call('/operator/queue/folder', {'early': True}, operator=True)
entry = next(r for r in folder['reviews'] if r['upload_id'] == row['upload_id'])
assert entry['name'] == row['name'] and entry['order'] == oid and entry['number'] == number, entry
# The customer sees no photo while the order is still in Revisão.
assert customer.call('/customer/orders/' + oid)['reviews'] == []
# A second review can be removed only while the order is in Revisão.
second = review_photo(customer, oid)
assert second['seq'] == 2, second
customer.call('/operator/orders/' + oid + '/reviews/' + str(second['id']) + '/remove', {},
operator=True)
# With the photo the order finishes, and the customer then sees it.
version = move('fin', version)
detail = customer.call('/customer/orders/' + oid)
assert detail['state'] == 'fin'
assert [(r['id'], r['name']) for r in detail['reviews']] == [(row['id'], row['name'])], detail['reviews']
view = customer.call('/customer/orders/' + oid + '/reviews/' + str(row['id']) + '/view')
assert view['kind'] == 'photo' and view['name'] == row['name']
with urlopen(view['url'], timeout=30) as response:
assert Image.open(BytesIO(response.read())).size == (2000, 1500)
# Once Finalizado, a review can no longer be removed.
customer.call('/operator/orders/' + oid + '/reviews/' + str(row['id']) + '/remove', {},
operator=True, expected=409)
print('PASS: review photo upload, signature and size checks, the 1 m rule, the folder and the customer view')
if __name__ == '__main__':
run()

74
tests/site_video_test.py Normal file
View File

@@ -0,0 +1,74 @@
"""Published site videos retain their file and expose same-origin captions.
Run against the local stack with an internal S3 public endpoint:
SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost python -m tests.site_video_test
"""
from urllib.request import Request, urlopen
from app.core import db
from app.runtime import storage
from tests.smoke_test import BASE, Client, with_host, wait_scan
VIDEO = b'\x00\x00\x00\x18ftypisom\x00\x00\x00\x00isomiso2'
CAPTIONS = b'WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nTeste de legenda.\n'
def upload(operator, name, content):
start = operator.call('/operator/site-videos/uploads', {'name': name, 'size': len(content)})
uid = start['id']
url = operator.call(f'/operator/uploads/{uid}/parts/1', {})['url']
with urlopen(Request(url, data=content, method='PUT'), timeout=30) as response:
assert response.status == 200
operator.call(f'/operator/uploads/{uid}/complete', {})
wait_scan(operator, uid, operator=True)
return uid
def run():
client = Client()
client.call('/session')
with db.connect() as c:
assert not c.execute("SELECT 1 FROM dtf_local.site_videos WHERE id='sala'").fetchone(), \
'The isolated test catalog entry is already configured'
ids = []
keys = []
try:
client.call('/operator/site-videos/sala', {'enabled': True}, expected=401)
operator = client.operator_client or Client()
# Client.call(operator=True) signs in and forwards to its own client.
client.call('/operator/site-videos', operator=True)
operator = client.operator_client
video = upload(operator, 'LOCAL-VIDEO.mp4', VIDEO)
captions = upload(operator, 'LOCAL-VIDEO.vtt', CAPTIONS)
ids = [video, captions]
operator.call('/operator/site-videos/sala', {'upload_id': video,
'captions_id': captions, 'product': 'file', 'enabled': True})
published = client.call('/site/videos')['videos']
entry = next(row for row in published if row['id'] == 'sala')
assert entry['product'] == 'file'
assert entry['captions'] == '/api/site/videos/sala/captions'
with urlopen(entry['src'], timeout=30) as response:
assert response.read() == VIDEO
with urlopen(Request(BASE + entry['captions'], headers=with_host()), timeout=30) as response:
assert response.headers['Content-Type'].startswith('text/vtt')
assert response.read() == CAPTIONS
operator.call('/operator/site-videos/sala', {'upload_id': video,
'captions_id': captions, 'product': 'file', 'enabled': False})
assert not any(row['id'] == 'sala' for row in client.call('/site/videos')['videos'])
print('PASS: Gestão publishes a scanned video, signed media and same-origin VTT; hiding removes it from the Site')
finally:
with db.connect() as c:
row = c.execute("DELETE FROM dtf_local.site_videos WHERE id='sala' RETURNING video_key,captions_key").fetchone()
if row:
keys.extend(key for key in row.values() if key)
if ids:
sources = c.execute('DELETE FROM dtf_local.uploads WHERE id=ANY(%s) RETURNING object_key',
(ids,)).fetchall()
keys.extend(row['object_key'] for row in sources)
for key in keys:
storage.client.delete_object(Bucket=storage.bucket, Key=key)
if __name__ == '__main__':
run()

View File

@@ -7,12 +7,25 @@ import hashlib
import http.cookiejar
import json
import os
import struct
import zlib
from pathlib import Path
import time
from urllib.error import HTTPError
from urllib.request import build_opener, HTTPCookieProcessor, Request, urlopen
from uuid import uuid4
def final_png_bytes(label='final'):
"""A tiny real RGBA PNG tagged 300 DPI for operator final-file tests."""
def chunk(kind, body):
return struct.pack('>I', len(body)) + kind + body + struct.pack('>I', zlib.crc32(kind + body) & 0xffffffff)
red = hashlib.sha256(label.encode()).digest()[0]
row = b'\x00' + bytes((red, 30, 60, 255, 0, 0, 0, 0))
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 2, 1, 8, 6, 0, 0, 0)) +
chunk(b'pHYs', struct.pack('>IIB', 11811, 11811, 1)) +
chunk(b'IDAT', zlib.compress(row)) + chunk(b'IEND', b''))
if Path('.env').exists():
for line in Path('.env').read_text().splitlines():
if line.strip() and not line.startswith('#') and '=' in line:
@@ -92,6 +105,26 @@ def upload_bytes(client, content, name='LOCAL-TEST.cdr', order_id=None, expected
wait_scan(client,uid,operator,expected_scan)
return uid
def review_photo(client, order_id):
"""A 2000x1500 JPEG attached as the order's review photo, in Revisão.
The same transport site_video_test uses: start the operator upload, PUT the
single part, complete it, wait for the scan, then POST the review."""
from io import BytesIO
from PIL import Image
out=BytesIO()
Image.new('RGB',(2000,1500),(200,80,40)).save(out,'JPEG',quality=85)
content=out.getvalue()
start=client.call('/operator/orders/'+order_id+'/reviews/uploads',
{'name':'revisao.jpg','size':len(content)},operator=True)
uid=start['id']
url=client.call('/operator/uploads/'+uid+'/parts/1',{},operator=True)['url']
with urlopen(Request(url,data=content,method='PUT'),timeout=30) as response:
assert response.status==200
client.call('/operator/uploads/'+uid+'/complete',{},operator=True)
wait_scan(client,uid,operator=True)
return client.call('/operator/orders/'+order_id+'/reviews',{'upload_id':uid},operator=True)
def item_spec(mode, metres, grade, uid):
film_width=27 if mode in ('uvfile','uv') else 57
length_cm=float(metres)*100
@@ -197,14 +230,17 @@ def run():
# A cart the Site priced is approved at once and can be paid straight away,
# at the server's own prices; no operator can then change it.
# The server works the grade out from the file: this PNG is 6059 px across
# 57 cm, 270 DPI, which is grade 90.
# 57 cm, 270 DPI, which is grade 100 under the 200 DPI clean threshold.
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
graded=upload_bytes(client,png,name='arte-270dpi.png')
low_png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(3366).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
low=upload_bytes(client,low_png,name='arte-150dpi.png')
small={**draft,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,graded)]}
auto=client.call('/quotes',small)
assert auto['status']=='approved'
seen=client.call('/quotes/'+auto['id'])
assert seen['auto_approved'] and seen['review_reason'] is None
assert isinstance(seen.get('prumo'), list) and seen['prumo'], seen.get('prumo')
assert seen['approved']['total_cents']==6132+int(os.environ.get('MOCK_FREIGHT_CENTS','1500'))
assert client.call('/quotes',small)['status']=='approved'
client.call('/operator/quotes/'+auto['id']+'/approve',{'items':small['items']},operator=True,expected=409)
@@ -214,6 +250,29 @@ def run():
kept=client.call('/quotes',accepted)
assert kept['status']=='approved'
assert client.call('/quotes/'+kept['id'])['approved']['items'][0]['residue_accepted']==3
# The thinnest stroke and its contraction class (item 9) stay with the item too.
stroked={**small,'request_key':str(uuid4()),'items':[{**item_spec('avulsa','2.75',90,graded),'stroke_px':6,'stroke_class':'C2'}]}
client.call('/quotes',{**stroked,'items':[{**stroked['items'][0],'stroke_class':'C4'}]},expected=422)
held_stroke=client.call('/quotes',stroked)
assert held_stroke['status']=='approved'
stroke_item=client.call('/quotes/'+held_stroke['id'])['approved']['items'][0]
assert (stroke_item['stroke_px'],stroke_item['stroke_class'])==(6,'C2'), stroke_item
# A sheet with fine lines and solid areas (item 16) keeps the customer's choice.
mixed={**stroked,'request_key':str(uuid4()),'items':[{**stroked['items'][0],'stroke_choice':'client_c3'}]}
client.call('/quotes',{**mixed,'items':[{**mixed['items'][0],'stroke_choice':'both'}]},expected=422)
mixed_item=client.call('/quotes/'+client.call('/quotes',mixed)['id'])['approved']['items'][0]
assert mixed_item['stroke_choice']=='client_c3', mixed_item
# Loose art split by stroke (item 17): each sheet is an item, and the pair
# has one 1 m minimum, on its first sheet.
part=lambda metres,n,mode='avulsa':{**item_spec(mode,metres,90,graded),'split':{'group':'f0','part':n,'of':2}}
split={**small,'request_key':str(uuid4()),'items':[part('0.3',1),part('0.15',2)]}
client.call('/quotes',{**split,'items':split['items'][:1]},expected=422)
client.call('/quotes',{**split,'items':[part('0.3',1),part('0.15',1)]},expected=422)
client.call('/quotes',{**split,'items':[part('0.3',1,'file'),part('0.15',2,'file')]},expected=422)
held_split=client.call('/quotes',split)
assert held_split['status']=='approved', held_split
sheets=client.call('/quotes/'+held_split['id'])['approved']['items']
assert [(i['billed_metres'],i['total_cents'],i['split']['part']) for i in sheets]==[('0.8',1752,1),('0.2',438,2)], sheets
# 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}
@@ -222,9 +281,10 @@ def run():
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:
# 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)]})
low_item={**item_spec('avulsa','2.75',100,low),'quality_status':'warning','quality_acknowledged':True}
inflated=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[low_item]})
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 (75)'
unchecked=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,uid)]})
assert client.call('/quotes/'+unchecked['id'])['review_reason']=='Nota não conferida no servidor'
print('PASS: priced carts are approved at checkout; large or inconsistent ones wait for review')
@@ -239,21 +299,34 @@ def run():
board=client.call('/operator/board',operator=True)
assert len([o for o in board['orders'] if o['quote_id']==qid])==1
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)
version=0
# Above 10 m the proof comes first: the parent cannot move at all until
# Prova OK on its proof card in Revisão (item 0.1).
held=client.call('/operator/orders/'+oid+'/move',{'state':'cor','version':0},operator=True,expected=409)
assert 'Aguardando prova' in held['detail'], held
card=next(o for o in board['orders'] if o['id']==oid)['proof_card']
from app.core import db
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s",(card['id'],))
client.call('/operator/orders/'+card['id']+'/proof-answer',{'result':'ok'},operator=True)
version=next(o for o in client.call('/operator/board',operator=True)['orders'] if o['id']==oid)['version']
client.call('/operator/orders/'+oid+'/move',{'state':'cor','version':version},operator=True,expected=422)
# Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão comes before Finalizado.
machine=None
for state in ('cor','rec','tra','imp','rev','fin'):
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,final_png_bytes(str(i)),name=f'LOCAL-FINAL-{i}.png',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)
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)
body={'state':state,'version':version,'reason':'Local test correction' if state=='cor' else ''}
if state=='imp':
if machine is None:
machine=client.call('/operator/machines',{'name':'Smoke '+uuid4().hex[:6],'products':['textil']},operator=True)['id']
body['machine_id']=machine
# Above 1 m Finalizado needs the review photo (app/reviews.py).
if state=='fin':review_photo(client,oid)
moved=client.call('/operator/orders/'+oid+'/move',body,operator=True)
version+=1;assert moved['version']==version
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
@@ -264,6 +337,7 @@ def run():
client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version},operator=True,expected=409)
back=client.call('/operator/orders/'+oid+'/move',{'state':'rev','version':version,'reason':'Movido por engano'},operator=True)
assert back['state']=='rev';version+=1
review_photo(client,oid)
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':version},operator=True);version+=1
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']

View File

@@ -0,0 +1,61 @@
"""Acceptable time per stage: Gestão edits it, the board marks the late cards."""
from uuid import uuid4
from psycopg.types.json import Jsonb
from app.core import db
from tests.smoke_test import Client
from tests.users_test import order_fixture
def run():
client = Client()
client.call('/session')
defaults = [{'state': 'rec', 'hours': 2, 'responsible': 'Designer'},
{'state': 'tra', 'hours': 6, 'responsible': 'Operador'},
{'state': 'imp', 'hours': 4, 'responsible': 'Operador'},
{'state': 'rev', 'hours': 2, 'responsible': 'Revisor'},
{'state': 'fin', 'hours': 72, 'responsible': 'Atendimento'}]
seen = client.call('/operator/stage-limits', operator=True)['limits']
assert {row['state'] for row in seen} == {'rec', 'tra', 'imp', 'rev', 'fin'}, seen
client.call('/operator/stage-limits', {'limits': defaults}, operator=True)
owner = uuid4()
with db.connect() as c:
quote, order = order_fixture(c, owner, 'file')
c.execute("""UPDATE dtf_local.orders SET created_at=now()-interval '3 hours',
payment=%s WHERE id=%s""",
(Jsonb({'provider': 'mercadopago', 'id': str(order)}), order))
try:
board = client.call('/operator/board', operator=True)
mine = next(o for o in board['orders'] if o['id'] == str(order))
assert mine['late'] == 'warn' and mine['limit_hours'] == 2, mine
assert board['stage_limits']['rec'] == {'hours': 2.0, 'responsible': 'Designer'}, board['stage_limits']
faster = [row for row in defaults if row['state'] != 'rec'] + [
{'state': 'rec', 'hours': 1, 'responsible': 'Designer'}]
client.call('/operator/stage-limits', {'limits': faster}, operator=True)
board = client.call('/operator/board', operator=True)
mine = next(o for o in board['orders'] if o['id'] == str(order))
assert mine['late'] == 'bad' and mine['limit_hours'] == 1, mine
# A paid treatment gives Art received its extra hours (front 5).
with db.connect() as c:
c.execute('UPDATE dtf_local.orders SET snapshot = snapshot || %s WHERE id=%s',
(Jsonb({'treatment': {'cents': 990, 'hours': 3}}), order))
board = client.call('/operator/board', operator=True)
mine = next(o for o in board['orders'] if o['id'] == str(order))
assert mine['late'] is None and mine['limit_hours'] == 4, mine
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET snapshot = snapshot - 'treatment' WHERE id=%s", (order,))
board = client.call('/operator/board', operator=True)
mine = next(o for o in board['orders'] if o['id'] == str(order))
assert mine['late'] == 'bad' and mine['limit_hours'] == 1, mine
print('PASS: stage limits are editable, a card past the limit is yellow/red, '
'and a paid treatment adds its hours')
finally:
client.call('/operator/stage-limits', {'limits': defaults}, operator=True)
with db.connect() as c:
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
if __name__ == '__main__':
run()

View File

@@ -5,6 +5,7 @@ Runs where Pillow and pikepdf are installed (the API image).
import io
import tempfile
import unittest
from unittest import mock
import pikepdf
from PIL import Image
@@ -26,6 +27,25 @@ class FakeFiles:
return grade_check.pdf_dpi(handle.name)
class CountingStorage:
"""A storage that counts every read, keyed by object_key as the real one."""
def __init__(self, blobs):
self.bucket = 'bucket'
self.blobs = blobs
self.downloads = 0
self.heads = 0
self.client = self
def get_object(self, Bucket, Key, Range=None):
self.heads += 1
return {'Body': io.BytesIO(self.blobs[Key][:grade_check.HEAD_BYTES])}
def download_fileobj(self, bucket, key, handle):
self.downloads += 1
handle.write(self.blobs[key])
def encoded(fmt, size, **options):
out = io.BytesIO()
Image.new('RGBA' if fmt in ('PNG', 'WEBP') else 'RGB', size, (200, 30, 30)).save(out, fmt, **options)
@@ -62,25 +82,56 @@ class GradeCheckTests(unittest.TestCase):
self.assertEqual(grade_check.pdf_dpi(handle.name), 300)
def test_grades_follow_the_site(self):
# 57 cm is 22.44 in: 6059 px is 270 DPI, grade 90; 3366 px is 150 DPI, grade 50.
# 57 cm is 22.44 in: the new clean threshold is 200 DPI.
files = FakeFiles({'a.png': encoded('PNG', (6059, 100)), 'b.jpg': encoded('JPEG', (3366, 100)),
'tall.png': encoded('PNG', (100, 2362)), 'x.cdr': b'CDR'})
rows = {n: {'name': n, 'size': 1} for n in files.blobs}
# A sheet takes the worst sheet's grade.
self.assertEqual(grade_check.item_grade(files, item('sheet', 0, [('a.png', 57, 0)]), rows), 90)
self.assertEqual(grade_check.item_grade(files, item('sheet', 0, [('a.png', 57, 0), ('b.jpg', 57, 0)]), rows), 50)
self.assertEqual(grade_check.item_grade(files, item('sheet', 0, [('a.png', 57, 0)]), rows), 100)
self.assertEqual(grade_check.item_grade(files, item('sheet', 0, [('a.png', 57, 0), ('b.jpg', 57, 0)]), rows), 75)
# Artworks average; a rotated one is measured along its height.
self.assertEqual(grade_check.item_grade(files, item('artwork', 0, [('a.png', 57, 0), ('b.jpg', 57, 0)]), rows), 70)
self.assertEqual(grade_check.item_grade(files, item('artwork', 0, [('a.png', 57, 0), ('b.jpg', 57, 0)]), rows), 88)
self.assertEqual(grade_check.item_grade(files, item('artwork', 0, [('tall.png', 20, 90)]), rows), 100)
self.assertIsNone(grade_check.item_grade(files, item('sheet', 0, [('x.cdr', 57, 0)]), rows))
# What the cart claims is checked, with a point or two of rounding.
claim = lambda g, src: grade_check.mismatch(files, [item('sheet', g, src)], rows)
self.assertIsNone(claim(90, [('a.png', 57, 0)]))
self.assertIsNone(claim(92, [('a.png', 57, 0)]))
self.assertEqual(claim(100, [('a.png', 57, 0)]), 'Nota 100 maior que a do arquivo (90)')
self.assertIsNone(claim(100, [('a.png', 57, 0)]))
self.assertIsNone(claim(77, [('b.jpg', 57, 0)]))
self.assertEqual(claim(100, [('b.jpg', 57, 0)]), 'Nota 100 maior que a do arquivo (75)')
self.assertEqual(claim(40, [('x.cdr', 57, 0)]), 'Nota não conferida no servidor')
self.assertIsNone(claim(0, [('x.cdr', 57, 0)]))
def test_a_file_is_read_once_per_quote(self):
storage = CountingStorage({'k.pdf': b'%PDF-1.4 test', 'k.png': encoded('PNG', (100, 50))})
files = grade_check.Files(storage)
pdf_row = {'object_key': 'k.pdf', 'size': 15, 'name': 'a.pdf'}
with mock.patch.object(grade_check, 'pdf_dpi', return_value=300):
self.assertEqual(files.pdf_dpi(pdf_row), 300)
self.assertEqual(files.pdf_dpi(pdf_row), 300)
self.assertEqual(storage.downloads, 1)
png_row = {'object_key': 'k.png', 'size': 1, 'name': 'a.png'}
self.assertEqual(files.head(png_row)[:8], b'\x89PNG\r\n\x1a\n')
self.assertEqual(files.head(png_row)[:8], b'\x89PNG\r\n\x1a\n')
self.assertEqual(storage.heads, 1)
def test_resolution_boundaries_and_consent(self):
width = lambda dpi: int(dpi * 57 / 2.54) + 1
files = FakeFiles({f'{dpi}.png': encoded('PNG', (width(dpi), 20))
for dpi in (95, 96, 199, 200, 287, 293)})
rows = {name: {'name': name, 'size': 1} for name in files.blobs}
def issue(dpi, status='ok', acknowledged=False):
spec = item('sheet', 0, [(f'{dpi}.png', 57, 0)])
spec.update(quality_status=status, quality_acknowledged=acknowledged)
return grade_check.resolution_issue(files, [spec], rows)
self.assertIn('abaixo do mínimo', issue(95))
self.assertIn('confirme a ressalva', issue(96))
self.assertIn('confirme a ressalva', issue(199))
self.assertIsNone(issue(96, 'warning', True))
self.assertIsNone(issue(199, 'warning', True))
for dpi in (200, 287, 293):
self.assertIsNone(issue(dpi), dpi)
self.assertEqual(grade_check.grade_of(dpi), 100)
if __name__ == '__main__':
unittest.main()

View File

@@ -1,34 +1,9 @@
"""Large sheets: when the original is its own print file, and the format check."""
"""Large files: the format check. A large PNG or PDF sheet is read band by band
(app/printpng.py), so it no longer passes as its own print file."""
import unittest
from app.printjobs import whole_sheet
from app.scanning import check_large, format_matches, real_name
ROW = {'id': 'u1', 'name': 'folha.png', 'size': 3 * 1024 ** 3, 'scan_state': 'clean',
'purged_at': None, 'expired': False}
def sheet(**changes):
source = {'kind': 'sheet', 'width_cm': 57, 'length_cm': 500, 'copies': 1}
place = {'x_cm': 0, 'y_cm': 0, 'rotation_degrees': 0, 'mirrored': False}
for key, value in changes.items():
(source if key in source else place)[key] = value
return {'uploads': ['u1'], 'production': {'film_width_cm': 57, 'sources': [source], 'placements': [place]}}
class WholeSheetTest(unittest.TestCase):
def test_a_finished_sheet_placed_whole_is_its_own_print_file(self):
self.assertIs(whole_sheet(sheet(), {'u1': ROW}), ROW)
def test_anything_else_is_prepared_by_hand(self):
for changes in ({'copies': 2}, {'kind': 'artwork'}, {'rotation_degrees': 90}, {'mirrored': True},
{'x_cm': 1}, {'width_cm': 50}):
with self.subTest(changes=changes):
self.assertIsNone(whole_sheet(sheet(**changes), {'u1': ROW}))
self.assertIsNone(whole_sheet(sheet(), {'u1': {**ROW, 'name': 'folha.cdr'}}))
self.assertIsNone(whole_sheet(sheet(), {'u1': {**ROW, 'scan_state': 'pending'}}))
self.assertIsNone(whole_sheet(sheet(), {'u1': {**ROW, 'expired': True}}))
class FormatTest(unittest.TestCase):
def test_bytes_must_match_the_name(self):

50
tests/test_machine_log.py Normal file
View File

@@ -0,0 +1,50 @@
"""The machine sheet's pure calculations (Fase 2, front 1a), without a database."""
import unittest
from decimal import Decimal
from app.machine_log import (ALIGN_AFTER_FILM_METRES, CLEAN_EVERY_METRES, estimate,
one_decimal, supply_low)
class EstimateTest(unittest.TestCase):
def test_two_entries_give_an_estimate(self):
value = estimate([Decimal('1'), Decimal('2')], [Decimal('10')], Decimal('5'), Decimal('0.5'))
self.assertEqual(value['per_metre'], Decimal('0.2'))
self.assertEqual(value['stock'], Decimal('1.0'))
self.assertEqual(value['metres_left'], Decimal('5'))
self.assertEqual(value['minimum'], Decimal('0.5'))
self.assertFalse(supply_low(value))
def test_one_entry_has_no_estimate(self):
self.assertIsNone(estimate([Decimal('1')], [], Decimal('10'), None))
def test_an_interval_without_film_has_no_estimate(self):
self.assertIsNone(estimate([Decimal('1'), Decimal('1')], [Decimal('0')], Decimal('0'), None))
def test_the_minimum_reached_is_an_alert(self):
# 0.1 per metre, one litre refilled on average, nine metres later:
# 0.1 L left, below the machine's 1.5 L minimum.
value = estimate([Decimal('1'), Decimal('1')], [Decimal('10')], Decimal('9'), Decimal('1.5'))
self.assertEqual(value['stock'], Decimal('0.1'))
self.assertTrue(supply_low(value))
def test_only_the_last_intervals_are_averaged(self):
# Four intervals; SUPPLY_INTERVALS is three, so the 100 m one is ignored.
value = estimate([Decimal('1'), Decimal('1'), Decimal('3'), Decimal('3'), Decimal('3')],
[Decimal('100'), Decimal('10'), Decimal('10'), Decimal('10')], Decimal('0'), None)
self.assertEqual(value['per_metre'], Decimal('0.3'))
def test_the_thresholds_are_the_documented_ones(self):
self.assertEqual(CLEAN_EVERY_METRES, Decimal('10'))
self.assertEqual(ALIGN_AFTER_FILM_METRES, Decimal('20'))
class AlertTextTest(unittest.TestCase):
def test_one_decimal_uses_a_comma(self):
self.assertEqual(one_decimal(Decimal('10.44')), '10,4')
self.assertEqual(one_decimal(Decimal('3')), '3,0')
self.assertEqual(one_decimal(Decimal('19.86')), '19,9')
if __name__ == '__main__':
unittest.main()

View File

@@ -0,0 +1,78 @@
"""The machine month's pure calculations (Fase 2, front 1b), without a database."""
import unittest
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from app.machine_stats import month_bounds, ratios
SAO_PAULO = ZoneInfo('America/Sao_Paulo')
class MonthBoundsTest(unittest.TestCase):
def test_a_valid_month(self):
start, end = month_bounds('2026-11')
self.assertEqual((start.year, start.month, start.day), (2026, 11, 1))
self.assertEqual((start.hour, start.minute, start.second), (0, 0, 0))
self.assertEqual(start.utcoffset(), timedelta(hours=-3))
self.assertEqual(start.tzinfo, SAO_PAULO)
self.assertEqual((end.year, end.month, end.day), (2026, 12, 1))
def test_the_year_turns_over(self):
start, end = month_bounds('2026-12')
self.assertEqual((start.year, start.month), (2026, 12))
self.assertEqual((end.year, end.month, end.day), (2027, 1, 1))
def test_a_malformed_month_is_invalid(self):
for month in ('2026-13', '2026-1', 'novembro', '2026-11-05', ''):
with self.subTest(month=month):
with self.assertRaises(ValueError):
month_bounds(month)
def test_none_is_the_current_month(self):
now = datetime.now(SAO_PAULO)
start, end = month_bounds(None)
self.assertEqual((start.year, start.month), (now.year, now.month))
class RatiosTest(unittest.TestCase):
def test_zero_or_unknown_divisors_are_none(self):
value = ratios(0, hours_running=0, supplies_cents=100, parts_cents=50,
rolls=0, inks={'ink_c': 1}, powder=0, price_cents=1000,
contribution_cents=200, months=10)
self.assertIsNone(value['metres_per_hour'])
self.assertIsNone(value['metres_per_roll'])
self.assertIsNone(value['ink_per_100m']['ink_c'])
self.assertIsNone(value['powder_g_per_100m'])
self.assertIsNone(value['supplies_per_metre_cents'])
self.assertIsNone(value['parts_per_metre_cents'])
self.assertIsNone(value['total_per_metre_cents'])
self.assertEqual(value['roi_pct'], 20.0)
def test_no_price_leaves_the_return_blank(self):
value = ratios(0, contribution_cents=500, installed_parts_cents=100, months=5)
self.assertIsNone(value['roi_pct'])
self.assertIsNone(value['payback_months'])
def test_the_known_ratios(self):
value = ratios(100, hours_running=10, supplies_cents=10000, parts_cents=5000,
rolls=2, inks={'ink_c': 1}, powder=1, price_cents=100000,
contribution_cents=30000, installed_parts_cents=20000, months=10)
self.assertEqual(value['metres_per_hour'], 10.0)
self.assertEqual(value['metres_per_roll'], 50.0)
self.assertEqual(value['ink_per_100m']['ink_c'], 1.0)
self.assertEqual(value['powder_g_per_100m'], 1000.0)
self.assertEqual(value['supplies_per_metre_cents'], 100)
self.assertEqual(value['parts_per_metre_cents'], 50)
self.assertEqual(value['total_per_metre_cents'], 150)
self.assertEqual(value['roi_pct'], 25.0)
self.assertEqual(value['payback_months'], 30.0)
def test_a_negative_average_has_no_payback(self):
value = ratios(100, price_cents=100000, contribution_cents=-1000,
installed_parts_cents=0, months=10)
self.assertEqual(value['roi_pct'], -1.0)
self.assertIsNone(value['payback_months'])
if __name__ == '__main__':
unittest.main()

View File

@@ -1,9 +1,11 @@
"""Run from repository root: python3 -m unittest tests.test_pricing -v."""
import json
import os
from pathlib import Path
from unittest.mock import patch
import subprocess
import unittest
from app.core.pricing import is_manual, price, PRICES
from app.core.pricing import is_manual, price, PRICES, treatment_cents
class PricingTests(unittest.TestCase):
def test_every_length_against_actual_site_javascript(self):
@@ -63,6 +65,15 @@ class PricingTests(unittest.TestCase):
# Loose artwork is assembled by the Site; it never pays this.
self.assertFalse(is_manual(item('artwork', 'customer'), {'u1': 'arte.cdr'}))
def test_treatment_is_optional_and_configured_by_the_environment(self):
with patch.dict(os.environ, {'TREATMENT_CENTS': '990'}):
self.assertEqual(treatment_cents(), 990)
with patch.dict(os.environ, {'TREATMENT_CENTS': '0'}):
self.assertEqual(treatment_cents(), 0)
with patch.dict(os.environ, {'TREATMENT_CENTS': '-1'}):
with self.assertRaises(ValueError):
treatment_cents()
def test_invalid_inputs(self):
for value in ('0','-1','NaN','Infinity','12001'):
with self.assertRaises(ValueError):price('file',value,90)

176
tests/test_printpng.py Normal file
View File

@@ -0,0 +1,176 @@
"""The PNG print file (item 13): 300 DPI, transparent, written and read in bands.
Runs in the API image (Pillow, pikepdf, pypdfium2).
"""
import io
import os
import tempfile
import unittest
from unittest import mock
from PIL import Image
from app import printpng
from app.printpng import PngRows, PngWriter, part_cuts, px, render
from tests.test_printfile import BLUE, GREEN, RED, YELLOW, item, placement, quadrants, source
def pattern(width, height, mode='RGBA'):
"""Rows that differ from each other, so every PNG filter gets used."""
image = Image.new('RGBA', (width, height))
image.putdata([((x * 7 + y * 3) % 256, (x * y) % 256, (y * 11) % 256, 255 if (x + y) % 5 else 0)
for y in range(height) for x in range(width)])
return image if mode == 'RGBA' else image.convert(mode)
class PngStreamTests(unittest.TestCase):
def test_rows_read_in_bands_match_the_whole_image(self):
with tempfile.TemporaryDirectory() as folder:
for mode in ('RGBA', 'RGB', 'L', 'LA', 'P'):
image = pattern(61, 47, mode)
path = os.path.join(folder, mode + '.png')
image.save(path, transparency=3) if mode == 'P' else image.save(path)
reader = PngRows(path)
bands = []
while (band := reader.band(10)) is not None:
bands.append(band.convert('RGBA'))
reader.close()
whole = Image.new('RGBA', image.size)
top = 0
for band in bands:
whole.paste(band, (0, top))
top += band.height
self.assertEqual(top, 47, mode)
self.assertEqual(whole.tobytes(), Image.open(path).convert('RGBA').tobytes(), mode)
def test_bands_written_make_one_png(self):
image = pattern(53, 70)
out = io.BytesIO()
writer = PngWriter(out, 53, 70)
for top in range(0, 70, 13):
writer.band(image.crop((0, top, 53, min(70, top + 13))))
writer.close()
out.seek(0)
written = Image.open(out)
self.assertEqual([round(v) for v in written.info.get('dpi')], [300, 300])
self.assertEqual(written.convert('RGBA').tobytes(), image.tobytes())
class PyramidTests(unittest.TestCase):
def test_strips_rebuild_the_film_at_each_level(self):
from app import printtiles
image = pattern(90, 1300)
strips = {}
with mock.patch.object(printtiles, 'STRIP_ROWS', 64), mock.patch.object(printtiles, 'SMALLEST_ROWS', 200):
pyramid = printtiles.Pyramid(90, 1300, lambda level, index, data: strips.setdefault(level, []).append(data))
for top in range(0, 1300, 100):
pyramid.band(image.crop((0, top, 90, min(1300, top + 100))))
manifest = pyramid.close()
self.assertEqual(len(manifest['levels']), 4) # 1300, 650, 325, 163 rows
for level, info in enumerate(manifest['levels']):
pieces = [Image.open(io.BytesIO(data)) for data in strips[level]]
self.assertEqual(len(pieces), info['strips'])
self.assertEqual(sum(p.height for p in pieces), info['height'], level)
self.assertTrue(all(p.width == info['width'] for p in pieces), level)
# Level 0 is the film itself.
whole = Image.new('RGBA', (90, 1300))
top = 0
for data in strips[0]:
piece = Image.open(io.BytesIO(data))
whole.paste(piece, (0, top))
top += piece.height
self.assertEqual(whole.tobytes(), image.tobytes())
class PngRenderTests(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
self.addCleanup(self.dir.cleanup)
def save(self, image, name):
path = os.path.join(self.dir.name, name)
image.save(path)
return path
def render(self, spec, paths, footer=None, part_cm=None):
out = os.path.join(self.dir.name, 'out')
os.makedirs(out, exist_ok=True)
files = {i: (path, os.path.basename(path)) for i, path in enumerate(paths)}
return render(spec, files, out, 'DTF-7-item-1', footer=footer, part_cm=part_cm)
def test_a_sheet_is_the_film_at_300_dpi_with_the_footer_below(self):
# 1 x 0,5 cm at 300 DPI: 118 x 59 px, on the 57 cm film.
art = quadrants(118, 59, alpha=True)
spec = item([placement(0, 0, 1, 0.5)], [source(1, 0.5)], 0.5)
for stream in (False, True):
with mock.patch.object(printpng, 'STREAM_ABOVE_PIXELS', 0 if stream else 10 ** 9):
parts, detail = self.render(spec, [self.save(art, 'sheet.png')], footer='DROPSTAR · Pedido DTF-7')
self.assertEqual([name for _, name in parts], ['DTF-7-item-1.png'])
film = Image.open(parts[0][0])
self.assertEqual(film.mode, 'RGBA')
self.assertEqual(film.size, (px(57), 59 + px(1.5)))
self.assertEqual(film.crop((0, 0, 118, 59)).tobytes(), art.tobytes(), stream)
# Transparent beside the art; the footer has ink of its own.
self.assertEqual(film.getpixel((300, 10))[3], 0)
self.assertGreater(film.crop((0, 59, film.width, film.height)).getextrema()[3][1], 0)
self.assertEqual(detail['format'], 'png')
def test_loose_art_is_turned_and_mirrored_like_the_site(self):
art = quadrants(80, 40, alpha=True)
# 80 x 40 px at 300 DPI is 6,773 x 3,387 cm; placed turned 90 degrees.
w, h = 80 / printpng.PX_PER_CM, 40 / printpng.PX_PER_CM
spec = item([placement(1, 1, h, w, rotation=90), placement(10, 1, w, h, mirrored=True, copy=1)],
[source(w, h, copies=2)], 10)
parts, _ = self.render(spec, [self.save(art, 'art.png')])
film = Image.open(parts[0][0]).convert('RGBA')
x, y = px(1), px(1)
# Turned clockwise: the top-left red goes to the top-right.
self.assertEqual(film.getpixel((x + 30, y + 10))[:3], RED)
self.assertEqual(film.getpixel((x + 10, y + 10))[:3], BLUE)
# Mirrored: green on the left.
mx = px(10)
self.assertEqual(film.getpixel((mx + 10, y + 10))[:3], GREEN)
self.assertEqual(film.getpixel((mx + 70, y + 30))[:3], BLUE)
def test_long_films_leave_as_parts_cut_between_pieces(self):
art = quadrants(118, 118, alpha=True)
placements = [placement(0, 11 * i, 10, 10, copy=i) for i in range(4)]
spec = item(placements, [source(10, 10, copies=4)], 43)
# Parts of up to 25 cm: the cut falls in the gap after the second piece, at 21 cm.
self.assertEqual([float(c) for c in part_cuts(spec['production'], 25)], [0, 21, 43])
parts, detail = self.render(spec, [self.save(art, 'art.png')], footer='DROPSTAR · Pedido DTF-7', part_cm=25)
self.assertEqual([name for _, name in parts], ['DTF-7-item-1-p1.png', 'DTF-7-item-1-p2.png'])
first, second = (Image.open(path) for path, _ in parts)
self.assertEqual(first.height, px(21) + px(1.5))
self.assertEqual(second.height, px(43) - px(21) + px(1.5))
self.assertEqual(second.convert('RGBA').getpixel((10, px(22) - px(21) + 5))[:3], RED)
self.assertEqual([p['name'] for p in detail['parts']], ['DTF-7-item-1-p1.png', 'DTF-7-item-1-p2.png'])
def test_pieces_for_the_viewer_come_with_the_file(self):
art = quadrants(118, 59, alpha=True)
spec = item([placement(0, 0, 1, 0.5)], [source(1, 0.5)], 0.5)
parts, detail = render(spec, {0: (self.save(art, 'art.png'), 'art.png')},
self.dir.name, 'DTF-7-item-1', footer='DROPSTAR · Pedido DTF-7', tiles=True)
tiles = detail['parts'][0]['tiles']
self.assertEqual((tiles['width'], tiles['height']), Image.open(parts[0][0]).size)
first = Image.open(os.path.join(self.dir.name, 'tiles', 'DTF-7-item-1.png', '0', '0.png'))
self.assertEqual(first.crop((0, 0, 118, 59)).tobytes(), art.tobytes())
def test_a_pdf_page_is_rendered_at_300_dpi(self):
art = quadrants(118, 59)
path = os.path.join(self.dir.name, 'sheet.pdf')
art.save(path, resolution=300)
spec = item([placement(0, 0, 1, 0.5)], [source(1, 0.5)], 0.5)
for stream in (False, True):
with mock.patch.object(printpng, 'STREAM_ABOVE_PIXELS', 0 if stream else 10 ** 9):
parts, detail = self.render(spec, [path])
film = Image.open(parts[0][0]).convert('RGBA')
self.assertEqual(film.size, (px(57), 59))
# Pillow writes the PDF's image as a JPEG: close, not exact.
for point, color in (((15, 15), RED), ((100, 50), YELLOW)):
self.assertLess(max(abs(a - b) for a, b in zip(film.getpixel(point), color)), 8, point)
self.assertEqual(detail['vector_sources'], 1)
if __name__ == '__main__':
unittest.main()

View File

@@ -0,0 +1,27 @@
"""Final artwork acceptance is based on PNG bytes, alpha and 300 DPI metadata."""
import io
import unittest
from PIL import Image
from app.printpng_validate import final_png_issue
def png(mode='RGBA', dpi=(300, 300)):
out = io.BytesIO()
Image.new(mode, (3, 3), (0, 0, 0, 0) if mode == 'RGBA' else (0, 0, 0)).save(out, 'PNG', dpi=dpi)
return out.getvalue()
class FinalPngTests(unittest.TestCase):
def test_accepts_only_rgba_300dpi_png(self):
self.assertIsNone(final_png_issue(png()))
self.assertIn('precisa ser PNG', final_png_issue(b'%PDF-1.7'))
self.assertIn('transparência', final_png_issue(png('RGB')))
self.assertIn('300 DPI', final_png_issue(png(dpi=(72, 72))))
self.assertIn('300 DPI', final_png_issue(png(dpi=(300, 150))))
self.assertIn('incompleto', final_png_issue(png()[:50]))
if __name__ == '__main__':
unittest.main()

42
tests/test_proof_cut.py Normal file
View File

@@ -0,0 +1,42 @@
"""The proof window: 15 cm around the finest stroke, never outside the film."""
import unittest
from decimal import Decimal
from app.printjobs import proof_part
from app.printpng import proof_cut
class ProofPartTests(unittest.TestCase):
def test_one_part_keeps_the_same_fraction(self):
self.assertEqual(proof_part([100], 100, 0.5), (0, 0.5))
self.assertEqual(proof_part([30], 30, 0.8), (0, 0.8))
def test_the_part_holding_the_finest_stroke_is_chosen(self):
self.assertEqual(proof_part([1000, 1000, 1000], 3000, 0.1), (0, 0.3))
self.assertEqual(proof_part([1000, 1000, 1000], 3000, 0.5), (1, 0.5))
self.assertEqual(proof_part([1000, 1000, 1000], 3000, 0.75), (2, 0.25))
def test_the_fraction_is_recalculated_inside_the_chosen_part(self):
self.assertEqual(proof_part([1500, 1500], 3000, 0.75), (1, 0.5))
self.assertEqual(proof_part([1500, 1500], 3000, 1), (1, 1))
class ProofCutTests(unittest.TestCase):
def test_centres_the_window_on_the_finest_stroke(self):
self.assertEqual(proof_cut(100, 15, 0.5), [Decimal('42.5'), Decimal('57.5')])
self.assertEqual(proof_cut(100, 15, 0.8), [Decimal('72.5'), Decimal('87.5')])
def test_clamps_at_both_ends(self):
self.assertEqual(proof_cut(100, 15, 0), [Decimal(0), Decimal(15)])
self.assertEqual(proof_cut(100, 15, 1), [Decimal(85), Decimal(100)])
def test_a_short_film_is_the_whole_proof(self):
self.assertEqual(proof_cut(10, 15, 0.5), [Decimal(0), Decimal(10)])
self.assertEqual(proof_cut(10, 15, None), [Decimal(0), Decimal(10)])
def test_without_a_measure_the_old_top_window_remains(self):
self.assertEqual(proof_cut(100, 15, None), [Decimal(0), Decimal(15)])
if __name__ == '__main__':
unittest.main()

View File

@@ -0,0 +1,66 @@
"""A free proof is a 15 cm window around the measured fine stroke, not the top."""
import io
import tempfile
import unittest
from pathlib import Path
from PIL import Image, ImageDraw
from app.printpng import render
PX_CM = 300 / 2.54
def item(height_cm=30, fraction='0.75'):
return {
'mode': 'file', 'metres': '10.5', 'billed_metres': '0',
'production': {
'version': 3, 'film_width_cm': 20, 'height_cm': height_cm,
'sources': [{'upload_id': '00000000-0000-0000-0000-000000000001',
'kind': 'sheet', 'width_cm': 20, 'length_cm': height_cm,
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
'measurement': 'file'}],
'placements': [{'source_index': 0, 'copy_index': 0, 'x_cm': 0, 'y_cm': 0,
'width_cm': 20, 'length_cm': height_cm,
'rotation_degrees': 0, 'mirrored': False}],
},
'proof_parent_item_index': 0, 'proof_y_fraction': fraction,
}
class ProofRenderTests(unittest.TestCase):
def _sheet(self, folder):
height = round(30 * PX_CM)
width = round(20 * PX_CM)
image = Image.new('RGBA', (width, height), (220, 30, 60, 255))
ImageDraw.Draw(image).rectangle((0, height // 2, width - 1, height - 1),
fill=(30, 60, 220, 255))
path = Path(folder) / 'sheet.png'
image.save(path, 'PNG', dpi=(300, 300))
return str(path)
def test_the_window_follows_the_finest_stroke(self):
with tempfile.TemporaryDirectory() as source, tempfile.TemporaryDirectory() as out:
sheet = self._sheet(source)
parts, detail = render(item(), {0: (sheet, 'sheet.png')}, out, 'proof',
limit_cm=15, proof_fraction='0.75')
self.assertEqual(len(parts), 1)
self.assertEqual(detail['parts'][0]['from_cm'], '15')
with Image.open(parts[0][0]) as proof:
self.assertEqual(proof.width, round(20 * PX_CM))
self.assertLessEqual(abs(proof.height - round(15 * PX_CM)), 1)
# The bottom half is blue: the window covered 15 to 30 cm.
self.assertEqual(proof.getpixel((proof.width // 2, round(5 * PX_CM))), (30, 60, 220, 255))
def test_the_top_is_still_the_default_without_a_measure(self):
with tempfile.TemporaryDirectory() as source, tempfile.TemporaryDirectory() as out:
sheet = self._sheet(source)
parts, detail = render(item(fraction=None), {0: (sheet, 'sheet.png')}, out, 'proof',
limit_cm=15)
self.assertEqual(detail['parts'][0]['from_cm'], '0')
with Image.open(parts[0][0]) as proof:
self.assertEqual(proof.getpixel((proof.width // 2, round(5 * PX_CM))), (220, 30, 60, 255))
if __name__ == '__main__':
unittest.main()

83
tests/test_prumo.py Normal file
View File

@@ -0,0 +1,83 @@
"""The Prumo report: only what happened, in the order it happened (front 6)."""
import unittest
from datetime import datetime, timedelta, timezone
from app.prumo import customer_summary, report
class PrumoReportTests(unittest.TestCase):
def order(self):
item = {
'mode': 'avulsa', 'billed_metres': '1.30', 'metres': '1.30',
'uploads': ['u1'], 'source_dpi': 96, 'residue_accepted': 3,
'residue_accepted_at': '2026-11-05T17:32:00+00:00',
'stroke_px': 6, 'stroke_class': 'C2', 'stroke_choice': 'measured',
'production': {'height_cm': '130', 'placements': [
{'rotation_degrees': 0}, {'rotation_degrees': 90}]},
}
started = datetime(2026, 11, 5, 14, 0, tzinfo=timezone.utc)
return {'snapshot': {'items': [item]}, 'print_files': [{
'item_index': 0, 'status': 'ready', 'created_at': started - timedelta(minutes=5),
'claimed_at': started, 'finished_at': started + timedelta(seconds=41),
'detail': {'format': 'png', 'dpi': 300, 'parts': [
{'from_cm': '0', 'to_cm': '15'}, {'from_cm': '15', 'to_cm': '16'}]},
}]}
def test_card_report_reads_the_decisions(self):
lines = report(self.order(), {'u1': {'name': 'arte.pdf', 'original_name': 'arte.cdr'}})
text = '\n'.join(lines)
self.assertIn('Chegou CDR, era PDF por dentro', text)
self.assertIn('PDF → PNG 300 DPI', text)
self.assertIn('Resolução detectada: 96 DPI', text)
self.assertIn('3 pontos < 2 mm — cliente aceitou', text)
self.assertIn('2 artes, 1 girada', text)
self.assertIn('Menor traço 6 px → C2', text)
self.assertIn('cliente escolheu imprimir em C1', text)
self.assertIn('2 partes (15,00 + 1,00)', text)
self.assertIn('Prumo levou 41 s', text)
self.assertNotIn('Prumo levou 341 s', text)
def test_without_a_claim_time_the_generation_line_is_hidden(self):
order = self.order()
del order['print_files'][0]['claimed_at']
text = '\n'.join(report(order, {'u1': {'name': 'arte.pdf', 'original_name': 'arte.cdr'}}))
self.assertNotIn('Prumo levou', text)
def test_one_format_line_per_item(self):
order = self.order()
item = order['snapshot']['items'][0]
item['uploads'] = ['u1', 'u2', 'u3']
uploads = {uid: {'name': f'arte-{uid}.png'} for uid in item['uploads']}
text = '\n'.join(report(order, uploads))
self.assertEqual(text.count('Formato detectado'), 1)
self.assertIn('Formato detectado: PNG (3 arquivos)', text)
# Mixed formats name them once, sorted, and the per-file changes stay.
uploads['u2'] = {'name': 'arte-u2.pdf', 'original_name': 'arte-u2.cdr'}
mixed = '\n'.join(report(order, uploads))
self.assertEqual(mixed.count('Formatos detectados'), 1)
self.assertIn('Formatos detectados: PDF, PNG', mixed)
self.assertIn('Chegou CDR, era PDF por dentro', mixed)
def test_customer_summary_is_plain_language(self):
lines = customer_summary(self.order()['snapshot']['items'])
text = ' '.join(lines)
self.assertIn('96 DPI', text)
self.assertIn('3 pontinhos', text)
self.assertIn('Sua arte tem traços médios; a impressão foi ajustada para eles.', text)
self.assertNotIn('O traço mais fino foi medido em C2.', text)
self.assertIn('C1', text)
self.assertIn('será preparado', text)
self.assertNotIn('foi ampliada', text)
def test_unfinished_job_does_not_claim_a_conversion_or_background_check(self):
order = self.order()
order['print_files'] = [{'item_index': 0, 'status': 'manual', 'detail': {}}]
lines = report(order, {'u1': {'name': 'arte.pdf', 'original_name': 'arte.cdr'}})
text = '\n'.join(lines)
self.assertIn('Arquivo exige preparo manual', text)
self.assertNotIn('PDF → PNG', text)
self.assertNotIn('Fundo transparente', text)
if __name__ == '__main__':
unittest.main()

35
tests/test_speed.py Normal file
View File

@@ -0,0 +1,35 @@
"""Números' speed block: average and p95, in the units the PDF asks for."""
import unittest
from app.api.operator import speed_figures
class SpeedFiguresTests(unittest.TestCase):
def test_formats_seconds_and_upload_speed(self):
site = {'page_avg': 1500, 'page_p95': 3000, 'page_n': 4,
'upload_avg': 2.5, 'upload_p95': 1.5, 'upload_n': 4,
'analysis_avg': 12000, 'analysis_p95': 20000, 'analysis_n': 3,
'montage_avg': 8000, 'montage_p95': 9000, 'montage_n': 2}
generation = {'per10_avg': 90, 'per10_p95': 120, 'per10_n': 5}
card = {'avg_s': 0.4, 'p95_s': 0.9, 'n': 2}
rows = {row['key']: row for row in speed_figures(site, generation, card)}
self.assertEqual(rows['page']['average'], 1.5)
self.assertEqual(rows['page']['p95'], 3.0)
self.assertEqual(rows['upload']['unit'], 's/MB')
self.assertEqual(rows['analysis']['average'], 12.0)
self.assertEqual(rows['montage']['p95'], 9.0)
self.assertEqual(rows['print']['average'], 90)
self.assertEqual(rows['card']['samples'], 2)
def test_missing_samples_stay_empty(self):
empty = {key: None for key in ('page_avg', 'page_p95', 'page_n', 'upload_avg', 'upload_p95',
'upload_n', 'analysis_avg', 'analysis_p95', 'analysis_n',
'montage_avg', 'montage_p95', 'montage_n')}
generation = {'per10_avg': None, 'per10_p95': None, 'per10_n': 0}
card = {'avg_s': None, 'p95_s': None, 'n': 0}
rows = speed_figures(empty, generation, card)
self.assertTrue(all(row['average'] is None and row['samples'] == 0 for row in rows))
if __name__ == '__main__':
unittest.main()

View File

@@ -149,6 +149,19 @@ class TinyTests(FakeTinyCase):
self.assertNotIn('enderecoEntrega', pickup)
self.assertIn('retirada', pickup['observacoes'])
def test_treatment_is_a_line_and_one_more_day(self):
base = {**PAID['order'],
'freight': {'service': 'mock-standard', 'total_cents': 1500, 'days': 3}}
plain = {'order': base, **{k: v for k, v in PAID.items() if k != 'order'}}
treatment = {'order': {**base, 'treatment': {'cents': 990, 'hours': 24},
'total_cents': base['total_cents'] + 990},
**{k: v for k, v in PAID.items() if k != 'order'}}
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
pedido = order_payload(treatment, 777, date(2026, 9, 24))
self.assertIn({'produto': {'id': 105}, 'quantidade': 1, 'valorUnitario': 9.9,
'infoAdicional': 'Tratamento da arte pelo designer · +24 h'}, pedido['itens'])
self.assertNotEqual(pedido['dataPrevista'], order_payload(plain, 777, date(2026, 9, 24))['dataPrevista'])
def test_second_delivery_finds_the_first_order(self):
first = self.tiny.deliver('k1', PAID)
second = self.tiny.deliver('k1', PAID)
@@ -788,5 +801,16 @@ class DefaultSkuTests(unittest.TestCase):
self.assertEqual(tiny.mode_codes('uvfile'), tiny.sku_codes('UV.P'))
class TreatmentSettingTests(unittest.TestCase):
"""A paid treatment needs its own Tiny product, asked with the rest."""
def test_the_treatment_product_is_required_only_when_it_is_paid(self):
from app.tiny import required_settings
with mock.patch.dict(os.environ, {'TREATMENT_CENTS': '0'}):
self.assertNotIn('TINY_PRODUCT_TREATMENT', required_settings())
with mock.patch.dict(os.environ, {'TREATMENT_CENTS': '5000'}):
self.assertIn('TINY_PRODUCT_TREATMENT', required_settings())
if __name__ == '__main__':
unittest.main()

View File

@@ -0,0 +1,38 @@
"""A paid treatment needs a designer-prepared final before the print queue.
Run against the local stack: SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost
python -m tests.treatment_gate_test
"""
from app.core import db
from tests.print_file_test import artwork, loose_item, paid_order, wait_print
from tests.smoke_test import Client, upload_bytes
def run():
client = Client()
client.call('/session')
original = upload_bytes(client, artwork(), name='LOCAL-TREATMENT-ORIGINAL.png')
order = paid_order(client, loose_item(original, copies=1))
_, generated = wait_print(client, order['id'], 'ready')
# The local price is normally zero. Mark this paid fixture as having bought
# treatment to exercise the production gate, not the checkout price rule.
with db.connect() as c:
c.execute("""UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{treatment}',
'{"cents":990,"hours":24}'::jsonb) WHERE id=%s""", (order['id'],))
approved = client.call('/operator/orders/' + order['id'] + '/final-files',
{'version': order['version'], 'files': [{'item_index': 0, 'upload_id': generated['upload_id']}],
'note': 'Gerado pelo Prumo'}, operator=True)
blocked = client.call('/operator/orders/' + order['id'] + '/move',
{'state': 'tra', 'version': approved['version']}, operator=True, expected=409)
assert 'Tratamento pago' in blocked['detail'], blocked
prepared = upload_bytes(client, artwork(), name='LOCAL-TREATMENT-FINAL.png', order_id=order['id'])
approved = client.call('/operator/orders/' + order['id'] + '/final-files',
{'version': approved['version'], 'files': [{'item_index': 0, 'upload_id': prepared}],
'note': 'PNG tratado pelo designer'}, operator=True)
client.call('/operator/orders/' + order['id'] + '/move',
{'state': 'tra', 'version': approved['version']}, operator=True)
print('PASS: generated artwork cannot satisfy paid treatment; designer PNG opens the print queue')
if __name__ == '__main__':
run()

107
tests/unpaid_test.py Normal file
View File

@@ -0,0 +1,107 @@
"""Approved quotes nobody paid expire after 24 h (Fase 2, front 9).
Run inside the API container: python -m tests.unpaid_test
A live payment attempt keeps the files; once it is final, the quote expires,
its files are freed, the customer is e-mailed once and it leaves the Kanban.
"""
from datetime import datetime, timedelta, timezone
from urllib.parse import urlencode
from uuid import uuid4
from psycopg.types.json import Jsonb
from app import unpaid
from app.core import db
from tests.smoke_test import Client, approved_quote, item_spec, upload_bytes
ORIGIN = 'http://localhost'
SUBJECT = 'Seu pedido expirou · DTF Dropstar'
def reviewed_quote():
"""A quote an operator has approved, ready to be paid."""
customer = Client()
customer.call('/session')
uid = upload_bytes(customer, b'UNPAID EXPIRE TEST')
item = item_spec('file', '1.01', 0, uid)
mail = 'unpaid-' + uuid4().hex[:8] + '@example.test'
profile = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail}
quote = customer.call('/quotes', {'request_key': str(uuid4()), 'customer': profile,
'items': [item], 'freight': {'service': 'pickup'}})
approved = approved_quote(customer, quote, [item])
return customer, quote['id'], approved, mail
def attempt(c, quote_id, total, status, expires_at):
"""A payment attempt as the intent route records it."""
c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,
method,status,amount_cents,response) VALUES(%s,%s,'fake',%s,'pix',%s,%s,%s)''',
(uuid4(), quote_id, 'unpaid-' + uuid4().hex, status, total,
Jsonb({'status': status, 'expires_at': expires_at.isoformat()})))
def run():
customer, quote_id, approved, mail = reviewed_quote()
uploads = [uid for item in approved['items'] for uid in item['uploads']]
# 25 h old, but a PIX still open: the quote must not expire, nor its files.
with db.connect() as c:
c.execute("UPDATE dtf_local.quotes SET approved_at=now()-interval '25 hours' WHERE id=%s",
(quote_id,))
attempt(c, quote_id, approved['total_cents'], 'pending',
datetime.now(timezone.utc) + timedelta(minutes=30))
with db.connect() as c:
unpaid.expire(c, ORIGIN)
assert c.execute('SELECT expired_at FROM dtf_local.quotes WHERE id=%s',
(quote_id,)).fetchone()['expired_at'] is None
page = customer.call('/operator/quotes?' + urlencode({'kind': 'approved', 'q': mail}), operator=True)
assert quote_id in {q['id'] for q in page['quotes']}
print('PASS: a live payment attempt keeps an approved quote and its files')
# The attempt is final now: the quote expires, its files are freed and the
# customer is told once.
with db.connect() as c:
c.execute("UPDATE dtf_local.payment_intents SET status='expired' WHERE quote_id=%s", (quote_id,))
expired = unpaid.expire(c, ORIGIN)
assert expired >= 1, expired
with db.connect() as c:
row = c.execute('SELECT expired_at FROM dtf_local.quotes WHERE id=%s', (quote_id,)).fetchone()
assert row['expired_at'] is not None
files = c.execute('''SELECT count(*) AS total,
count(*) FILTER (WHERE expires_at<=now()) AS released
FROM dtf_local.uploads WHERE id=ANY(%s)''', (uploads,)).fetchone()
assert files['total'] and files['released'] == files['total'], files
mails = c.execute('SELECT kind,subject FROM dtf_local.mail_queue WHERE to_addr=%s ORDER BY id',
(mail,)).fetchall()
assert [m['subject'] for m in mails] == [SUBJECT], mails
page = customer.call('/operator/quotes?' + urlencode({'kind': 'approved', 'q': mail}), operator=True)
assert quote_id not in {q['id'] for q in page['quotes']}
print('PASS: the expired quote leaves the Kanban, frees its files and e-mails the customer')
# Expiring again is a no-op: the customer is not told twice.
with db.connect() as c:
unpaid.expire(c, ORIGIN)
with db.connect() as c:
sent = c.execute('SELECT count(*) AS n FROM dtf_local.mail_queue WHERE to_addr=%s AND subject=%s',
(mail, SUBJECT)).fetchone()['n']
assert sent == 1, sent
print('PASS: a second run does not e-mail the customer again')
# A quote from before this front ran out days ago: it expires silently.
_, old_id, _, old_mail = reviewed_quote()
with db.connect() as c:
c.execute("UPDATE dtf_local.quotes SET approved_at=now()-interval '3 days' WHERE id=%s", (old_id,))
unpaid.expire(c, ORIGIN)
with db.connect() as c:
assert c.execute('SELECT expired_at FROM dtf_local.quotes WHERE id=%s',
(old_id,)).fetchone()['expired_at'] is not None
assert not c.execute('SELECT 1 FROM dtf_local.mail_queue WHERE to_addr=%s', (old_mail,)).fetchone()
print('PASS: an old backlog quote expires without an e-mail')
stats = customer.call('/operator/stats?days=7', operator=True)
assert stats['unpaid']['expired'] >= 1, stats['unpaid']
print('PASS: Números counts the expired order')
if __name__ == '__main__':
run()

View File

@@ -4,16 +4,14 @@ Run inside the API container: python -m tests.users_test
"""
import secrets
import time
from decimal import Decimal
from urllib.request import Request, urlopen
from uuid import uuid4
from psycopg.types.json import Jsonb
from app import machines as routing
from app import payments, proof
from app.core import db
from tests.smoke_test import BASE, Client, with_host
from tests.smoke_test import BASE, Client, with_host, review_photo
PASSWORD = 'senha-de-teste-123'
@@ -61,34 +59,7 @@ def pickup_photo(client, oid, content):
return uid
def expected_machine(su, product, metres=1.0):
"""What app/machines.py should pick now: the active machine of the product
with the fewest metres open, among those with room, else among all."""
# Listed in the order they were registered: min() keeps the first of equals, as the routing does.
rows = [m for m in su.call('/operator/machines', operator=True)['machines'] if m['active'] and product in m['products']]
room = [m for m in rows if m['limit_metres'] is None or m['open_metres'] + metres <= m['limit_metres']]
return min(room or rows, key=lambda m: m['open_metres'])['id']
def picking():
"""The choice itself: room first, then the fewest metres, then the first registered."""
textil = {'snapshot': {'items': [{'mode': 'file', 'billed_metres': '1'}]}}
uv = {'snapshot': {'items': [{'mode': 'uvfile', 'billed_metres': '1'}]}}
a = {'id': 'a', 'products': ['textil'], 'active': True, 'limit_metres': Decimal('2')}
b = {'id': 'b', 'products': ['textil'], 'active': True, 'limit_metres': None}
off = {'id': 'off', 'products': ['textil'], 'active': False, 'limit_metres': None}
assert routing.pick([a, b], {}, textil)['id'] == 'a'
assert routing.pick([off, a, b], {'a': Decimal('0.5')}, textil)['id'] == 'b'
# Full: the one with room takes it, even with more metres open.
assert routing.pick([a, b], {'a': Decimal('1.5'), 'b': Decimal('9')}, textil)['id'] == 'b'
# All full: the least loaded anyway.
b_full = {**b, 'limit_metres': Decimal('3')}
assert routing.pick([a, b_full], {'a': Decimal('5'), 'b': Decimal('4')}, textil)['id'] == 'b'
assert routing.pick([a, b], {}, uv) is None
def run():
picking()
tag = secrets.token_hex(3)
su = Client()
su.call('/session')
@@ -131,19 +102,22 @@ def run():
expected=409)
admin.call(f"/operator/users/{mine['id']}/delete", {}, expected=409)
# Orders other suites left open get their machines first; then each paid
# order goes to the machine of its product with the fewest metres open.
# No machine at payment: a card waits for a person to choose one or to
# pull it into Imprimindo (Dropstar, 2026-11-05).
su.call('/operator/board', operator=True)
want = {'textil': expected_machine(su, 'textil'), 'uv': expected_machine(su, 'uv')}
with db.connect() as c:
textil_q, textil_o = order_fixture(c, owner, 'file')
uv_q, uv_o = order_fixture(c, owner, 'uvfile')
made += [(textil_q, textil_o), (uv_q, uv_o)]
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[str(textil_o)]['machine']['id'] == want['textil'] and not board[str(textil_o)]['machine']['chosen']
assert board[str(uv_o)]['machine']['id'] == want['uv'] and not board[str(uv_o)]['machine']['chosen']
# On the UV machine of this test, whatever the others carry.
assert board[str(uv_o)]['machine'] is None and not board[str(textil_o)]['machine_chosen']
assert board[str(uv_o)]['machine'] is None and not board[str(uv_o)]['machine_chosen']
# Chosen before printing, each one stays there.
su.call(f'/operator/orders/{textil_o}/machine', {'machine_id': textil}, operator=True)
su.call(f'/operator/orders/{uv_o}/machine', {'machine_id': uv}, operator=True)
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[str(textil_o)]['machine']['id'] == textil and board[str(textil_o)]['machine']['chosen']
assert board[str(uv_o)]['machine']['id'] == uv and board[str(uv_o)]['machine']['chosen']
# The operator prints: Arte conferida to Imprimindo to Revisão, nothing
# else (Dropstar, 2026-10-23). After signing in they say which machine
@@ -153,6 +127,11 @@ def run():
assert (me['machine_question'], me['machine_answered'], me['machine']) == ('required', False, None), me
assert {str(uv_o), str(textil_o)} <= {o['id'] for o in op.call('/operator/board')['orders']}
assert sorted(me['moves']) == [['imp', 'rev'], ['imp', 'tra'], ['rev', 'imp'], ['tra', 'imp']]
# The designer approves every file (D-16): the operator neither approves
# a final nor picks the contraction.
assert me['can'] == ['deliver', 'print', 'view'], me
op.call(f'/operator/orders/{uv_o}/contraction', {'item_index': 0, 'value': 'C2'}, expected=403)
op.call(f'/operator/orders/{uv_o}/final-files', {'version': 0, 'note': '', 'files': []}, expected=403)
op.call(f'/operator/orders/{uv_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403)
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='imp' WHERE id=%s", (uv_o,))
@@ -194,7 +173,8 @@ def run():
seller.call(f'/operator/orders/{textil_o}/machine', {'machine_id': None}, expected=403)
seller.call(f'/operator/orders/{textil_o}/contact', {'waiting': True, 'note': 'Ligar'}, expected=403)
# The seller only views the board (D-30): no order registered by hand either.
assert seller.call('/operator/me')['can'] == ['view']
# The seller only views, but answers a proof card (Dropstar, 2026-11-03).
assert seller.call('/operator/me')['can'] == ['proof', 'view']
seller.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=403)
# Financeiro (Dropstar, 2026-10-30): the board, Pagamentos, Números and
# Cotações, and cancels an order with its reason; moves nothing.
@@ -223,7 +203,7 @@ def run():
'password': PASSWORD})
reviewer = signed_in(emails['revisor'])
me = reviewer.call('/operator/me')
assert me['can'] == ['deliver', 'view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me
assert me['can'] == ['deliver', 'inspect', 'view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me
reviewer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403)
assert reviewer.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'],
'reason': ''})['state'] == 'fin'
@@ -294,6 +274,8 @@ def run():
version = su.call(f'/operator/orders/{long_o}/proof', {}, operator=True)['version']
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[str(long_o)]['proof_ok_at'] and board[str(long_o)]['proof_ok_by']
# Above 1 m Finalizado also needs the review photo (app/reviews.py).
review_photo(su, str(long_o))
su.call(f'/operator/orders/{long_o}/move', {'state': 'fin', 'version': version, 'reason': ''}, operator=True)
# Up to 10 m, nothing to wait for.
with db.connect() as c:
@@ -301,6 +283,8 @@ def run():
made.append((short_q, short_o))
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (short_o,))
version = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(short_o))['version']
# 10 m is above the 1 m review photo rule just the same.
review_photo(su, str(short_o))
su.call(f'/operator/orders/{short_o}/move', {'state': 'fin', 'version': version, 'reason': ''}, operator=True)
# Asked for at checkout: the paid order arrives waiting for the customer's word.
with db.connect() as c:
@@ -332,36 +316,36 @@ def run():
listed = {m['id']: m for m in admin.call('/operator/machines')['machines']}
assert listed[textil2]['operators'] == [] and [o['id'] for o in listed[uv]['operators']] == [op_id], listed[uv]
assert next(u for u in admin.call('/operator/users')['users'] if u['id'] == op_id)['machines'] == [uv]
# The next order goes to the one with fewer metres open.
target = expected_machine(su, 'textil')
# A paid order starts with no machine; choosing one by hand is the
# only way it gets one before a pull (Dropstar, 2026-11-05).
with db.connect() as c:
made.append(order_fixture(c, owner, 'file'))
second = str(made[-1][1])
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[second]['machine']['id'] == target
# Chosen by hand, the order stays there; back to automatic, it is routed again.
assert board[second]['machine'] is None and not board[second]['machine_chosen']
su.call(f'/operator/orders/{second}/machine', {'machine_id': textil2}, operator=True)
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[second]['machine']['id'] == textil2 and board[second]['machine']['chosen']
listed = {m['id']: m for m in su.call('/operator/machines', operator=True)['machines']}
assert listed[textil2]['open_orders'] >= 1 and listed[textil2]['states'].get('rec', 0) >= 1
# A limit: once full, the next order goes to a machine with room.
# The limit is shown on the machine; it no longer routes new orders.
open_now = listed[textil2]['open_metres']
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'],
'limit_metres': round(open_now + 0.5, 1)})
listed = {m['id']: m for m in su.call('/operator/machines', operator=True)['machines']}
assert listed[textil2]['limit_metres'] == round(open_now + 0.5, 1)
target = expected_machine(su, 'textil')
assert target != textil2
with db.connect() as c:
made.append(order_fixture(c, owner, 'file'))
third = str(made[-1][1])
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[third]['machine']['id'] == target
assert board[third]['machine'] is None and not board[third]['machine_chosen']
su.call(f'/operator/orders/{third}/machine', {'machine_id': textil}, operator=True)
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'],
'limit_metres': 0}, expected=422)
su.call(f'/operator/orders/{second}/machine', {'machine_id': None}, operator=True)
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert not board[second]['machine']['chosen']
assert not board[second]['machine_chosen']
# Números per machine: an order printed for half an hour on its machine, then
# finished. It counts the film printed (0,40 m), not the metre billed.
@@ -375,10 +359,10 @@ def run():
c.execute(f'''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
VALUES(%s,%s,%s,'users-test','',false,{at})''', (third, frm, to))
after = {m['id']: m for m in su.call('/operator/stats?days=7', operator=True)['machines']}
assert after[target]['orders'] == before[target]['orders'] + 1
assert round(after[target]['metres'] - before[target]['metres'], 2) == 0.4, (before[target], after[target])
assert after[target]['last_finished'] and after[target]['metres_per_hour'] is not None
assert after[target]['printing_hours'] >= before[target]['printing_hours'] + 0.49
assert after[textil]['orders'] == before[textil]['orders'] + 1
assert round(after[textil]['metres'] - before[textil]['metres'], 2) == 0.4, (before[textil], after[textil])
assert after[textil]['last_finished'] and after[textil]['metres_per_hour'] is not None
assert after[textil]['printing_hours'] >= before[textil]['printing_hours'] + 0.49
# Two orders printing at once on one machine: the half hour they share counts
# once, so the machine did 1,50 m in 0,5 h, not in 1 h.
with db.connect() as c:
@@ -399,7 +383,7 @@ def run():
cap = admin.call('/operator/machines', {'name': f'Cap {tag}', 'products': ['textil']})['id']
machines.append(cap)
with db.connect() as c:
pulled = [order_fixture(c, owner, 'file') for _ in range(4)]
pulled = [order_fixture(c, owner, 'file') for _ in range(5)]
made.extend(pulled)
for _, oid in pulled:
upload = uuid4()
@@ -410,7 +394,7 @@ def run():
VALUES(%s,%s,%s,0,'final','ok','t')''', (uuid4(), oid, upload))
c.execute("UPDATE dtf_local.orders SET state='tra', machine_id=%s, machine_chosen=true WHERE id=%s",
(cap, oid))
first, second_in, third, elsewhere = (str(oid) for _, oid in pulled)
first, second_in, third, elsewhere, lane = (str(oid) for _, oid in pulled)
pull = lambda oid, version=0: su.call(f'/operator/orders/{oid}/move', {'state': 'imp', 'version': version,
'reason': ''}, operator=True)
running = pull(first)
@@ -418,6 +402,25 @@ def run():
refused = su.call(f'/operator/orders/{third}/move', {'state': 'imp', 'version': 0, 'reason': ''},
operator=True, expected=409)
assert refused['detail'] == f'Cap {tag} já tem 2 em Imprimindo.', refused
# Dropped on another machine's lane, an order of the full one prints
# there instead; never on a machine that does not print its product.
not_uv = su.call(f'/operator/orders/{lane}/move', {'state': 'imp', 'version': 0, 'reason': '', 'machine_id': uv},
operator=True, expected=409)
assert not_uv['detail'] == f'A UV {tag} não imprime este produto.', not_uv
onto = su.call(f'/operator/orders/{lane}/move', {'state': 'imp', 'version': 0, 'reason': '', 'machine_id': textil2},
operator=True)
assert str(onto['machine_id']) == textil2 and onto['machine_chosen'], onto
# The contraction class (item 9): chosen per item until its file goes to
# the machine's hot folder (item 10), and back to the browser's measure with None.
su.call(f'/operator/orders/{third}/contraction', {'item_index': 0, 'value': 'C3'}, operator=True)
chosen = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == third)['contraction']
assert chosen['0']['class'] == 'C3' and chosen['0']['by'], chosen
su.call(f'/operator/orders/{third}/contraction', {'item_index': 5, 'value': 'C1'}, operator=True, expected=422)
# Printing, with nothing in the hot folder yet, it still changes.
su.call(f'/operator/orders/{lane}/contraction', {'item_index': 0, 'value': 'C1'}, operator=True)
su.call(f'/operator/orders/{lane}/contraction', {'item_index': 0, 'value': None}, operator=True)
su.call(f'/operator/orders/{third}/contraction', {'item_index': 0, 'value': None}, operator=True)
assert next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == third)['contraction'] == {}
loaded = su.call('/operator/board', operator=True)
board = {o['id']: o for o in loaded['orders']}
assert (board[first]['printing'], board[second_in]['printing'], board[third]['printing']) == \
@@ -469,12 +472,13 @@ def run():
assert {o['name'] for o in on_free} == {'Op', 'Marcus'}, on_free
designer.call('/operator/me/machine', {'machine_id': free}, expected=403)
# Switched off, a machine gives its automatic orders to another one.
# Switching a machine off no longer re-routes the cards: a person
# chooses another machine (Dropstar, 2026-11-05).
with db.connect() as c:
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=false WHERE id=%s', (textil2, second))
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'], 'active': False})
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
assert board[second]['machine']['id'] not in (None, textil2)
assert board[second]['machine']['id'] == textil2
# Disabled, the operator is out at once; deleted, the account is gone.
op_row = users[emails['operador']]
@@ -483,12 +487,11 @@ def run():
op.call('/operator/board', expected=401)
admin.call(f"/operator/users/{op_row['id']}/delete", {})
assert emails['operador'] not in {u['email'] for u in admin.call('/operator/users')['users']}
# A deleted machine sends its orders back to the automatic choice.
# A deleted machine leaves its cards without a machine; a person picks one.
su.call(f'/operator/machines/{uv}/delete', {}, operator=True)
machines.remove(uv)
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
back = board[str(textil_o)]['machine']
assert back and back['id'] != uv and not back['chosen']
assert board[str(uv_o)]['machine'] is None
# Rework (D-02 to D-04): Gestão opens it with its cause, an Administrador
# authorizes it, never their own, and only then it counts in Números.
emails['gestao'] = f'gestao-{tag}@example.test'

View File

@@ -2,7 +2,7 @@
import os
from uuid import uuid4
from urllib.request import urlopen
from tests.smoke_test import Client, approved_quote, upload_bytes, item_spec, register
from tests.smoke_test import Client, approved_quote, upload_bytes, item_spec, register, final_png_bytes, review_photo
def run():
customer=Client();other=Client();customer.call('/session');other.call('/session')
@@ -50,12 +50,21 @@ def run():
assert other.call('/customer/orders/'+oid)['id']==oid
print('PASS: registration claims only current guest records, cross-session account login, revoked sessions, owner UUID is not a credential')
machine = None
def move(state,version):
return customer.call('/operator/orders/'+oid+'/move',{'state':state,'version':version,'reason':'Please replace the artwork' if state=='cor' else ''},operator=True)['version']
nonlocal machine
body={'state':state,'version':version,'reason':'Please replace the artwork' if state=='cor' else ''}
if state=='imp':
if machine is None:
machine=customer.call('/operator/machines',{'name':'Workflow '+uuid4().hex[:6],
'products':['textil']},operator=True)['id']
body['machine_id']=machine
return customer.call('/operator/orders/'+oid+'/move',body,operator=True)['version']
# Arte conferida is the print queue (2026-10-23): it takes approved finals only.
version=0
customer.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
final_id=upload_bytes(customer,b'LOCAL FINAL VERSION ONE',order_id=oid)
final_one=final_png_bytes('final one')
final_id=upload_bytes(customer,final_one,name='LOCAL-FINAL-ONE.png',order_id=oid)
customer.call('/uploads/'+final_id,expected=404)
body={'version':version,'files':[{'item_index':0,'upload_id':final_id}],'note':'Manually checked final'}
customer.call('/operator/orders/'+oid+'/final-files',body,expected=401)
@@ -67,21 +76,21 @@ def run():
detail=customer.call('/customer/orders/'+oid)
final=detail['files'][0]
link=customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download')
assert urlopen(link['url']).read()==b'LOCAL FINAL VERSION ONE'
assert urlopen(link['url']).read()==final_one
guest=Client();guest.call('/session');guest.call('/customer/orders/'+oid+'/files/'+final['id']+'/download',expected=404)
version=move('tra',version)
# The print queue's files come named after their order, straight from storage.
queued=customer.call('/operator/queue/finals',operator=True)['files']
mine=[f for f in queued if urlopen(f['url']).read()==b'LOCAL FINAL VERSION ONE']
mine=[f for f in queued if f['order']==oid and urlopen(f['url']).read()==final_one]
assert len(mine)==1 and mine[0]['name'].startswith('DTF-%d-item-1-' % mine[0]['number']), queued
customer.call('/operator/queue/finals',expected=401)
version=move('imp',version);version=move('cor',version)
customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download',expected=404)
premature_final=upload_bytes(customer,b'FINAL BEFORE CUSTOMER CORRECTION',order_id=oid)
premature_final=upload_bytes(customer,final_png_bytes('premature'),name='LOCAL-PREMATURE-FINAL.png',order_id=oid)
version=customer.call('/operator/orders/'+oid+'/final-files',
{'version':version,'files':[{'item_index':0,'upload_id':premature_final}],
'note':'Prepared before customer sent the new correction'},operator=True)['version']
correction_id=upload_bytes(customer,b'LOCAL CORRECTED ORIGINAL')
correction_id=upload_bytes(customer,final_png_bytes('correction'),name='LOCAL-CORRECTION.png')
payload={'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Replaced the artwork as requested'}
guest.call('/customer/orders/'+oid+'/corrections',payload,expected=404)
customer.call('/customer/orders/'+oid+'/corrections',{**payload,'version':0},expected=409)
@@ -97,12 +106,15 @@ def run():
# The customer's own correction approved as it is: not treated.
assert treated() is None, treated()
customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Twice'},operator=True,expected=409)
new_final=upload_bytes(customer,b'LOCAL FINAL VERSION TWO',order_id=oid)
new_final=upload_bytes(customer,final_png_bytes('final two'),name='LOCAL-FINAL-TWO.png',order_id=oid)
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':new_final}],'note':'Checked corrected final'},operator=True)['version']
assert treated()=={'items':[0],'by':operator_email}, treated()
stats=customer.call('/operator/stats?days=7',operator=True)['treated']
assert stats['orders']>=1 and any(t['orders']>=1 for t in stats['by']), stats
for state in ('tra','imp','rev','fin'):version=move(state,version)
for state in ('tra','imp','rev','fin'):
# Above 1 m Finalizado needs the review photo (app/reviews.py).
if state=='fin':review_photo(customer,oid)
version=move(state,version)
# In the queue the finals stay as approved.
customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':new_final}],'note':'Too late'},operator=True,expected=409)
detail=other.call('/customer/orders/'+oid)
@@ -128,7 +140,7 @@ def treating():
approved_quote(customer,q,items)
order=customer.call('/orders/dev-paid',{'quote_id':q['id']});oid=order['id'];number=order['number']
files=lambda:[f for f in customer.call('/operator/orders/'+oid+'/files',operator=True) if f['kind']=='final' and f['active']]
first=[upload_bytes(customer,b'LOCAL FIRST FINAL %d' % n,order_id=oid) for n in (1,2)]
first=[upload_bytes(customer,final_png_bytes(f'first {n}'),name=f'LOCAL-FIRST-FINAL-{n}.png',order_id=oid) for n in (1,2)]
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':0,'note':'Aprovado',
'files':[{'item_index':i,'upload_id':u} for i,u in enumerate(first)]},operator=True)['version']
# Where each item is in the stage folder, named as the folders save it.
@@ -137,7 +149,7 @@ def treating():
assert all(f['name'].startswith('DTF-%d-item-%d' % (number,f['item'])) for f in folder['files']), folder
customer.call('/operator/orders/'+oid+'/folder-files',expected=401)
# Saved over with the same name and sent back: item 1 changes, item 2 keeps its final.
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
png=final_png_bytes('treated')
treated=upload_bytes(customer,png,name='DTF-%d-item-1.png' % number,order_id=oid)
both=[{'item_index':0,'upload_id':treated},{'item_index':1,'upload_id':first[1]}]
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':both,'note':'Arte tratada'},operator=True)['version']

View File

@@ -21,8 +21,10 @@
quality:item.qualityStatus,
acknowledged:item.qualityAcknowledged,
residue:item.residueAccepted||0,
stroke:item.strokeClass||null,strokeChoice:item.strokeChoice||null,
sheets:(item.partes||[]).map(part=>part.production),
files:(item.localFiles||[]).map(file=>({name:file.name,size:file.size,lastModified:file.lastModified}))
}))});
})),treatment:!!$('fTratamento')?.checked});
}
// The quote this browser is paying, forgotten. clearDraft also empties the
// payment area; forgetDraft leaves on screen what is there (a confirmation).
@@ -72,6 +74,17 @@
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho();
}
// Treatment by the designer (front 5): only offered when TREATMENT_CENTS
// is set; the server adds the same amount and the 24 h to the quote.
TAXA_TRATAMENTO=(session.treatment_cents||0)/100;
const tratamentoBox=document.getElementById('tratamentoBox');
if(tratamentoBox){
tratamentoBox.hidden=!(TAXA_TRATAMENTO>0);
const preco=document.getElementById('tratamentoPreco');
if(preco)preco.textContent=TAXA_TRATAMENTO>0?rs(TAXA_TRATAMENTO):'';
if(!(TAXA_TRATAMENTO>0)&&document.getElementById('fTratamento'))document.getElementById('fTratamento').checked=false;
}
if(typeof pintaPedido==='function')pintaPedido();
}).catch(()=>{});
window.dtfSessionReady=ready;
window.dtfApi=api;
@@ -106,14 +119,29 @@
const amount=document.createElement('b'); amount.textContent=value;
row.append(name,amount); return row;
};
const rows = approved.items.map(item => linha(
(MODOS[item.mode]?.tit || item.mode)+' · '+fmtM(Number(item.billed_metres))+' m', rs(item.total_cents/100)));
// The sheets of a split (item 17) are one line, as in the cart.
const linhas=[];
for (const item of approved.items) {
const grupo=item.split && linhas.find(l=>l.split?.group===item.split.group);
if (grupo) { grupo.billed_metres=String(Number(grupo.billed_metres)+Number(item.billed_metres)); grupo.total_cents+=item.total_cents; grupo.folhas++; }
else linhas.push({...item,folhas:1});
}
const rows = linhas.map(item => linha(
(MODOS[item.mode]?.tit || item.mode)+(item.folhas>1?' · '+item.folhas+' folhas':'')+' · '+
fmtM(Number(item.billed_metres))+' m', rs(item.total_cents/100)));
const pickup = approved.freight.service === 'pickup';
const prazo = approved.freight.days ? ' · até '+approved.freight.days+' dias úteis' : '';
rows.push(linha(pickup ? 'Retirada em Franca' : (approved.freight.description || 'Frete')+prazo,
approved.freight.total_cents ? rs(approved.freight.total_cents/100) : 'Grátis'));
if(quote.treatment?.cents)
rows.push(linha('Tratamento da arte pelo designer · +24 h', rs(quote.treatment.cents/100)));
rows.push(linha('Total', rs(approved.total_cents/100), 'tot'));
resumo.replaceChildren(node('h4','Resumo do pedido'), ...rows);
const prumoBox=node('div',null,'prumoResumo');
if(quote.prumo?.length){
prumoBox.append(node('b','O que o Prumo fez'));
for(const line of quote.prumo) prumoBox.append(node('span',line));
}
resumo.replaceChildren(node('h4','Resumo do pedido'), ...rows, ...(quote.prumo?.length?[prumoBox]:[]));
}
function esqueletoPagamento() {
const linhas=['skel skelLinha','skel skelLinha','skel skelLinha curta'].map(c=>node('div',null,c));
@@ -136,13 +164,16 @@
const k=chaveArquivo(file);
let e=envios.get(k);
if (!e) {
const T=window.dtfTimings;
if(T){ if(T.uploadStart==null)T.uploadStart=performance.now();
if(!T.uploadSeen.has(k)){T.uploadSeen.add(k);T.uploadBytes+=file.size;} }
e={file, sent:0, done:false, failed:null, stop:new AbortController()};
e.promise=(async()=>{
const session=await ready;
return window.dtfUpload(file,{api,scope:session.cart_scope,progress:()=>{},signal:e.stop.signal,
onBytes:n=>{e.sent=n;pintaEnvio();}});
})();
e.promise.then(()=>{e.done=true;falhas.delete(k);pintaEnvio();},
e.promise.then(()=>{e.done=true;if(window.dtfTimings)T.uploadEnd=performance.now();falhas.delete(k);pintaEnvio();},
error=>{envios.delete(k);if(error?.name!=='AbortError')falhas.set(k,{file,error});pintaEnvio();});
envios.set(k,e);
}
@@ -327,7 +358,12 @@
if((await api('/session')).cart_scope !== (await ready).cart_scope) throw new Error('Sua conta ou sessão mudou. Recarregue a página antes de enviar o carrinho.');
const items=[];
pintaEnvio();
for (const item of cart) {
// Loose art split by stroke (item 17) is one cart line and one order item
// per sheet, billed together.
const sheets=cart.flatMap((line,index)=>line.partes?.length
? line.partes.map((part,i)=>({...line,...part,split:{group:'f'+index,part:i+1,of:line.partes.length}}))
: [line]);
for (const item of sheets) {
if (!item.localFiles?.length) throw new Error('Selecione novamente os arquivos deste item.');
const uploads=[];
for (const [index,file] of item.localFiles.entries()) {
@@ -341,7 +377,11 @@
production:{...item.production,sources:item.production.sources.map((source,index)=>({
upload_id:uploads[index],...source}))},
quality_status:item.qualityStatus,quality_acknowledged:item.qualityAcknowledged,
residue_accepted:item.residueAccepted||0});
residue_accepted:item.residueAccepted||0,
...(item.strokeClass?{stroke_px:item.strokePx,stroke_class:item.strokeClass}:{}),
...(item.strokeChoice?{stroke_choice:item.strokeChoice}:{}),
...(item.proofYFraction!=null?{proof_y_fraction:item.proofYFraction}:{}),
...(item.split?{split:item.split}:{})});
}
const service = entrega.tipo==='retira' ? 'pickup' : entrega.servico;
if (!service) throw new Error('A entrega ainda não está disponível. Escolha a retirada em Franca.');
@@ -350,14 +390,26 @@
if (destination) content.destination = destination;
// "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
if ($('fProva')?.checked) content.proof = true;
if ($('fTratamento')?.checked) content.treatment = true;
if (cartSnapshot()!==initialCart) throw new Error('O carrinho mudou durante o envio. Confira os itens e envie de novo.');
const serialized = JSON.stringify(content);
// Browser timings for Números (item 0.12); they never affect the price.
const T=window.dtfTimings, timings={};
const nav=performance.getEntriesByType?.('navigation')?.[0];
const pageMs=nav?.domContentLoadedEventEnd || (T?.pageStart!=null?performance.now()-T.pageStart:0);
if(pageMs>0)timings.page_ms=Math.round(pageMs);
if(T?.uploadStart!=null&&T.uploadEnd!=null){
timings.upload_ms=Math.round(T.uploadEnd-T.uploadStart);
timings.upload_bytes=Math.round(T.uploadBytes||0);
}
if(T?.analysisStart!=null&&T.analysisEnd!=null)timings.analysis_ms=Math.round(T.analysisEnd-T.analysisStart);
if(T?.montageStart!=null&&T.montageEnd!=null)timings.montage_ms=Math.round(T.montageEnd-T.montageStart);
const serialized = JSON.stringify({...content,timings});
if (!requestKey || serialized !== requestBody) {
requestKey = crypto.randomUUID(); requestBody = serialized;
localStorage.setItem('dtf-request-key',requestKey);
localStorage.setItem('dtf-request-body',requestBody);
}
const quote = await api('/quotes',{request_key:requestKey,...content});
const quote = await api('/quotes',{request_key:requestKey,...content,timings});
quotedCart=initialCart;localStorage.setItem('dtf-quote-cart',quotedCart);
draftId=quote.id; localStorage.setItem('dtf-quote',draftId);
await refresh(true);
@@ -395,7 +447,7 @@
}
if (quote.status==='pending_review') {
message((await ready).environment==='local'
? 'Arquivos enviados. No Kanban, confira metragem e nota e aprove a cotação '+draftId.slice(0,8)+'.'
? 'Arquivos enviados. No Kanban, confira a metragem e os arquivos e aprove a cotação '+draftId.slice(0,8)+'.'
: 'Arquivos enviados. Nossa equipe está conferindo a cotação '+draftId.slice(0,8)+'; o valor final aparece aqui em seguida.');
} else if (quote.status==='approved') {
if ((await ready).payment_provider === 'mercadopago') {
@@ -473,7 +525,8 @@
const titulo=node('h4','Pagamento confirmado');
titulo.insertAdjacentHTML('afterbegin', icone('okCirculo'));
box.append(titulo,
node('p','Recebemos seu pedido e ele já está na produção. Você acompanha cada etapa em Meus pedidos.'));
node('p','Recebemos seu pedido e ele já está na produção. Você acompanha cada etapa em Meus pedidos.'),
node('p','Seu pedido já aparece em Meus pedidos. O Prumo está preparando o arquivo de impressão; você pode acompanhar o andamento por lá.'));
button('Ver meus pedidos',()=>location.assign('/conta/pedidos?order='+quote.order.id),box);
actions.append(box);
}

View File

@@ -717,7 +717,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<span class="chip2">Franca · SP · envio em até 24 h</span>
</div>
<h1>A gente encaixa sua folha e você paga <em>menos metro</em></h1>
<p>Mande a arte, veja a nota e a folha montada antes de pagar. Revisão de 5 pontos e reencaixe por nossa conta.</p>
<p>Mande a arte, confira a folha montada e veja o preço antes de pagar. Revisão de 5 pontos e reencaixe por nossa conta.</p>
<div class="hero2-cta">
<a href="/#envio" class="btn-laranja">Enviar minha arte <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg></a>
<span>Sem cadastro · preço em segundos</span>
@@ -736,7 +736,7 @@ h2 em{font-style:normal;color:var(--laranja)}
</div>
<div class="hf-num">
<div><span>Metragem</span><b>0,60 m</b></div>
<div><span>Nota da arte</span><b class="verde">92</b></div>
<div><span>Conferência</span><b class="verde">Inclusa</b></div>
<div><span>Preço do metro</span><b class="laranja" data-preco="file">R$ 19,90</b></div>
</div>
</div>
@@ -745,11 +745,20 @@ h2 em{font-style:normal;color:var(--laranja)}
<section class="etapas2"><div class="w">
<div><span>1</span><div><b>Envie a arte</b><p>PNG ou PDF, conforme o produto. Sem cadastro.</p></div></div>
<div><span>2</span><div><b>Veja nota e montagem</b><p>A folha e o preço aparecem na hora.</p></div></div>
<div><span>2</span><div><b>Confira a montagem</b><p>A folha e o preço aparecem na hora.</p></div></div>
<div><span>3</span><div><b>Pague na hora</b><p>Cartão de crédito ou PIX, na própria página.</p></div></div>
<div><span>4</span><div><b>Acompanhe</b><p>Em Minha conta, com aviso no WhatsApp quando ficar pronto.</p></div></div>
</div></section>
<!-- VÍDEOS -->
<section id="videos" class="videos2"><div class="w">
<div class="videosCab">
<div><div class="et">Vídeos</div><h2>A DTF por dentro</h2></div>
<p>Do upload à retirada: o que acontece com a sua arte, sem letra miúda.</p>
</div>
<div class="videosGrid" id="videosGrid"></div>
</div></section>
<!-- ENVIO -->
<section id="envio">
<nav class="passos" id="passos" aria-label="Etapas do pedido" hidden>
@@ -767,7 +776,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<div class="cards-cab">
<div><div class="et">Escolha o produto</div>
<h2>Qual é o seu caso?</h2></div>
<p>Preço único por produto. A nota da arte aparece na tela para você entender o seu arquivo; ela não muda o preço.</p>
<p>Preço único por produto. Você confere a resolução e a montagem antes de pagar.</p>
</div>
<div class="escolha">
<button class="ec f" data-modo="file">
@@ -855,14 +864,13 @@ h2 em{font-style:normal;color:var(--laranja)}
<details>
<summary>Dicas para o seu arquivo</summary>
<ul>
<li class="s"><b>300 DPI no tamanho que vai imprimir.</b> É a nota máxima</li>
<li class="s"><b>300 DPI no tamanho que vai imprimir.</b> É a resolução ideal</li>
<li class="s"><b>O tamanho manda mais que o arquivo.</b> A mesma arte passa
em 20 cm e não passa em 40. Reduzir um pouco costuma subir a nota</li>
em 20 cm e não passa em 40. Reduzir um pouco costuma melhorar a resolução</li>
<li class="s"><b>Larguras parecidas rendem mais.</b> Se as suas artes têm
medidas próximas, cabem mais por fileira e a folha encolhe</li>
</ul>
<p class="obs2">A nota não muda o preço do metro: ela serve para você
entender o seu arquivo.</p>
<p class="obs2">A resolução não muda o preço do metro; ela mostra se o arquivo pode sair nítido.</p>
</details>
<details>
@@ -884,8 +892,8 @@ h2 em{font-style:normal;color:var(--laranja)}
<b>do arquivo</b>: se a arte foi ampliada antes de exportar, isso não aparece
para nós — e sai serrilhado no filme do mesmo jeito</li>
<li class="s"><b>PDF é o que conferimos melhor.</b> Nele medimos a resolução de
cada imagem dentro da folha, uma por uma. Se a sua arte é boa, é onde a nota
aparece com mais precisão</li>
cada imagem dentro da folha, uma por uma. É onde a conferência
de resolução fica mais precisa</li>
<li class="a"><b>PDF grande.</b> Sem UserUnit, a página passa do limite de 508 cm
do formato; divida a folha ou mande PNG. Envie um PDF de uma página por folha.</li>
<li class="a"><b>TIFF, PSD, AI e CDR</b> a gente aceita, mas ninguém consegue
@@ -906,7 +914,7 @@ h2 em{font-style:normal;color:var(--laranja)}
não deixa pagar</li>
<li class="n"><b>Pontinho de recorte.</b> A impressora enxerga qualquer
resíduo e imprime. Não existe pequeno demais: o site mostra onde cada um está
e só deixa pagar depois que você apagar</li>
e pede que você apague ou aceite imprimir assim</li>
<li class="n"><b>Cópias sobrepostas.</b> Duas iguais com 1 mm de diferença
saem duplicadas</li>
<li class="n"><b>Menos de 96 DPI.</b> Abaixo disso não imprimimos: sai
@@ -929,7 +937,6 @@ h2 em{font-style:normal;color:var(--laranja)}
<div class="compra" id="compra">
<div class="aoVivo" id="aoVivo"></div>
<div id="compraVals" hidden>
<div class="cLin"><span>Nota da arte</span><b id="cNota">—</b></div>
<div class="cLin"><span id="cMetroLbl">Metro</span><b id="cMetro">—</b></div>
<div class="cLin"><span>Metragem <small>(a cada 10 cm)</small></span><b id="cMetragem">—</b></div>
<p class="cObs" id="cObs"></p>
@@ -947,6 +954,13 @@ h2 em{font-style:normal;color:var(--laranja)}
</div>
</aside>
<dialog class="ampliaDlg mistaDlg" id="mistaDlg" aria-labelledby="mistaTit">
<div class="ampliaCab"><b id="mistaTit">Traços finos e áreas chapadas</b></div>
<div class="mistaCorpo">
<p id="mistaTxt"></p>
<div class="mistaBot"><button type="button" class="ec-go" id="mistaSegue">Imprimir assim mesmo (C1)</button><button type="button" id="mistaSep">Quero subir em dois arquivos</button></div>
</div>
</dialog>
<dialog class="ampliaDlg" id="ampliaDlg" aria-labelledby="ampliaTit">
<div class="ampliaCab"><b id="ampliaTit">Sua folha</b>
<button type="button" id="ampliaFecha" aria-label="Fechar"><svg class="ic" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg></button></div>
@@ -964,10 +978,9 @@ h2 em{font-style:normal;color:var(--laranja)}
<div class="qh">
<div><h3 id="qNome">sua folha</h3>
<span style="font-size:14.5px;color:var(--fraco)" id="qSub"></span></div>
<div style="text-align:right"><div class="pct" id="pct">—</div>
<span style="font-size:13.5px;color:var(--fraco)">qualidade</span></div>
<div style="display:none"><div class="pct" id="pct">—</div></div>
</div>
<div class="qbar"><i id="qbi" style="width:0%"></i></div>
<div class="qbar" style="display:none"><i id="qbi" style="width:0%"></i></div>
<div class="qitens" id="qitens"></div>
<div class="qbts">
<button class="qb chama" id="qOk">Seguir para o pedido</button>
@@ -1022,7 +1035,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<div class="cp"><label>WhatsApp <span class="obr" aria-hidden="true">*</span></label>
<input id="fZap" aria-required="true" autocomplete="off" inputmode="numeric" maxlength="15" placeholder="(16) 99999-9999">
<span class="err" id="eZap"></span></div>
<div class="cp larga"><label>E-mail para a nota <span class="obr" aria-hidden="true">*</span></label>
<div class="cp larga"><label>E-mail para o pedido <span class="obr" aria-hidden="true">*</span></label>
<input id="fMail" aria-required="true" autocomplete="off" type="email" placeholder="voce@empresa.com.br">
<span class="err" id="eMail"></span></div>
</div>
@@ -1079,9 +1092,17 @@ h2 em{font-style:normal;color:var(--laranja)}
<h4>Prova antes de imprimir</h4>
<label class="provaOp"><input type="checkbox" id="fProva">
<span><b>Quero aprovar uma prova antes de imprimir</b>
Imprimimos até 30 cm da sua folha e mandamos a foto pelo WhatsApp. O resto só é impresso
Imprimimos até 15 cm por classe de contração e mandamos a foto pelo WhatsApp. O resto só é impresso
depois do seu ok, então o pedido espera a sua resposta. Até 3 provas por pedido, sem custo.</span></label>
</div>
<div class="cxE" id="tratamentoBox" hidden>
<h4>Tratamento da arte</h4>
<label class="provaOp"><input type="checkbox" id="fTratamento">
<span><b>Quero o tratamento pelo designer — <span id="tratamentoPreco"></span></b>
O designer ajusta a arte para DTF, com fundo transparente e 300 DPI, e sobe o arquivo
pelo card. O prazo do pedido aumenta em 24 h.</span></label>
</div>
</div>
<aside class="resumo">
@@ -1126,7 +1147,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<div class="info2-preco">
<div class="et">Preço</div>
<h2>Preço único por produto</h2>
<p>A nota da arte aparece na tela antes de você pagar, para você entender o seu arquivo. Ela não muda o preço. Preço do metro:</p>
<p>O preço por metro depende do produto. Você confere a arte e a montagem antes de pagar:</p>
<table>
<thead><tr><th scope="col">Produto</th><th scope="col">Têxtil 57 cm</th><th scope="col">UV 27 cm</th></tr></thead>
<tbody>
@@ -1177,6 +1198,7 @@ h2 em{font-style:normal;color:var(--laranja)}
they share one global scope and run in this order, which is exactly how the
single inline script this replaces behaved. Order is therefore significant. -->
<script src="/site-config.js"></script>
<script src="/site-videos.js"></script>
<script src="/site-modes.js"></script>
<script src="/site-upload.js"></script>
<script src="/site-sheet.js"></script>

1
web/kanban-icon.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><path d="M8 5h24a2 2 0 0 1 2 2v19l-9 9H8a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" fill="#0B0B0C"/><path d="M16 9v22 M24 9v14" fill="none" stroke="#F5F5F3" stroke-width="2"/><path d="M34 26l-9 9v-7a2 2 0 0 1 2-2z" fill="#FF5F1F"/></svg>

After

Width:  |  Height:  |  Size: 287 B

143
web/kanban-viewer.js Normal file
View File

@@ -0,0 +1,143 @@
/* Kanban DTF — "Abrir e conferir" (Dropstar's third round, item 7).
The print file in the browser, full screen: zoom up to 100% real (one file
pixel, one screen pixel), the position in cm, the order's files one after
the other without closing, and a background behind the transparency (light,
dark or checkered, remembered: white art vanishes on light, black on dark).
A 57 cm x 15 m film is loaded in pieces, like a map: strips of the film's
width at the zoom shown (app/printtiles.py), only those on screen.
openViewer(files, {title, onClose}): files are [{name, label, manifest,
picture}], each with its strips' manifest (and their urls), or only a
picture when it has none. */
(function(){
const BG_KEY='dtf-viewer-bg';
const BACKGROUNDS=[['light','Claro'],['dark','Escuro'],['check','Xadrez']];
const PX_PER_CM=300/2.54;
// Decoded strips kept, the least recently drawn going first.
const KEEP=24;
const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!=null)n.textContent=text;if(cls)n.className=cls;return n;};
const cm=px=>(px/PX_PER_CM).toFixed(1).replace('.',',');
let bg='check';try{bg=localStorage.getItem(BG_KEY)||'check';}catch(_){}
window.openViewer=function(files,{title='',onClose}={}){
const dlg=el('dialog',null,'viewer');dlg.setAttribute('aria-label','Abrir e conferir');
const top=el('div',null,'vtop'), name=el('b',title,'vname');
const tabs=el('div',null,'vtabs'), tools=el('div',null,'vtools');
const where=el('span','','vwhere');
const zoomOut=el('button','−','vbtn'), zoomText=el('span','','vzoom'), zoomIn=el('button','+','vbtn');
const fit=el('button','Inteira','vbtn'), real=el('button','100%','vbtn');
const bgBox=el('div',null,'vbg');
const close=el('button','Fechar','vbtn pri');
for(const b of [zoomOut,zoomIn,fit,real,close])b.type='button';
zoomOut.setAttribute('aria-label','Diminuir');zoomIn.setAttribute('aria-label','Aumentar');
for(const [key,label] of BACKGROUNDS){const b=el('button',label,'vbtn');b.type='button';b.dataset.bg=key;
b.onclick=()=>{bg=key;try{localStorage.setItem(BG_KEY,key);}catch(_){}paintBg();draw();};bgBox.append(b);}
tools.append(where,zoomOut,zoomText,zoomIn,fit,real,bgBox,close);
top.append(name,tabs,tools);
const stage=el('div',null,'vstage'), canvas=el('canvas'), note=el('p','','vnote');
stage.append(canvas,note);dlg.append(top,stage);document.body.append(dlg);
let file=null, zoom=1, x=0, y=0, cache=new Map(), loading=new Set(), picture=null, raf=0;
const paintBg=()=>{for(const b of bgBox.children)b.setAttribute('aria-pressed',String(b.dataset.bg===bg));stage.dataset.bg=bg;};
const size=()=>file?.manifest?{w:file.manifest.width,h:file.manifest.height}:picture?{w:picture.width,h:picture.height}:{w:1,h:1};
const fitZoom=()=>{const {w,h}=size();return Math.min(stage.clientWidth/w,stage.clientHeight/h,1);};
const clamp=()=>{const {w,h}=size(), vw=stage.clientWidth/zoom, vh=stage.clientHeight/zoom;
x=w<=vw?(w-vw)/2:Math.max(0,Math.min(w-vw,x));y=h<=vh?(h-vh)/2:Math.max(0,Math.min(h-vh,y));};
function setZoom(z,cx=stage.clientWidth/2,cy=stage.clientHeight/2){
const fx=x+cx/zoom, fy=y+cy/zoom;
zoom=Math.max(Math.min(fitZoom(),0.02),Math.min(4,z));
x=fx-cx/zoom;y=fy-cy/zoom;clamp();
zoomText.textContent=Math.round(zoom*100)+'%';draw();
}
// The level whose detail is at least what the zoom shows.
function level(){
const levels=file.manifest.levels;let k=0;
while(k+1<levels.length&&levels[k+1].scale>=zoom)k++;
return k;
}
async function strip(k,i){
const key=k+':'+i;
if(cache.has(key)){const v=cache.get(key);cache.delete(key);cache.set(key,v);return v;}
if(loading.has(key))return null;
loading.add(key);
try{
const url=file.manifest.urls[k][i];
const res=await fetch(url,{referrerPolicy:'no-referrer'});
if(!res.ok)throw new Error('erro '+res.status);
const bmp=await createImageBitmap(await res.blob());
if(closed||file?.manifest?.urls[k]?.[i]!==url){bmp.close();return null;}
cache.set(key,bmp);
while(cache.size>KEEP){const [old,v]=cache.entries().next().value;v.close?.();cache.delete(old);}
draw();
}catch(e){note.textContent='Não foi possível carregar um pedaço do arquivo ('+e.message+').';}
finally{loading.delete(key);}
return null;
}
function draw(){cancelAnimationFrame(raf);raf=requestAnimationFrame(paint);}
function paint(){
if(closed)return;
const ratio=devicePixelRatio||1, W=stage.clientWidth, H=stage.clientHeight;
canvas.width=Math.round(W*ratio);canvas.height=Math.round(H*ratio);canvas.style.width=W+'px';canvas.style.height=H+'px';
const g=canvas.getContext('2d');g.setTransform(ratio,0,0,ratio,0,0);g.clearRect(0,0,W,H);
g.imageSmoothingEnabled=zoom<1;
if(picture){g.drawImage(picture,-x*zoom,-y*zoom,picture.width*zoom,picture.height*zoom);return;}
if(!file?.manifest)return;
const k=level(), L=file.manifest.levels[k], s=L.scale, rows=file.manifest.strip_rows;
const first=Math.max(0,Math.floor(y*s/rows)), last=Math.min(L.strips-1,Math.floor((y+H/zoom)*s/rows));
for(let i=first;i<=last;i++){
let bmp=cache.get(k+':'+i);
if(!bmp){strip(k,i);
// Meanwhile, a coarser level that is already here.
for(let c=k+1;c<file.manifest.levels.length&&!bmp;c++){
const C=file.manifest.levels[c], j=Math.floor(i*rows/s*C.scale/rows), have=cache.get(c+':'+j);
if(have){const top=j*rows/C.scale;g.drawImage(have,-x*zoom,(top-y)*zoom,have.width/C.scale*zoom,have.height/C.scale*zoom);bmp=null;break;}
}
continue;}
const top=i*rows/s;
g.drawImage(bmp,-x*zoom,(top-y)*zoom,bmp.width/s*zoom,bmp.height/s*zoom);
}
}
async function show(f,tab){
file=f;picture=null;cache.forEach(v=>v.close?.());cache=new Map();note.textContent='';
for(const b of tabs.children)b.setAttribute('aria-pressed',String(b===tab));
name.textContent=title?title+' · '+f.name:f.name;
if(!f.manifest){
note.textContent=f.picture?'Este arquivo não tem os pedaços para 100%: veja a prévia ou baixe o arquivo.':'Este arquivo não tem prévia: baixe para conferir.';
if(f.picture){try{const r=await fetch(f.picture);picture=await createImageBitmap(await r.blob());}catch(_){}}
}
zoom=fitZoom();x=0;y=0;clamp();zoomText.textContent=Math.round(zoom*100)+'%';draw();
}
files.forEach((f,i)=>{const b=el('button',f.label||f.name,'vtab');b.type='button';b.onclick=()=>show(f,b);tabs.append(b);});
tabs.hidden=files.length<2;
// Drag to move, wheel or pinch to zoom, keys for the rest.
let drag=null;
stage.onpointerdown=e=>{drag={x:e.clientX,y:e.clientY,ox:x,oy:y};stage.setPointerCapture(e.pointerId);};
stage.onpointermove=e=>{
const r=stage.getBoundingClientRect(), fx=x+(e.clientX-r.left)/zoom, fy=y+(e.clientY-r.top)/zoom;
where.textContent=cm(Math.max(0,fx))+' × '+cm(Math.max(0,fy))+' cm';
if(!drag)return;x=drag.ox-(e.clientX-drag.x)/zoom;y=drag.oy-(e.clientY-drag.y)/zoom;clamp();draw();};
stage.onpointerup=()=>{drag=null;};
// As on a map: the wheel zooms where the pointer is.
stage.onwheel=e=>{e.preventDefault();const r=stage.getBoundingClientRect();
setZoom(zoom*Math.exp(-e.deltaY*(e.deltaMode?40:1)/400),e.clientX-r.left,e.clientY-r.top);};
zoomIn.onclick=()=>setZoom(zoom*1.5);zoomOut.onclick=()=>setZoom(zoom/1.5);
fit.onclick=()=>setZoom(fitZoom());real.onclick=()=>setZoom(1);
dlg.onkeydown=e=>{if(e.key==='+'||e.key==='=')setZoom(zoom*1.5);else if(e.key==='-')setZoom(zoom/1.5);
else if(e.key==='0')setZoom(fitZoom());else if(e.key==='1')setZoom(1);};
const resize=()=>{clamp();draw();};addEventListener('resize',resize);
// Closed by its button or Escape, and by the dialog's own close as well,
// once: some browsers never send that event.
let closed=false;
const finish=()=>{if(closed)return;closed=true;cancelAnimationFrame(raf);removeEventListener('resize',resize);
const strips=[...cache.values()];cache=new Map();strips.forEach(v=>v.close?.());
if(dlg.open)dlg.close();dlg.remove();onClose?.();};
close.onclick=finish;
dlg.addEventListener('cancel',e=>{e.preventDefault();finish();});
dlg.onclose=finish;
paintBg();dlg.showModal();
if(files.length)show(files[0],tabs.children[0]);
return {close:finish};
};
})();

File diff suppressed because it is too large Load Diff

View File

@@ -2,143 +2,190 @@
<html lang="pt-BR"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Kanban DTF</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&amp;display=swap">
<link rel="icon" href="/kanban-icon.svg" type="image/svg+xml">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wdth,wght@75..100,400..700&amp;family=IBM+Plex+Mono:wght@400;500&amp;display=swap">
<script src="/theme.js"></script>
<link rel="stylesheet" href="/kanban.css">
</head><body>
<form id="login" class="login" hidden>
<div class="brand"><i aria-hidden="true">D</i>Kanban DTF</div>
<label>E-mail <input id="email" type="email" autocomplete="username" required></label>
<label>Senha <input id="password" type="password" autocomplete="current-password" required></label>
<button class="btn primary">Entrar</button>
<p id="login-status" class="hint" role="alert"></p>
<div class="lart" aria-hidden="true">
<div class="ltable">
<div class="lsheet">
<span class="lr lr-tl"></span><span class="lr lr-tr"></span><span class="lr lr-bl"></span><span class="lr lr-br"></span>
<span class="lw">57 cm</span>
<div class="lruler"></div>
<div class="lclip"><div class="lroll"><img src="/login-sheet.svg" alt=""><img src="/login-sheet.svg" alt=""><img src="/login-sheet.svg" alt=""><img src="/login-sheet.svg" alt=""></div></div>
</div>
</div>
<p class="ltag">Da arte recebida à folha conferida, num quadro só.</p>
</div>
<div class="lform">
<div class="lbrand"><svg class="mark" viewBox="0 0 40 40" aria-hidden="true"><path d="M8 5h24a2 2 0 0 1 2 2v19l-9 9H8a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" fill="currentColor"></path><path class="cut" d="M16 9v22 M24 9v14" fill="none" stroke-width="2"></path><path d="M34 26l-9 9v-7a2 2 0 0 1 2-2z" fill="var(--acc)"></path></svg><b>Kanban DTF</b></div>
<div class="lbox">
<div class="lbrand phone"><svg class="mark" viewBox="0 0 40 40" aria-hidden="true"><path d="M8 5h24a2 2 0 0 1 2 2v19l-9 9H8a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" fill="currentColor"></path><path class="cut" d="M16 9v22 M24 9v14" fill="none" stroke-width="2"></path><path d="M34 26l-9 9v-7a2 2 0 0 1 2-2z" fill="var(--acc)"></path></svg><b>Kanban DTF</b></div>
<h1>Bom ver você de novo</h1>
<label>E-mail <input id="email" type="email" autocomplete="username" required></label>
<label>Senha <input id="password" type="password" placeholder="Sua senha" autocomplete="current-password" required></label>
<button class="btn pri lg">Entrar</button>
<p id="login-status" class="hint" role="alert"></p>
<p class="lhelp">Esqueceu a senha? Peça ao administrador.</p>
</div>
</div>
</form>
<div id="app" hidden>
<div id="app" class="app" hidden>
<nav class="rail" aria-label="Seções">
<svg class="mark" viewBox="0 0 40 40" role="img" aria-label="Kanban DTF"><path d="M8 5h24a2 2 0 0 1 2 2v19l-9 9H8a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" fill="currentColor"></path><path class="cut" d="M16 9v22 M24 9v14" fill="none" stroke-width="2"></path><path d="M34 26l-9 9v-7a2 2 0 0 1 2-2z" fill="var(--acc)"></path></svg>
<button class="nav" type="button" data-tab="board" aria-selected="true"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M3 3.75h4v12.5H3z M8 3.75h4v8.5H8z M13 3.75h4v10.5h-4z"></path></svg><span>Produção</span></button>
<button class="nav" type="button" data-tab="quotes" aria-selected="false"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M5 2.75h7l3 3v11.5H5z M12 2.75v3h3 M7.5 9.5h5 M7.5 12.5h5 M7.5 15h3"></path></svg><span>Cotações</span><span class="pip" id="badge-quotes"></span></button>
<button class="nav" type="button" data-tab="payments" aria-selected="false"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 5h14.5v10H2.75z M2.75 8.25h14.5 M5.5 12.25h3"></path></svg><span>Pagamentos</span><span class="pip" id="badge-payments"></span></button>
<button class="nav" type="button" data-tab="stats" aria-selected="false"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M3 16.75h14 M4.75 14V9.5 M8.5 14V4.5 M12.25 14V7.5 M16 14v-3.5"></path></svg><span>Números</span></button>
<button class="nav" type="button" data-tab="integrations" aria-selected="false"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M8.5 6.5H6a3.25 3.25 0 0 0 0 6.5h2.5 M11.5 6.5H14a3.25 3.25 0 0 1 0 6.5h-2.5 M7 9.75h6"></path></svg><span>Integrações</span><span class="pip" id="badge-integrations" title="A pasta da fila precisa de atenção"></span></button>
<button class="nav" type="button" data-tab="users" aria-selected="false" hidden><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M6.75 6.25a3.25 3.25 0 1 0 6.5 0a3.25 3.25 0 1 0 -6.5 0 M3.75 17c.6-3.2 3.1-5 6.25-5s5.65 1.8 6.25 5"></path></svg><span>Usuários</span></button>
<button class="nav phone" id="more-nav" type="button" aria-haspopup="menu"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M4.1 10a.9.9 0 1 0 1.8 0a.9.9 0 1 0 -1.8 0 M9.1 10a.9.9 0 1 0 1.8 0a.9.9 0 1 0 -1.8 0 M14.1 10a.9.9 0 1 0 1.8 0a.9.9 0 1 0 -1.8 0"></path></svg><span>Mais</span><span class="pip" id="badge-more"></span></button>
<span class="grow"></span>
<button class="railmachine" id="rail-machine" type="button" hidden><small>Máquina</small><b></b></button>
<button class="rbtn" id="theme-rail" type="button"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path></path></svg></button>
<div class="account">
<button class="avatar" id="account" type="button" aria-haspopup="menu" aria-label="Minha conta"><span id="initials">·</span></button>
<div class="menu acct" id="account-menu" role="menu" hidden>
<div class="menu-head"><span class="ava" id="who-ava"><span id="who-initials"></span><i class="pres on"></i></span><span class="who-text"><b id="who"></b><span id="who-role"></span></span></div>
<button class="menuitem" id="my-password" type="button" role="menuitem"><svg class="i m" viewBox="0 0 20 20" aria-hidden="true"><path d="M6.75 6.25a3.25 3.25 0 1 0 6.5 0a3.25 3.25 0 1 0 -6.5 0 M3.75 17c.6-3.2 3.1-5 6.25-5s5.65 1.8 6.25 5"></path></svg>Minha conta</button>
<button class="menuitem" id="account-machine" type="button" role="menuitem" hidden><svg class="i m" viewBox="0 0 20 20" aria-hidden="true"><path d="M5.75 7.5V3h8.5v4.5 M5.75 14H3V7.5h14V14h-2.75 M5.75 11.25h8.5v5.75h-8.5z"></path></svg>Trocar de máquina<span class="lbl"></span></button>
<div class="menusep"></div>
<button class="menuitem" id="logout" type="button" role="menuitem"><svg class="i m" viewBox="0 0 20 20" aria-hidden="true"><path d="M8 3.25H3.75v13.5H8 M12 6.5l3.5 3.5-3.5 3.5 M15.5 10H7.5"></path></svg>Sair</button>
</div>
</div>
</nav>
<div class="shell">
<header class="top">
<div class="brand"><i aria-hidden="true">D</i>Kanban DTF</div>
<nav class="tabs" aria-label="Seções">
<button type="button" data-tab="board" aria-selected="true">Produção <span class="count" id="count-board"></span></button>
<button type="button" data-tab="quotes" aria-selected="false">Cotações <span class="badge" id="badge-quotes"></span></button>
<button type="button" data-tab="payments" aria-selected="false">Pagamentos <span class="badge warn" id="badge-payments"></span></button>
<button type="button" data-tab="stats" aria-selected="false">Números</button>
<button type="button" data-tab="integrations" aria-selected="false">Integrações <span class="badge warn" id="badge-integrations" title="A pasta da fila precisa de atenção"></span></button>
<button type="button" data-tab="users" aria-selected="false" hidden>Usuários</button>
</nav>
<div class="ptitle"><svg class="mark phone" viewBox="0 0 40 40" aria-hidden="true"><path d="M8 5h24a2 2 0 0 1 2 2v19l-9 9H8a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" fill="currentColor"></path><path class="cut" d="M16 9v22 M24 9v14" fill="none" stroke-width="2"></path><path d="M34 26l-9 9v-7a2 2 0 0 1 2-2z" fill="var(--acc)"></path></svg><h1 id="page-title">Produção</h1><span id="board-summary"></span></div>
<button class="mic phone" id="search-open" type="button" aria-label="Buscar" aria-expanded="false"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M3.0 8.75a5.75 5.75 0 1 0 11.5 0a5.75 5.75 0 1 0 -11.5 0 M13 13l4.25 4.25"></path></svg></button>
<button class="mic phone" id="filter-open" type="button" aria-label="Filtros"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M3 5h14 M5.5 10h9 M8 15h4"></path></svg><span class="dotn" id="filter-dot" hidden></span></button>
<div class="searchbox">
<button class="mic phone" id="search-back" type="button" aria-label="Voltar"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M12 5.5L7.5 10l4.5 4.5"></path></svg></button>
<label class="search">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><path d="M20 20l-3.5-3.5"></path></svg>
<input id="search" type="search" placeholder="Buscar em pedidos e cotações: cliente, CPF/CNPJ, nº" aria-label="Buscar em pedidos e cotações" autocomplete="off" role="combobox" aria-expanded="false" aria-controls="search-results">
<svg class="i m" viewBox="0 0 20 20" aria-hidden="true"><path d="M3.0 8.75a5.75 5.75 0 1 0 11.5 0a5.75 5.75 0 1 0 -11.5 0 M13 13l4.25 4.25"></path></svg>
<input id="search" type="search" placeholder="Buscar cliente, CPF/CNPJ ou pedido" aria-label="Buscar em pedidos e cotações" autocomplete="off" role="combobox" aria-expanded="false" aria-controls="search-results">
<kbd>/</kbd>
</label>
<div id="search-results" class="results" role="listbox" aria-label="Resultados da busca" hidden></div>
</div>
<span id="tiny" class="tinydot"></span>
<div class="refresh">
<button class="btn ghost" id="refresh" type="button"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-2.64-6.36"></path><path d="M21 3v6h-6"></path></svg>Atualizar</button>
<select id="refresh-every" aria-label="Atualizar sozinho a cada">
<option value="0">Desligado</option><option value="10">10 s</option><option value="30">30 s</option>
<option value="60">1 min</option><option value="300">5 min</option><option value="900">15 min</option>
</select>
</div>
<button class="mymachine" id="my-machine" type="button" hidden></button>
<div class="morewrap account">
<button class="btn ghost" id="account" type="button" aria-haspopup="menu" aria-label="Minha conta"><span id="initials">·</span></button>
<div class="menu" id="account-menu" role="menu" hidden>
<div class="menu-head"><b id="who"></b><span id="who-role"></span></div>
<button class="menuitem" id="my-password" type="button">Minha senha</button>
<button class="menuitem" id="logout" type="button">Sair</button>
<div class="syncwrap">
<button class="sync" id="sync" type="button" aria-haspopup="menu" aria-expanded="false"><span class="livedot" aria-hidden="true"></span><span id="sync-at">Atualizar</span></button>
<div class="menu syncmenu" id="sync-menu" role="menu" hidden>
<div class="menu-label">Atualizar sozinho</div>
<div id="sync-every"></div>
<div class="menusep"></div>
<button class="menuitem" id="refresh" type="button" role="menuitem"><svg class="i m" viewBox="0 0 20 20" aria-hidden="true"><path d="M16.25 10a6.25 6.25 0 1 1-1.83-4.42 M16.5 3.25V6.5h-3.25"></path></svg>Atualizar agora</button>
</div>
<select id="refresh-every" aria-label="Atualizar sozinho a cada" hidden><option value="0">Desligado</option><option value="10">A cada 10 s</option><option value="30">A cada 30 s</option><option value="60">A cada 1 min</option><option value="300">A cada 5 min</option><option value="900">A cada 15 min</option></select>
</div>
</header>
<p id="status" role="status"></p>
<main>
<section id="tab-board">
<div class="bar"><h1>Produção</h1><span class="muted" id="board-summary"></span>
<div class="filterbar">
<div class="filtertags" id="filter-tags"></div>
<div class="filterwrap">
<button class="btn" id="filter-btn" type="button" aria-expanded="false" aria-controls="filter-pop">Filtros <span class="badge" id="filter-count" hidden></span></button>
<div class="filterpop" id="filter-pop" role="dialog" aria-label="Filtros" hidden></div>
</div>
<div class="mtabs" id="col-tabs" role="tablist" aria-label="Etapas"></div>
<div class="tools">
<div class="seg" id="product-seg" role="group" aria-label="Produto"></div>
<div class="filterwrap">
<button class="btn" id="filter-btn" type="button" aria-expanded="false" aria-controls="filter-pop"><svg class="i m" viewBox="0 0 20 20" aria-hidden="true"><path d="M3 5h14 M5.5 10h9 M8 15h4"></path></svg>Filtros<span class="coln" id="filter-count" hidden></span></button>
<div class="pop filterpop" id="filter-pop" role="dialog" aria-label="Filtros" hidden></div>
</div>
<div class="filtertags" id="filter-tags"></div>
</div>
<div class="kan" id="kan"></div>
<div id="latebar" class="latebar" hidden></div>
<div class="board" id="kan"></div>
</section>
<section id="tab-quotes" hidden>
<div class="split">
<div class="list">
<div class="lhead"><h1>Cotações</h1><span>pedidos ainda não pagos</span></div>
<div class="chips" id="quote-filters"></div>
<label class="qsearch">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><path d="M20 20l-3.5-3.5"></path></svg>
<input id="quote-q" type="search" placeholder="Filtrar por e-mail, CPF/CNPJ ou WhatsApp" aria-label="Filtrar cotações por cliente" autocomplete="off">
</label>
<div class="chips small" id="quote-chips"></div>
<div id="quote-list"></div>
<div class="qlist">
<div class="qtools">
<div class="seg" id="quote-filters" role="group" aria-label="Situação"></div>
<div class="toggles" id="quote-chips"></div>
</div>
<div class="qrows" id="quote-list"></div>
<div id="quote-pager"></div>
</div>
<div class="pane" id="reviews"></div>
<div class="review" id="reviews"></div>
</div>
</section>
<section id="tab-payments" class="page" hidden>
<h1>Pagamentos</h1>
<section id="payments"></section>
</section>
<section id="tab-stats" class="page" hidden>
<div class="pagehead"><h1>Números</h1><div class="statchips" id="stats-period"></div></div>
<p class="faint stats-note" id="stats-note">Pedidos pagos no período. Pedidos de teste e cancelados ficam de fora.</p>
<div class="kpis" id="stats-kpis"></div>
<section class="statbox"><h2>Metros por dia</h2><div class="chart" id="stats-chart"></div></section>
<section class="statbox"><h2>Por máquina</h2>
<p class="faint stats-hint">Pedidos que chegaram a Finalizado no período, na máquina em que estavam. Impresso: o filme da folha, não o metro cobrado.
Metros por hora: sobre o tempo em Imprimindo; pedidos imprimindo juntos na mesma máquina contam esse tempo uma vez.</p>
<table class="log"><thead><tr><th scope="col">Máquina</th><th scope="col">Impresso</th><th scope="col">Metros por hora</th><th scope="col">Último finalizado</th><th scope="col">Agora</th></tr></thead><tbody id="stats-machines"></tbody></table>
</section>
<section class="statbox"><h2>Retrabalho</h2>
<p class="faint stats-hint">Metros refeitos sobre o filme impresso no período (Por máquina), só os retrabalhos autorizados, pela data em que foram abertos. Meta de 0,4% por causa, 1,6% no total da casa; arte ruim aprovada pelo cliente fica fora da meta. <span id="stats-rework-film"></span></p>
<table class="log"><thead><tr><th scope="col">Causa</th><th scope="col">Refeito</th><th scope="col">Do impresso</th><th scope="col">Meta</th></tr></thead><tbody id="stats-rework"></tbody></table>
<h3 class="stats-sub">Da casa, por quem imprimiu</h3>
<table class="log"><thead><tr><th scope="col">Quem imprimiu</th><th scope="col">Refeito</th></tr></thead><tbody id="stats-rework-printers"></tbody></table>
<h3 class="stats-sub">Aguardando autorização</h3>
<ul class="plainlist" id="stats-rework-pending"></ul></section>
<section class="statbox"><h2>Por origem</h2>
<p class="faint stats-hint">Por onde o pedido entrou: o Site, os lotes do Dropflow ou a equipe, em Atendimento. O tempo vai do pagamento ao Finalizado, sem o tempo em Aguardando contato.</p>
<table class="log"><thead><tr><th scope="col">Origem</th><th scope="col">Pedidos</th><th scope="col">Metros</th><th scope="col">Recebido</th><th scope="col">Do pagamento ao Finalizado</th></tr></thead><tbody id="stats-origins"></tbody></table></section>
<section class="statbox"><h2>Artes tratadas</h2>
<p class="faint stats-hint">Pedidos do período em que o arquivo final aprovado não é a arte do cliente: alguém da equipe preparou. Por quem aprovou o arquivo.</p>
<table class="log"><thead><tr><th scope="col">Quem aprovou</th><th scope="col">Pedidos</th></tr></thead><tbody id="stats-treated"></tbody></table></section>
<section class="statbox"><h2>Tempo em cada etapa</h2>
<p class="faint stats-hint">Tempo mediano por pedido: um pedido que voltou para a etapa soma o tempo de cada passagem. O tempo em Aguardando contato não conta, aqui nem em “Do pagamento ao Finalizado”.</p>
<table class="log"><thead><tr><th scope="col">Etapa</th><th scope="col">Tempo mediano</th><th scope="col">Pedidos que passaram</th><th scope="col">Agora</th></tr></thead><tbody id="stats-stages"></tbody></table>
</section>
<div class="pagetools">
<div class="seg" id="stats-period" role="group" aria-label="Período"></div>
<div class="calwrap" id="stats-range"></div>
<span class="lbl right" id="stats-note"></span>
</div>
<div class="panel" id="stats-kpis"></div>
<section class="panel"><div class="phead"><h2>Metros por dia</h2><span class="legend right" id="stats-legend"></span></div><div id="stats-chart"></div></section>
<div class="g12">
<section class="panel clip s4"><div class="phead"><h2>Por máquina</h2><span class="hint tip-r" tabindex="0" data-tip="Pedidos que chegaram a Finalizado no período, na máquina em que estavam. Impresso: o filme da folha, não o metro cobrado. Por hora: sobre o tempo em Imprimindo; pedidos imprimindo juntos na mesma máquina contam esse tempo uma vez."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<div class="fillbox short"><div class="scrollin"><table class="table"><thead><tr><th scope="col">Máquina</th><th scope="col" class="r">Impresso</th><th scope="col" class="r">Por hora</th><th scope="col">Agora</th></tr></thead><tbody id="stats-machines"></tbody></table></div></div></section>
<section class="panel clip s4"><div class="phead"><h2>Por origem</h2><span class="hint" tabindex="0" data-tip="Por onde o pedido entrou: o Site, os lotes do Dropflow ou a equipe, em Atendimento. Até Finalizado: do pagamento ao Finalizado, mediana, sem o tempo em Aguardando contato."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<table class="table"><thead><tr><th scope="col">Origem</th><th scope="col" class="r">Pedidos</th><th scope="col" class="r">Metros</th><th scope="col" class="r">Recebido</th><th scope="col" class="r">Até Finalizado</th></tr></thead><tbody id="stats-origins"></tbody></table></section>
<section class="panel s4"><div class="phead"><h2>Artes tratadas, por quem aprovou</h2><span class="hint tip-l" tabindex="0" data-tip="Pedidos do período em que o arquivo final aprovado não é a arte do cliente: alguém da equipe preparou."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<div class="fillbox short"><div class="scrollin bylist" id="stats-treated"></div></div></section>
</div>
<div class="g12">
<section class="panel clip s6"><div class="phead"><h2>Retrabalho</h2><span class="hint" tabindex="0" data-tip="Metros refeitos sobre o filme impresso no período, só os autorizados, pela data em que foram abertos. Arte ruim aprovada pelo cliente fica fora da meta."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span><span class="pill warn right" id="stats-rework-pending-pill" hidden></span></div>
<table class="table"><thead><tr><th scope="col">Causa</th><th scope="col" class="r">Refeito</th><th scope="col" class="w50" id="stats-rework-film">Do impresso, contra a meta</th></tr></thead><tbody id="stats-rework"></tbody></table>
<details class="psub"><summary>Por quem imprimiu e aguardando autorização</summary>
<h3>Da casa, por quem imprimiu</h3>
<table class="table"><tbody id="stats-rework-printers"></tbody></table>
<h3>Aguardando autorização</h3><ul class="plainlist" id="stats-rework-pending"></ul></details></section>
<section class="panel clip s6"><div class="phead"><h2>Tempo em cada etapa</h2><span class="hint tip-l" tabindex="0" data-tip="Tempo mediano por pedido: quem voltou para a etapa soma cada passagem. O tempo em Aguardando contato não conta."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span><button class="btn right" id="edit-stage-limits" type="button" hidden>Editar tempos</button></div>
<table class="table"><thead><tr><th scope="col">Etapa</th><th scope="col" class="r">Média</th><th scope="col" class="r">Aceitável</th><th scope="col" class="r">Estouros</th><th scope="col">Agora</th></tr></thead><tbody id="stats-stages"></tbody></table></section>
</div>
<section class="panel clip"><div class="phead"><h2>Pedidos sem pagamento</h2><span class="hint" tabindex="0" data-tip="Cotações aprovadas no período, pela data de aprovação. Pagas viraram pedido; expiradas passaram de 24 horas sem pagamento; aguardando ainda podem ser pagas. A taxa de abandono é expiradas sobre pagas mais expiradas."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<table class="table"><thead><tr><th scope="col">Indicador</th><th scope="col" class="r">Valor</th></tr></thead><tbody id="stats-unpaid"></tbody></table></section>
<section class="panel clip" id="stats-machine-panel"><div class="phead"><h2>Máquinas, mês a mês</h2><div class="mnav" id="stats-machine-nav"></div></div>
<div class="fillbox machinebox"><div class="scrollin"><table class="table machine-month"><thead id="stats-machine-head"></thead><tbody id="stats-machine-body"></tbody></table></div></div>
<p class="phint" id="stats-machine-note"></p></section>
<section class="panel clip"><div class="phead"><h2>Velocidade do site e do Prumo</h2><span class="hint tip-l" tabindex="0" data-tip="Média e p95 do que o cliente sente, por pedido pago no período: abrir a página, subir o arquivo (segundos por MB), a conferência do Prumo, a montagem das avulsas, a geração do arquivo final por 10 m e o tempo do evento de pagamento até o card. Referências: página < 3 s; conferência < 30 s; geração < 2 min por 10 m; card em até 1 min."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<table class="table"><thead><tr><th scope="col">Etapa</th><th scope="col" class="r">Média</th><th scope="col" class="r">p95</th><th scope="col" class="r">Amostras</th></tr></thead><tbody id="stats-speed"></tbody></table></section>
</section>
<section id="tab-users" class="page" hidden>
<div class="pagehead"><h1>Usuários</h1><button class="btn primary" id="new-user" type="button">Novo usuário</button></div>
<p class="faint stats-note">Quem entra no Kanban e o que cada perfil pode fazer. Administrador: tudo, inclusive esta página.
Gestão: tudo, menos usuários; no quadro só puxa para trás, com motivo (Correção ou voltar uma etapa). Designer: vê todos os pedidos, aprova e recusa o arquivo final, pede correção.
Operador: escolhe a máquina ao entrar; vê o quadro todo, puxa da fila para a máquina dele, imprime e passa para a Revisão, e só move os cards da máquina dele. Revisor: confere a folha impressa e libera para Finalizado; o Administrador também pode liberar.
Vendedor: só consulta. Financeiro: vê o quadro, Pagamentos, Números e Cotações e cancela pedido, com o motivo; não move card nem mexe em arquivo.
Retrabalho: a Gestão abre, com a causa; o Administrador autoriza.</p>
<section class="statbox"><table class="log"><thead><tr><th scope="col">Nome</th><th scope="col">Perfil</th><th scope="col">Máquina agora</th><th scope="col">Último acesso</th><th scope="col"></th></tr></thead><tbody id="users-list"></tbody></table></section>
<div class="pagehead"><h2>Máquinas</h2><button class="btn" id="new-machine" type="button">Nova máquina</button></div>
<p class="faint stats-note">Cada pedido vai para a máquina do produto com menos metros em aberto, dentro do limite. No pedido dá para trocar.</p>
<div class="mtiles" id="machines-list"></div>
<section class="panel clip">
<div class="phead"><h2>Pessoas</h2><span class="n" id="users-count"></span>
<span class="plegend"><span title="Usou o sistema nos últimos 15 minutos"><i class="pres on"></i>Ativo agora</span><span><i class="pres away"></i>Inativo</span><span><i class="pres never"></i>Nunca entrou</span><span><i class="pres off"></i>Desativado</span></span>
<button class="btn right" id="new-user" type="button"><svg class="i m" viewBox="0 0 20 20" aria-hidden="true"><path d="M10 4v12 M4 10h12"></path></svg>Novo usuário</button></div>
<div class="mlist phone" id="users-phone"></div>
<div class="scrollbox people"><table class="table"><thead><tr><th scope="col">Nome</th><th scope="col">Perfil</th><th scope="col">Máquina agora</th><th scope="col">Último acesso</th><th scope="col"><span class="vh">Editar</span></th></tr></thead><tbody id="users-list"></tbody></table></div>
</section>
<div class="cols2 lean">
<section class="panel clip"><div class="phead"><h2>O que cada perfil faz</h2><span class="canlegend right"><span><i class="can"></i>faz</span><span><i class="can view"></i>só consulta</span></span></div>
<div class="scrollx"><table class="table matrix" id="roles-matrix"></table></div></section>
<section class="panel clip"><div class="phead"><h2>Máquinas</h2><span class="n" id="machines-count"></span><button class="btn right" id="new-machine" type="button"><svg class="i m" viewBox="0 0 20 20" aria-hidden="true"><path d="M10 4v12 M4 10h12"></path></svg>Nova máquina</button></div>
<p class="phint">Cada pedido vai para a máquina do produto com menos metros em aberto, dentro do limite. No pedido dá para trocar.</p>
<div class="fillbox"><div class="mtiles" id="machines-list"></div></div></section>
</div>
</section>
<section id="tab-integrations" class="page" hidden>
<h1>Integrações</h1>
<section><div class="integ-list" id="integrations"></div></section>
<section id="event-log"><h2>Envios ao Tiny</h2>
<div class="filters" id="event-filters"></div>
<table class="log"><thead><tr><th scope="col">Quando</th><th scope="col">Pedido</th><th scope="col">Evento</th><th scope="col">Resultado</th></tr></thead><tbody id="events"></tbody></table>
<div class="panel" id="integrations"></div>
<section class="panel clip" id="site-videos-panel" hidden>
<div class="phead"><h2>Vídeos do Site</h2></div>
<p class="phint">Envie MP4 ou WebM e legenda VTT. Escolha o produto para o vídeo flutuante e publique quando estiver pronto.</p>
<div id="site-videos-list" class="siteVideoList"></div>
</section>
<section class="panel clip" id="event-log">
<div class="phead"><h2>Envios ao Tiny</h2><div class="pfilters" id="event-filters"></div></div>
<div class="scrollbox log"><table class="table"><thead><tr><th scope="col">Quando</th><th scope="col">Pedido</th><th scope="col">Evento</th><th scope="col">Resultado</th></tr></thead><tbody id="events"></tbody></table></div>
<div id="events-more"></div>
</section>
</section>
</main>
</div>
</div>
<div class="drawer" id="drawer" hidden>
<div class="dwrap" id="drawer" hidden>
<div class="scrim" id="scrim"></div>
<aside class="panel" id="panel" aria-label="Pedido"></aside>
<aside class="drawer" id="panel" aria-label="Pedido"></aside>
</div>
<script src="/upload.js"></script><script src="/kanban.js"></script></body></html>
<script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script></body></html>

File diff suppressed because it is too large Load Diff

129
web/login-sheet.svg Normal file
View File

@@ -0,0 +1,129 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 570 1000" width="570" height="1000"><g transform="translate(22.5 13.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(165.0 13.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(307.5 13.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(450.0 13.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(22.5 138.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(165.0 138.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(307.5 138.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(450.0 138.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(22.5 263.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(165.0 263.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(307.5 263.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(450.0 263.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(22.5 388.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(165.0 388.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(307.5 388.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(450.0 388.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(22.5 513.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(165.0 513.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(307.5 513.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(450.0 513.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(22.5 638.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(165.0 638.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(307.5 638.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(450.0 638.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(22.5 763.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(165.0 763.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(307.5 763.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(450.0 763.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(22.5 888.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(165.0 888.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g><g transform="translate(307.5 888.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(0 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(45 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(90 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(135 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(180 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(225 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(270 50 50)"/><ellipse cx="50" cy="25" rx="14" ry="23" fill="#F6C33B" transform="rotate(315 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(22 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(67 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(112 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(157 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(202 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(247 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(292 50 50)"/><ellipse cx="50" cy="32" rx="7" ry="13" fill="#FFE08A" transform="rotate(337 50 50)"/><circle cx="50" cy="50" r="13" fill="#F28C1F"/><circle cx="46" cy="47" r="1.8" fill="#FFE08A"/><circle cx="54" cy="48" r="1.8" fill="#FFE08A"/><circle cx="50" cy="54" r="1.8" fill="#FFE08A"/></g><g transform="translate(450.0 888.75) rotate(0 48.75 48.75) scale(0.975)"><ellipse cx="22" cy="80" rx="15" ry="10" fill="#D9561C"/><ellipse cx="78" cy="80" rx="15" ry="10" fill="#D9561C"/>
<ellipse cx="50" cy="64" rx="29" ry="27" fill="#F2741F"/><ellipse cx="50" cy="40" rx="31" ry="21" fill="#F2741F"/>
<circle cx="33" cy="25" r="13" fill="#F2741F"/><circle cx="67" cy="25" r="13" fill="#F2741F"/>
<circle cx="33" cy="25" r="9" fill="#1A1210"/><circle cx="67" cy="25" r="9" fill="#1A1210"/>
<circle cx="30" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="64" cy="21.5" r="3" fill="#FFFFFF"/><circle cx="36" cy="28" r="1.3" fill="#FFFFFF"/><circle cx="70" cy="28" r="1.3" fill="#FFFFFF"/>
<path d="M42 44 Q50 49 58 44" stroke="#8A2E0B" stroke-width="2.4" fill="none" stroke-linecap="round"/>
<ellipse cx="50" cy="68" rx="15" ry="17" fill="#F7CF7A"/><circle cx="45" cy="63" r="2.6" fill="#E8862F"/><circle cx="55" cy="68" r="3.2" fill="#E8862F"/><circle cx="47" cy="75" r="2.2" fill="#E8862F"/><circle cx="54" cy="58" r="1.8" fill="#E8862F"/>
<ellipse cx="37" cy="90" rx="8" ry="4.5" fill="#D9561C"/><ellipse cx="63" cy="90" rx="8" ry="4.5" fill="#D9561C"/>
<path d="M26 47 Q32 58 37 54 M74 47 Q68 58 63 54" stroke="#D9561C" stroke-width="5" fill="none" stroke-linecap="round"/></g></svg>

After

Width:  |  Height:  |  Size: 46 KiB

View File

@@ -134,6 +134,8 @@ button:disabled{opacity:.6;cursor:default}
.arquivo>div{flex:1;min-width:0;display:flex;flex-direction:column}
.arquivo b{overflow-wrap:anywhere;font-size:15px}
.arquivo span{font-size:14px;color:var(--fraco)}
.fotoPed{display:flex;flex-direction:column;align-items:flex-start;gap:10px;margin-bottom:14px}
.fotoPed img{display:block;max-width:100%;height:auto;border:1px solid var(--linha);border-radius:var(--raio2)}
.correcaoForm{display:flex;flex-direction:column;padding:16px;border-radius:var(--raio2);background:var(--cinza)}
.correcaoForm label{margin:10px 0 5px;font-size:14px;font-weight:600;color:var(--texto2)}
.correcaoForm textarea{height:auto;padding:10px 13px;resize:vertical}

View File

@@ -29,6 +29,8 @@ function icone(nome){
}
const PRODUTO={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',
uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'};
// Artes avulsas que o Site separou por traço (item 17): uma folha por item.
const nomeItem=item=>(PRODUTO[item.mode]||item.mode)+(item.split?' · folha '+item.split.part+' de '+item.split.of:'');
// The order's steps as the customer sees them (Dropstar's flow, 2026-10-23).
const TRILHA=['rec','tra','imp','rev','fin'];
const TAMANHO=10;
@@ -199,7 +201,7 @@ function itensPedido(snapshot){
const ul=node('ul',null,'itensPed');
for(const item of snapshot.items){
const li=node('li');
li.append(node('span',PRODUTO[item.mode]||item.mode,'nome'),node('span',metros(item.billed_metres),'qt'),node('b',money(item.total_cents)));
li.append(node('span',nomeItem(item),'nome'),node('span',metros(item.billed_metres),'qt'),node('b',money(item.total_cents)));
ul.append(li);
}
const f=snapshot.freight;
@@ -244,10 +246,22 @@ async function details(id,container,criado){
}
container.append(arq);
}
if(order.state==='fin'&&order.reviews?.length){
const sec=node('div',null,'secao fotoPedSec');sec.append(node('h4','Foto do seu pedido'));
for(const review of order.reviews){
const view=await api('/customer/orders/'+id+'/reviews/'+review.id+'/view');
const row=node('div',null,'fotoPed');
const img=node('img');img.alt='Foto da folha impressa do pedido #'+order.number;
img.loading='lazy';img.src=view.url;
const link=node('a','Baixar foto','bSec');link.href=view.url;link.download=view.name;link.target='_blank';link.rel='noopener noreferrer';
row.append(img,link);sec.append(row);
}
container.append(sec);
}
if(order.state==='cor'){
const form=node('form',null,'secao correcaoForm');form.append(node('h4','Enviar arte corrigida'));
const inputs=order.snapshot.items.map((item,index)=>{
const label=node('label',(index+1)+'. '+(PRODUTO[item.mode]||item.mode));
const label=node('label',(index+1)+'. '+nomeItem(item));
const input=node('input');input.type='file';input.multiple=true;input.dataset.item=index;
form.append(label,input);return input;
});

View File

@@ -55,7 +55,8 @@ function pintaPedido(){
const aPagar = itensAPagar();
const itens = aPagar.reduce((t,it)=>t+it.total,0);
const frete = entrega.tipo==='frete' && entrega.cotado ? entrega.valor : 0;
const soma = itens + frete;
const tratamento=$('fTratamento')?.checked&&TAXA_TRATAMENTO>0?TAXA_TRATAMENTO:0;
const soma = itens + frete + tratamento;
const n = aPagar.length, noCarrinho = pedido.length + (itemAtual?1:0);
$('resLin').innerHTML =
'<div class="l"><span>'+n+(n===1?' item':' itens')+'</span><b>'+rs(itens)+'</b></div>'+
@@ -64,6 +65,7 @@ function pintaPedido(){
'</span><b>'+
(entrega.tipo==='retira' ? '<span style="color:var(--verde-ml)">Grátis</span>'
: entrega.cotado ? rs(frete) : 'a cotar')+'</b></div>'+
(tratamento?'<div class="l"><span>Tratamento da arte · +24 h</span><b>'+rs(tratamento)+'</b></div>':'')+
'<div class="l"><span>Revisão e reencaixe</span>'+
'<b><span style="color:var(--verde-ml)">Grátis</span></b></div>';
$('carrTot').textContent=rs(soma);
@@ -73,6 +75,8 @@ function pintaPedido(){
// The proof is only for orders above 10 m (Dropstar, 2026-10-28): below it the box is gone.
const prova=$('fProva');
if(prova){ const longo=aPagar.reduce((t,it)=>t+(it.cob||0),0)>10; prova.closest('.cxE').hidden=!longo; if(!longo) prova.checked=false; }
const tratamentoBox=$('tratamentoBox');
if(tratamentoBox){tratamentoBox.hidden=!(TAXA_TRATAMENTO>0);if(tratamentoBox.hidden)$('fTratamento').checked=false;}
$('bPagar').disabled = !cartPodeEnviar() || !entrega.cotado || !clienteOk() || !enderecoOk();
if(pedido.length || itemAtual) $('carr').classList.add('on');
if($('cartN')){ $('cartN').textContent=noCarrinho>99?'99+':noCarrinho; $('cartN').hidden=!noCarrinho;
@@ -81,13 +85,17 @@ function pintaPedido(){
}
// Um preço por produto (Dropstar, 23/10/2026): a nota aparece, mas não entra na conta.
// A arte avulsa como fonte da montagem: largura, comprimento, cópias e giro.
const fonteDaArte=x=>({kind:'artwork',width_cm:x.cm,length_cm:+(x.cm*propDe(x)).toFixed(4),
copies:x.q,rotation_degrees:x.giro||0,mirrored:!!x.esp,
measurement:(x.src||x.semPrevia)?'file':'customer'});
function carrinho(){
const base=precoMetro(), cob=cobrar(metros);
const base=precoMetro(), cob=cobrarMontagem();
const extra=folhaManual()? TAXA_MANUAL : 0;
const unit=base+extra, tot=cob*unit, sobra=+(cob-metros).toFixed(2);
$('carr').classList.add('on');
let l='<div class="l"><span>'+MODOS[modo].tit+'</span><b>'+rs(base)+'/m</b></div>';
if(!ehFolha()) l += '<div class="l" style="color:#8D9AB0"><span>Montagem da folha</span><b>inclusa</b></div>';
if(!ehFolha()) l += '<div class="l" style="color:#8D9AB0"><span>'+(montagemFolhas?'Montagem em '+montagemFolhas.length+' folhas, pela espessura do traço':'Montagem da folha')+'</span><b>inclusa</b></div>';
if(extra) l += '<div class="l"><span>Arquivo aberto na mão</span><b>+'+rs(extra)+'/m</b></div>';
l += '<div class="l"><span>Metragem'+(sobra>0.001?' · arredondada para 10 cm':'')+
'</span><b>'+fmtM(cob)+' m</b></div>';
@@ -99,10 +107,8 @@ function carrinho(){
? {kind:'sheet',width_cm:x.med?.larg||larguraFilme(),length_cm:+(x.m*100).toFixed(4),
copies:x.rep||1,rotation_degrees:0,mirrored:false,
measurement:x.med?'file':'customer'}
: {kind:'artwork',width_cm:x.cm,length_cm:+(x.cm*propDe(x)).toFixed(4),
copies:x.q,rotation_degrees:x.giro||0,mirrored:!!x.esp,
measurement:(x.src||x.semPrevia)?'file':'customer'});
let layout;
: fonteDaArte(x));
let layout, partes=null;
if(ehFolha()){
let y=0;
const placements=[];
@@ -115,6 +121,14 @@ function carrinho(){
}
});
layout={height_cm:+y.toFixed(4),placements};
}else if(montagemFolhas){
// Item 17: one order item per sheet, each with its files, layout and class.
partes=montagemFolhas.map((f,i)=>({rotulo:'Folha '+(i+1)+' · '+f.nome,
localFiles:f.artes.map(x=>x.f), fotos:f.artes.map(x=>x.fotoSrc||null),
metros:+(f.layout.height_cm/100).toFixed(4),
production:{version:3,film_width_cm:larguraFilme(),sources:f.artes.map(fonteDaArte),...f.layout},
residueAccepted:residuosDasArtes(f.artes), ...tracoDoItem(f.artes,f.layout)}));
layout=null;
}else{
if(!montagemLayout) return;
layout=montagemLayout;
@@ -125,13 +139,16 @@ function carrinho(){
fotos:(ehFolha()?folhas:artes).map(x=>x.fotoSrc||null),
ext:extDe(((ehFolha()?folhas:artes)[0]||{f:{name:''}}).f.name),
arquivos:(ehFolha()?folhas:artes).length,
production:{version:3,film_width_cm:larguraFilme(),sources,...layout},
production:layout?{version:3,film_width_cm:larguraFilme(),sources,...layout}:null,
partes,
qualityStatus:$('ciente').classList.contains('recusa')?'rejected':
$('ciente').classList.contains('on')?'warning':nota===0?'unverified':'ok',
qualityAcknowledged:false,
// The residue dots the customer accepted printing (Dropstar, 2026-10-29).
residueAccepted:ehFolha()?residuosAceitos():0,
desc:fmtM(cob)+' m · '+rs(unit)+'/m · nota '+nota};
residueAccepted:residuosAceitos(),
// The thinnest stroke and its contraction class (item 9), for the room.
...tracoDoItem(null,layout),
desc:(partes?partes.length+' folhas · ':'')+fmtM(cob)+' m · '+rs(unit)+'/m'};
pintaPedido();
previa();
}
@@ -145,6 +162,7 @@ function avisaDesfazer(texto,acao){
function fechaDesfazer(){ clearTimeout(desfazerTimer); desfazerAcao=null; $('desfazer').hidden=true; }
addEventListener('dtf-page-changed',fechaDesfazer);
$('desfazerBtn').addEventListener('click',()=>{ const acao=desfazerAcao; fechaDesfazer(); if(acao) acao(); });
$('fTratamento')?.addEventListener('change',()=>pintaPedido());
$('bEsvaziar').addEventListener('click',()=>{
const antes=pedido.slice();
pedido=[]; invalidaItemAtual(); pintaPedido();

View File

@@ -9,9 +9,6 @@
vals.hidden=!it;
add.disabled=!it || !itemPodeEnviar(it);
if(!it) return;
// One price per product (Dropstar, 2026-10-23): the grade is shown to explain
// the file, on its own line, and never changes the metre.
$('cNota').textContent = it.nota ? it.nota+'/100' : '—';
$('cMetroLbl').textContent = it.extra ? 'Metro · com '+rs(it.extra)+' de arquivo manual' : 'Metro';
$('cMetro').textContent=rs(it.unit);
$('cMetragem').textContent=fmtM(it.cob)+' m';

View File

@@ -4,6 +4,14 @@
scope and run top to bottom, exactly as the original did. */
const $=id=>document.getElementById(id);
// Segundos desde um marco, para as etapas nunca ficarem mudas (item 0.12).
const segundosDesde=inicio=>inicio?Math.max(0,Math.round((Date.now()-inicio)/1000)):0;
// What the browser measured while the customer built the cart (item 0.12):
// page load, upload, Prumo's check and the loose-art montage. It only feeds
// Números; no price or acceptance depends on it.
window.dtfTimings={pageStart:performance.now(),uploadStart:null,uploadEnd:null,
uploadBytes:0,uploadSeen:new Set(),analysisStart:null,analysisEnd:null,
montageStart:null,montageEnd:null};
const rs=v=>'R$ '+v.toFixed(2).replace('.',',');
// Ícones (Lucide, licença ISC) desenhados no próprio HTML: nada a carregar, e a
// cor vem do texto em volta. Os que ficam no HTML estático são os mesmos.
@@ -52,6 +60,8 @@ const PRECO={file:19.90, avulsa:21.90, uvfile:79.90, uv:89.90};
// Folha que alguém abre na mão (CDR, AI, PSD, TIFF): R$ a mais por metro.
// Vem do servidor (/api/session), que cobra o mesmo; zero não soma nada.
let TAXA_MANUAL=0;
// Fixed price of the designer treatment, set by the server (TREATMENT_CENTS).
let TAXA_TRATAMENTO=0;
const folhaManual=()=>ehFolha() && folhas.some(x=>!x.med);
const ehFolha=m=>!!MODOS[m||modo].folha;
const precoMetro=m=>PRECO[m||modo];
@@ -67,7 +77,7 @@ const ACEITA={
avulsa: /[.](png|webp)$/i
};
const MEDE=/[.](png|jpe?g|webp|gif|bmp|pdf)$/i;
const DPI_RECUSA=96, DPI_AVISA=300; // régua dos designers · 02/09/2026
const DPI_RECUSA=96, DPI_AVISA=200; // régua aprovada pela Dropstar · 05/11/2026
// A especificação do PDF limita a página a 14.400 unidades — 200 pol, 508 cm.
// Passar disso só é válido com UserUnit (PDF 1.6+), que a maioria dos programas
// não escreve: o arquivo sai fora do padrão e só o gerador lê direito.
@@ -85,6 +95,7 @@ const folhaTotalM=()=>folhas.reduce((t,x)=>t+(x.m||0)*(x.rep||1),0);
const PAR={file:'avulsa', avulsa:'file', uvfile:'uv', uv:'uvfile'};
let montagemCm=0; // altura da folha montada pelo motor, em cm
let montagemLayout=null; // posições aprovadas de cada cópia, em cm
let montagemFolhas=null; // artes avulsas separadas por traço (item 17)
let montagemFolgaCm=0.5; // a menor folga da montagem na largura
const ZOOMS=[1,1.5,2,3,4]; let zoomI=0; // ampliação da montagem ao vivo
let pedido=[]; // itens já fechados · o pagamento é um só
@@ -155,6 +166,10 @@ function faltaLeitura(l){
const larguraFilme=()=>MODOS[modo].larg;
// cobrança proporcional: arredonda para cima em 10 cm · 2,75 m vira 2,80 m
const cobrar=m=>Math.max(MINIMO_M, Math.ceil(m*10)/10);
// Com as artes em folhas separadas por traço (item 17), cada folha arredonda
// a 10 cm e o mínimo de 1 m vale para a soma: o cliente não escolheu separar.
const cobrarFolhas=fs=>Math.max(MINIMO_M, +fs.reduce((t,f)=>t+Math.ceil(+(f.alturaCm/100).toFixed(4)*10)/10,0).toFixed(1));
const cobrarMontagem=()=>!ehFolha() && montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(metros);
const fmtM=m=>m.toFixed(2).replace('.',',');
const cls=n=>n>=85?'ok':n>=50?'av':'er';
const dpiDe=a=>a.cm>0? (a.giro?a.py:a.px)/(a.cm/2.54) : 0;

View File

@@ -393,7 +393,7 @@ function previaAoVivo(){
if(!x.previewSrc){
const esqueleto=document.createElement('div'); esqueleto.className='skel folhaSkel';
esqueleto.style.aspectRatio=x.med ? x.med.larg+' / '+Math.min(x.med.alt,x.med.larg*4) : '1 / 2';
esqueleto.append(Object.assign(document.createElement('span'),{textContent:'Gerando a prévia da folha…'}));
esqueleto.append(Object.assign(document.createElement('span'),{textContent:'Gerando a prévia da folha… · '+segundosDesde(x.analiseInicio)+' s'}));
figura.append(esqueleto,legenda); painel.append(figura); return;
}
const pilha=document.createElement('div'); pilha.className='folhaPilha';
@@ -426,6 +426,9 @@ function previaAoVivo(){
const prontas=artes.filter(a=>a.cm>0 && a.cm<=larguraFilme() && (a.src||a.semPrevia));
const W=Math.round(300*ZOOMS[zoomI]);
$('vArea').classList.toggle('ampliado', zoomI>0);
montagemFolhas=null;
const grupos=gruposDeTraco(prontas);
if(grupos.length>1){ montaFolhasDeTraco(grupos,W); $('vArea').scrollTop=0; return; }
desenhaMontagem($('vArea'), prontas, 0, W, $('vUso'), r=>{
montagemCm = r.alturaCm; // altura real da folha montada
montagemFolgaCm = r.folgaCm ?? MARGEM_CM;
@@ -439,6 +442,43 @@ function previaAoVivo(){
},140);
}
// Item 17 (Dropstar, 30/10/2026): artes de traço fino (C1, C2) e de traço
// grosso (C3) saem em folhas separadas, cada uma com a sua contração; o
// cliente não escolhe nada. Uma arte que o navegador não mediu fica nas finas.
const NOMES_TRACO=['traço fino','chapado'];
function gruposDeTraco(lista){
const grossa=a=>(tracoDaArte(a)||{}).classe==='C3';
const grupos=[lista.filter(a=>!grossa(a)), lista.filter(grossa)];
return grupos.every(g=>g.length) ? grupos : [lista];
}
function montaFolhasDeTraco(grupos,W){
const area=$('vArea'), versao=area.montagemVersao, feitas=[];
$('vUso').innerHTML='';
const painel=document.createElement('div'); painel.className='folhasTraco';
grupos.forEach((lista,i)=>{
const figura=document.createElement('figure'); figura.className='folhaTraco';
// Sem a nota de aproveitamento de cada folha: quem separou fomos nós.
const legenda=document.createElement('figcaption'), desenho=document.createElement('div'), uso=document.createElement('div');
legenda.textContent='Folha '+(i+1)+' · '+NOMES_TRACO[i];
figura.append(legenda,desenho); painel.append(figura);
desenhaMontagem(desenho, lista, 0, W, uso, r=>{
if(area.montagemVersao!==versao) return; // a montagem mudou nesse meio-tempo
legenda.textContent='Folha '+(i+1)+' · '+NOMES_TRACO[i]+' · '+fmtM(Math.ceil(+(r.alturaCm/100).toFixed(4)*10)/10)+' m';
feitas[i]={nome:NOMES_TRACO[i], artes:lista, alturaCm:r.alturaCm, folgaCm:r.folgaCm ?? MARGEM_CM,
layout:r.placements ? {height_cm:+r.alturaCm.toFixed(4), placements:r.placements} : null};
if(feitas.filter(Boolean).length<grupos.length) return;
montagemFolhas=feitas.every(f=>f.layout) ? feitas : null;
montagemLayout=null;
montagemCm=feitas.reduce((t,f)=>t+f.alturaCm,0);
montagemFolgaCm=Math.min(...feitas.map(f=>f.folgaCm));
$('vMt').textContent=montagemFolhas ? fmtM(cobrarFolhas(montagemFolhas))+' m' : '—';
resumoArtes();
agendaAvaliacao();
});
});
area.replaceChildren(painel);
}
function motivoNota(){
if(!nota) return 'sem nota ainda · a conferência roda na sala antes de imprimir';
if(!ehFolha()){
@@ -453,11 +493,13 @@ function motivoNota(){
: 'nota '+nota+' · a resolução é o único ponto — o resto corrigimos por você';
}
function previa(){
const T=window.dtfTimings;
if(T && T.montageStart!=null && T.montageEnd==null) T.montageEnd=performance.now();
// Na folha pronta o painel não tem o que mostrar: a folha vem fechada, ninguém
// olhou dentro dela. Largura e metragem — o que de fato medimos — já aparecem
// na coluna ao lado e no carrinho.
if(ehFolha()){ $('prev').classList.remove('on'); return; }
const cob=cobrar(metros), sobra=+(cob-metros).toFixed(2);
const cob=cobrarMontagem(), sobra=+(cob-metros).toFixed(2);
$('pMt').innerHTML=fmtM(cob)+'<small> m</small>';
$('pSub').textContent='folha montada por nós com as artes que você enviou';
const linhas=[
@@ -465,7 +507,6 @@ function previa(){
['var(--verde)','✓','Espaço entre artes', montagemFolgaCm>=MARGEM_CM-1e-9
? '5 mm entre as artes e nas bordas'
: n1(montagemFolgaCm*10)+' mm · 5 mm não cabem na largura, a sobra fica dividida por igual'],
[nota>=75?'var(--verde)':'var(--laranja)', nota>=75?'✓':'!','Qualidade da folha',motivoNota()],
['var(--verde)','✓','Metragem proporcional',
'sua folha tem '+fmtM(metros)+' m e você paga '+fmtM(cob)+
' m · arredondamos só até os 10 cm mais próximos'],

View File

@@ -333,6 +333,16 @@ async function fontePdf(lib, file){
function medirFolha(file){
return new Promise(res=>{
const nome=(file.name||'').toLowerCase();
if(/\.png$/.test(nome)){
dimensoesImagem(file).then(d=>{
if(!d || !(d.w>0) || !(d.h>0)) return res({rejected:true,reason:'Não foi possível ler as dimensões do PNG. Exporte novamente.'});
const L=larguraFilme(), measure={larg:L,alt:+(d.h/d.w*L).toFixed(1),
fonte:'dimensões do arquivo',dpiFolha:Math.round(d.w/(L/2.54)),px:d.w};
if(d.h>32767 || file.size>GRANDE_BYTES) return res({...measure,grande:true,tall:d.h>32767});
carregarImagem(file).then(img=>res(img&&img.width?{...measure,fonte:'proporção da imagem'}:null));
}).catch(()=>res({rejected:true,reason:'Não foi possível ler o PNG. Exporte novamente.'}));
return;
}
if(RENDERIZA.test(nome) && file.size>GRANDE_BYTES){
dimensoesImagem(file).then(d=>{
if(!d || !(d.w>0) || !(d.h>0)) return res(null);
@@ -396,8 +406,9 @@ function medirFolha(file){
}
function textoProgresso(x){
if(x.med && x.med.grande) return 'gerando a prévia e conferindo a arte · '+faltaLeitura(x.leitura);
return x.pct<50?'lendo o arquivo…':x.pct<70?'medindo a folha…':'conferindo a arte…';
const tempo=x.analiseInicio?' · '+segundosDesde(x.analiseInicio)+' s':'';
if(x.med && x.med.grande) return 'o Prumo está gerando a prévia e conferindo a arte · '+faltaLeitura(x.leitura)+tempo;
return (x.pct<50?'lendo o arquivo…':x.pct<70?'medindo a folha…':'o Prumo está conferindo a arte…')+tempo;
}
// The file card's thumbnail (52 x 96 px, drawn at twice that for sharp screens).
// At 480 x 720 it is the picture the Kanban shows of the order (checkout.js).
@@ -453,9 +464,8 @@ function chipsDaFolha(a,aceito){
}
// Resíduo e fundo chapado barram o pedido (Dropstar, 21/10/2026): o texto diz
// quantos pontos, onde estão e o que fazer, sem "arquivo com problema". O
// resíduo o cliente pode aceitar imprimir (29/10/2026); marcado, o aviso sai
// e fica só o aceite.
function avisosDaFolha(a,nome,i,aceito){
// resíduo o cliente pode aceitar imprimir em ambos os caminhos.
function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
if(a.grande) return '';
if(a.fundoChapado) return /\.jpe?g$/i.test(nome||'')
? '<p class="avisoF"><b>JPG não tem fundo transparente.</b> O que parece branco na tela sai branco '+
@@ -465,14 +475,13 @@ function avisosDaFolha(a,nome,i,aceito){
if(!a.residuos) return '';
const n=a.residuos, varios=n>1;
const aceite='<label class="aceiteRes"><input type="checkbox" data-residuo="'+i+'"'+(aceito?' checked':'')+'>'+
'<span>Esta arte tem '+n+(varios?' pontos menores':' ponto menor')+' que 2 mm. Estou ciente e aceito '+
'imprimir assim — '+(varios?'eles podem':'ele pode')+' se perder no recorte.</span></label>';
if(aceito) return aceite;
'<span>Esses pontos fazem parte da arte. Li e concordo em imprimir assim — eles podem sair no recorte.</span></label>';
if(aceitavel && aceito) return aceite;
return '<p class="avisoF"><b>'+(varios?'Sobraram ':'Sobrou ')+n+(varios?' pontos':' ponto')+
' de recorte na sua folha.</b> São restos da remoção de fundo: não aparecem na sua tela, mas a '+
'impressora enxerga e imprime. Apague '+(varios?'os pontos':'o ponto')+' na ferramenta que você '+
'usou e envie de novo. '+(varios?'Os círculos vermelhos na prévia mostram onde estão.':'O círculo vermelho na prévia mostra onde está.')+
' Se '+(varios?'os pontos são':'o ponto é')+' da própria arte, marque abaixo.</p>'+aceite;
(aceitavel?' Se '+(varios?'os pontos são':'o ponto é')+' da própria arte, marque abaixo.</p>'+aceite:'</p>');
}
function detalhesDaFolha(a,i,aberto){
const linhas = a.grande
@@ -481,9 +490,9 @@ function detalhesDaFolha(a,i,aberto){
: [a.artes+' peça'+(a.artes===1?'':'s')+' · '+a.aproveitamento+'% da folha com arte',
'Resolução '+a.dpi+' DPI · '+(a.fonteDpi==='imagens'? 'medida imagem por imagem dentro do PDF'
: a.fonteDpi==='vetor'? 'arte vetorial, sem imagem embutida' : 'lida do arquivo'),
'Conferido numa grade de '+n1(a.grade)+' mm'];
'Conferido pelo Prumo numa grade de '+n1(a.grade)+' mm'];
return '<details class="confDet" data-det="'+i+'"'+(aberto?' open':'')+'>'+
'<summary>Ver detalhes da conferência</summary>'+
'<summary>Ver o que o Prumo conferiu</summary>'+
linhas.map(l=>'<span>'+l+'</span>').join('')+'</details>';
}
function pintaFolha(){
@@ -504,7 +513,7 @@ function pintaFolha(){
if(lido){
medida='<div class="repMed"><b>'+n1(x.med.larg)+' × '+n1(x.med.alt)+' cm</b>'+
'<span>'+escapeHTML(extDe(x.f.name))+' · '+fmt(x.f.size)+'</span></div>'+
(a? '<ul class="chips">'+chipsDaFolha(a,residuoAceito(x))+'</ul>'+avisosDaFolha(a,x.f.name,i,residuoAceito(x))+
(a? '<ul class="chips">'+chipsDaFolha(a,residuoAceito(x))+'</ul>'+avisosDaFolha(a,x.f.name,i,residuoAceito(x),true)+
detalhesDaFolha(a,i,x.detAberto) : '')+
// Over 150 MB the browser cannot check a PDF: said before payment, as
// for a file opened by hand (Dropstar, 2026-10-23).
@@ -525,7 +534,7 @@ function pintaFolha(){
: ' Remonte a folha em '+n1(L)+' cm e suba de novo.')+'</p>':'');
}else if(x.measurementError){
medida='<span class="repPeso">'+escapeHTML(extDe(x.f.name))+' · '+fmt(x.f.size)+'</span>'+
'<p class="avisoF"><b>Este PDF não pode ser orçado.</b> '+escapeHTML(x.measurementError)+'</p>';
'<p class="avisoF"><b>Este arquivo não pode ser orçado.</b> '+escapeHTML(x.measurementError)+'</p>';
}else{
// Só a abertura manual muda o metro (TAXA_MANUAL); a nota não mexe no preço.
const dif=(x.m>0)? TAXA_MANUAL*cobrar(x.m*(x.rep||1)) : 0;
@@ -546,8 +555,8 @@ function pintaFolha(){
'<span class="progT">'+textoProgresso(x)+'</span>'
: x.semAnalise
? '<div class="progF"><b>Não conseguimos conferir esta folha.</b> '+escapeHTML(x.semAnalise)+
'. Seguimos sem a nota, e a conferência é feita na mão. Se quiser a nota, exporte a mesma '+
'folha em <b>PNG</b>, que a conferência é bem mais leve.</div>'
'. A conferência será feita na sala. Para conferir a resolução aqui, exporte a mesma '+
'folha em <b>PNG</b>.</div>'
: '';
// A small thumbnail made once: the list is rebuilt on every change, and the
// full preview of a file up to 150 MB would be re-parsed each time.
@@ -664,6 +673,10 @@ function pintaArtes(){
n1(sug.cm)+' cm.<button data-usar="'+i+'" data-cm="'+sug.alvo+'">Usar '+n1(sug.alvo)+' cm</button></div>'
: '';
}
// Item 4: the art's dots under 2 mm, with the same warning and acceptance as a sheet.
const an=analiseDaArte(a);
if(an && an.residuos) aviso+=avisosDaFolha({residuos:an.residuos},a.f.name,i,!!a.residuoAceito,true).replace('data-residuo=','data-residuoa=')
.replace('na sua folha','nesta arte');
if(a.semPrevia && !a.decodeError)
aviso+='<p class="repTxt"><b>Sem prévia para '+escapeHTML(extDe(a.f.name))+' deste tamanho.</b> '+
'A arte entra na folha pela medida, e a equipe confere antes de imprimir. Em PNG, a prévia aparece.</p>';
@@ -700,6 +713,8 @@ function pintaArtes(){
el.dispatchEvent(new Event('change'));
}));
$('lista').querySelectorAll('[data-rm]').forEach(b=>b.addEventListener('click',()=>{artes.splice(+b.dataset.rm,1);pintaArtes();}));
$('lista').querySelectorAll('[data-residuoa]').forEach(el=>el.addEventListener('change',()=>{
artes[+el.dataset.residuoa].residuoAceito=el.checked; pintaArtes();}));
$('lista').querySelectorAll('[data-cm]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.cm].cm=+i.value||0;pintaArtes();}));
$('lista').querySelectorAll('[data-q]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.q].q=Math.max(1,Math.min(200,Math.floor(+i.value||1)));pintaArtes();}));
$('lista').querySelectorAll('[data-cm], [data-q]').forEach(i=>i.addEventListener('input',()=>{
@@ -728,16 +743,12 @@ function resumoArtes(){
const r=$('rA'), prontas=artes.filter(a=>a.cm>0 && a.cm<=larguraFilme() && (a.src||a.semPrevia));
if(!prontas.length){ r.style.display='none'; return; }
const m=montagemCm/100; // a mesma folha que aparece ao lado
const notas=prontas.map(a=>Math.max(6,Math.min(100,Math.round(dpiDe(a)/300*100))));
const media=Math.round(notas.reduce((s,n)=>s+n,0)/notas.length), pior=Math.min(...notas);
const cob=montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(m);
const falta=artes.length-prontas.length;
r.style.display='block'; r.className='resumoA on';
r.innerHTML='<div class="r"><span>artes com tamanho</span><b>'+prontas.length+' de '+artes.length+'</b></div>'+
'<div class="r"><span>qualidade média</span><b style="color:'+
(media>=85?'var(--verde)':media>=50?'var(--laranja)':'var(--vermelho)')+'">'+media+'%</b></div>'+
(pior<media?'<div class="r"><span>a pior arte</span><b>'+pior+'%</b></div>':'')+
(m>0?'<div class="r"><span>folha montada</span><b>'+fmtM(m)+' m</b></div>'+
(cobrar(m)>m+0.001?'<div class="r"><span>cobrança</span><b>'+fmtM(cobrar(m))+
' m'+(cobrar(m)===MINIMO_M?' · mínimo':'')+'</b></div>':''):'')+
(m>0?'<div class="r"><span>'+(montagemFolhas?montagemFolhas.length+' folhas montadas':'folha montada')+'</span><b>'+fmtM(m)+' m</b></div>'+
(cob>m+0.001?'<div class="r"><span>cobrança</span><b>'+fmtM(cob)+
' m'+(cob===MINIMO_M?' · mínimo':'')+'</b></div>':''):'')+
(falta?'<div class="r" style="color:var(--laranja)"><span>faltam informar</span><b>'+falta+'</b></div>':'');
}

View File

@@ -7,13 +7,79 @@
// transparente. Só vale para o que o navegador conferiu. O resíduo que o
// cliente aceita imprimir (Dropstar, 29/10/2026: às vezes os pontos são da
// arte) não barra; o fundo chapado barra sempre.
const residuoAceito=x=>!!(x.residuoAceito && x.an && x.an.residuos);
const residuoAceito=x=>!!x.residuoAceito;
const folhaBarrada=x=>!!(x.an && !x.an.grande && (x.an.fundoChapado || (x.an.residuos && !residuoAceito(x))));
// Quantos pontos o cliente aceitou imprimir, somadas as folhas: vai no item.
const residuosAceitos=()=>folhas.filter(residuoAceito).reduce((t,x)=>t+x.an.residuos,0);
// the sheet of loose art inherits what each artwork accepted
const residuosDasArtes=lista=>lista.filter(a=>a.residuoAceito).reduce((t,a)=>t+((analiseDaArte(a)||{}).residuos||0),0);
const residuosAceitos=()=>ehFolha()
? folhas.filter(residuoAceito).reduce((t,x)=>t+x.an.residuos,0)
: residuosDasArtes(artes);
// Item 16 (Dropstar, 03/11/2026): um detalhe fino pequeno que leva a arte
// inteira para C1, numa arte quase toda chapada. Os três ao mesmo tempo: o
// menor traço até 4 px, pelo menos 60% da tinta em áreas de 20 px ou mais e
// no máximo 10% da tinta em traços de até 4 px.
const mista=t=>!!(t && t.px<=4 && t.largos>=0.6 && t.finos<=0.10);
const tracoDoArquivo=x=>ehFolha()?x.an&&x.an.traco:tracoDaArte(x);
const TEXTO_MISTA={
arte:'Esta arte tem traços finos e áreas chapadas no mesmo arquivo. O branco por baixo precisa de ajuste diferente pra cada um. '+
'Vamos proteger os traços finos; as áreas chapadas podem mostrar uma borda branca muito fina. Quer evitar? Suba esta arte em dois '+
'arquivos, um com os traços finos e outro com as áreas chapadas; a gente monta cada um na folha certa. Pode dar alguns centímetros a mais de filme.',
folha:'Esta folha tem traços finos e áreas chapadas no mesmo arquivo. O branco por baixo precisa de ajuste diferente pra cada um. '+
'Vamos proteger os traços finos; as áreas chapadas podem mostrar uma borda branca muito fina. Quer evitar? Mande em duas folhas, '+
'uma com os traços finos e outra com as áreas chapadas. Pode dar alguns centímetros a mais de filme.'};
// O aviso não barra e aparece uma vez por arquivo, na folha pronta e na arte
// avulsa: imprimir assim mesmo (C1), ou trocar o arquivo por dois.
function perguntaMista(){
const dlg=$('mistaDlg');
if(!dlg || dlg.open) return;
const lista=ehFolha()?folhas:artes;
const x=lista.find(y=>!y.mistaVista && mista(tracoDoArquivo(y)));
if(!x) return;
$('mistaTit').textContent=x.f.name;
$('mistaTxt').textContent=ehFolha()?TEXTO_MISTA.folha:TEXTO_MISTA.arte;
$('mistaSep').onclick=()=>{ dlg.close(); const i=lista.indexOf(x);
if(i>=0){ lista.splice(i,1); ehFolha()?pintaFolha():pintaArtes(); } $('inp').click(); };
$('mistaSegue').onclick=()=>{ x.mistaVista=true; dlg.close(); agendaAvaliacao(); };
dlg.showModal();
}
// O traço mais fino do item (item 9, Dropstar 30/10/2026): o menor entre as
// folhas que o navegador mediu. Não aparece para o cliente; vai para a sala,
// que confere a classe de contração ao aprovar o arquivo final.
// Onde o traço mais fino cai no filme montado (0 no topo, 1 no fim): a prova
// de 15 cm é recortada em volta dele, não no começo da folha (item 0.1).
function fracaoNoFilme(layout,sourceIndex,fraction){
if(!layout || !(layout.height_cm>0)) return fraction||0;
const placement=(layout.placements||[]).find(p=>p.source_index===sourceIndex);
if(!placement) return fraction||0;
const y=placement.rotation_degrees%180===90
? placement.y_cm+placement.length_cm/2
: placement.y_cm+(fraction||0)*placement.length_cm;
return Math.max(0,Math.min(1,y/layout.height_cm));
}
function tracoDoItem(lista,layout){
const arquivos=lista||(ehFolha()?folhas:artes);
const medidas=arquivos.map((x,index)=>({index,traco:lista?tracoDaArte(x):tracoDoArquivo(x)})).filter(x=>x.traco);
if(!medidas.length) return {strokePx:null, strokeClass:null, strokeChoice:null};
const fino=medidas.reduce((a,b)=>b.traco.px<a.traco.px?b:a);
// Avisado do item 16, o cliente quis imprimir assim: fica a medida, C1.
const avisado=arquivos.some(x=>x.mistaVista && mista(lista?tracoDaArte(x):tracoDoArquivo(x)));
return {strokePx:fino.traco.px, strokeClass:fino.traco.classe, strokeChoice:avisado?'measured':null,
proofSourceIndex:fino.index,
proofYFraction:fracaoNoFilme(layout||montagemLayout,fino.index,fino.traco.proofYFraction||0)};
}
// Fecha a medida da conferência quando não há mais arquivo sendo lido (0.12).
function marcaTempos(){
const T=window.dtfTimings;
if(!T || T.analysisStart==null || T.analysisEnd!=null) return;
if(!(folhas.length+artes.length)) return;
if(folhas.some(x=>x.pct!=null) || artes.some(a=>a.lendoArte)) return;
T.analysisEnd=performance.now();
}
// Avalia sozinho conforme o cliente sobe e preenche. Devolve o que ainda falta,
// para a fila dizer em texto em vez de travar num botão.
function avaliar(){
marcaTempos();
if(ehFolha()){
if(!folhas.length) return {pronto:false, falta:'Arraste sua folha montada para começar.'};
const pdfInvalido=folhas.find(x=>x.measurementError);
@@ -27,13 +93,14 @@ function avaliar(){
// Resíduo e fundo chapado barram antes do pagamento, com um ponto só
// (Dropstar, 21/10/2026): então o pedido espera a conferência terminar.
const lendo=folhas.find(x=>x.pct!=null);
if(lendo) return {pronto:false, falta:'Conferindo '+lendo.f.name+'…'};
if(lendo) return {pronto:false, falta:'Conferindo '+lendo.f.name+'… · '+segundosDesde(lendo.analiseInicio)+' s'};
const barrada=folhas.find(folhaBarrada);
if(barrada) return {pronto:false, falta:barrada.an.fundoChapado
? barrada.f.name+' está sem fundo transparente. Exporte a folha com fundo transparente, em PNG ou PDF, e envie de novo.'
: barrada.f.name+' tem '+barrada.an.residuos+' ponto'+(barrada.an.residuos>1?'s':'')+
' de recorte. Apague e envie de novo, ou marque que aceita imprimir assim.'};
metros=folhaTotalM();
setTimeout(perguntaMista);
reencaixado=false;
const ans=folhas.map(x=>x.an).filter(Boolean);
if(ans.length!==folhas.length){
@@ -42,7 +109,7 @@ function avaliar(){
const ausentes=folhas.filter(f=>!f.an);
const exts=[...new Set(ausentes.map(f=>extDe(f.f.name)))].join(', ');
mostraNota([
['av','Sem nota · '+exts+' sem análise completa',
['av','Conferência manual · '+exts+' sem análise completa',
ausentes.length+' de '+folhas.length+' folha(s) precisam de conferência manual'],
['fix','Alguém abre seu arquivo','a conferência é feita na mão, na sala']
], 0, folhas.length>1? folhas.length+' folhas' : folhas[0].f.name,
@@ -78,7 +145,8 @@ function avaliar(){
return {pronto:true};
}
if(!artes.length) return {pronto:false, falta:'Arraste suas artes para começar.'};
if(artes.some(a=>a.lendo!=null)) return {pronto:false, falta:'Gerando a prévia das artes grandes…'};
const grande=artes.find(a=>a.lendo!=null);
if(grande) return {pronto:false, falta:'Gerando a prévia das artes grandes… · '+segundosDesde(grande.analiseInicio)+' s'};
if(artes.some(a=>a.decodeError || !(a.src||a.semPrevia) || !(a.px>0) || !(a.py>0)))
return {pronto:false, falta:'Não conseguimos ler uma das imagens. Exporte-a novamente em PNG antes de continuar.'};
if(artes.some(a=>!Number.isFinite(a.cm) || a.cm>larguraFilme()))
@@ -86,15 +154,24 @@ function avaliar(){
n1(larguraFilme())+' cm. Reduza a medida solicitada antes de continuar.'};
const sem=artes.filter(a=>!a.cm).length;
if(sem) return {pronto:false, falta:'Informe a largura de '+sem+' arte'+(sem>1?'s':'')+
' para ver a nota e o preço.'};
' para ver a conferência e o preço.'};
// Item 4: a dot under 2 mm in a loose artwork holds the order like on a
// sheet, until the customer erases it or accepts printing that artwork so.
const lendoArte=artes.find(a=>a.lendoArte);
if(lendoArte) return {pronto:false, falta:'Conferindo as artes… · '+segundosDesde(lendoArte.analiseInicio)+' s'};
const comPontos=artes.find(a=>{const an=analiseDaArte(a);return an&&an.residuos&&!a.residuoAceito;});
if(comPontos){const n=analiseDaArte(comPontos).residuos;
return {pronto:false, falta:comPontos.f.name+' tem '+n+' ponto'+(n>1?'s':'')+
' de recorte. Apague e envie de novo, ou marque que aceita imprimir assim.'};}
setTimeout(perguntaMista);
// metragem = altura da folha depois de montada, com os 5 mm entre peças
metros=+(montagemCm/100).toFixed(4);
if(!(metros>0)) return {pronto:false, falta:'Montando a folha…'};
const notas=artes.map(a=>Math.max(6,Math.min(100,Math.round(dpiDe(a)/300*100))));
const notas=artes.map(a=>Math.max(6,Math.min(100,Math.round(dpiDe(a)/DPI_AVISA*100))));
const media=Math.round(notas.reduce((s,n)=>s+n,0)/notas.length), pior=Math.min(...notas);
mostraNota([
['ok','Montagem por nossa conta','5 mm garantidos'],
[cls(pior),'Pior arte em '+pior+'%',pior>=85?'todas em boa resolução':'há arte abaixo da resolução ideal']
[cls(pior),'Resolução das artes',pior>=85?'todas em boa resolução':'há arte abaixo da resolução ideal']
],media,artes.length+' arte'+(artes.length>1?'s':''),
'folha montada por nós · '+fmtM(metros)+' m');
return {pronto:true};
@@ -112,7 +189,7 @@ function agendaAvaliacao(){
if(!el) return;
if(r.pronto){
el.className='aoVivo pronto';
el.innerHTML='<span class="pt2"></span><span><b>Nota e preço calculados.</b> '+
el.innerHTML='<span class="pt2"></span><span><b>Conferência e preço calculados.</b> '+
'Confira abaixo e feche o pedido.</span>';
}else{
el.className='aoVivo';
@@ -156,7 +233,7 @@ function ressalvaResolucao(){
quantas:r.quantasBaixas, parte:Math.round(r.fracBaixa*100),
quantasAviso:r.quantasAviso, parteAviso:Math.round(r.fracAviso*100)} : {};
if(x.an.dpi<DPI_RECUSA) recusadas.push(Object.assign({nome, dpi:x.an.dpi, cm}, extra));
else if(x.an.dpi<DPI_AVISA || (r&&r.quantasAviso))
else if(x.an.dpi<DPI_AVISA)
baixas.push(Object.assign({nome, dpi:x.an.dpi, cm}, extra));
});
geral = folhas.some(x=>x.an) ? Math.max(...folhas.filter(x=>x.an).map(x=>x.an.dpi)) : 300;

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