Compare commits

...

64 Commits

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

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

# Conflicts:
#	.gitea/workflows/deploy.yml
2026-11-09 15:40:55 -03:00
Cauê Faleiros
3d8be36d65 Merge front 8.3: discount coupons
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 6m28s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m3s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 15:40:29 -03:00
Cauê Faleiros
2c80de0c0a feat: Montar creates the invoiced order card (front 7a.2b)
The montador sends each stamp to storage, splits the list into items of
at most 20 sources and 4000 copies, packs each one with the Site's engine
and creates the order in Arte recebida: typed customer, pickup, the Site's
table price, payment 'faturado', origin dropflow for Expedição and
atendimento otherwise. Until Dropstar decides, these orders do not go to
Tiny and the customer gets no paid e-mail. Vendedor and Expedição may now
upload through the operator upload routes (can_any).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 15:27:04 -03:00
Cauê Faleiros
60105e7cbe feat: Site videos up to 500 MB
All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 6m23s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m6s
Dropstar uploads the six videos themselves; 100 MB was our own limit and
could stop a longer video in the videos area. ClamAV scans up to 2000 MiB,
so 500 MB is still scanned.

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

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 15:24:44 -03:00
Cauê Faleiros
8993eb25db Merge branch 'main' into front-7a
# Conflicts:
#	app/schema.sql
2026-11-09 15:10:55 -03:00
Cauê Faleiros
07ee38d677 Merge front 8.2 and 8.4: price bands, videos in the Site tab
All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 6m17s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m6s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 15:00:58 -03:00
Cauê Faleiros
2f85a38562 feat: the videos panel in the Site tab, captions optional (front 8.4)
Dropstar uploads the six videos themselves, so the panel moves from
Integrações to the Site tab, next to products and prices. A video can be
published without a VTT: the Site plays it without a captions track.

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

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

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

# Conflicts:
#	.gitea/workflows/deploy.yml
#	app/app.py
#	app/schema.sql
#	web/kanban.html
#	web/kanban.js
2026-11-09 14:14:25 -03:00
Cauê Faleiros
c5e7a80b64 Merge front 8.1: products and prices in the Site tab
All checks were successful
Build and deploy / Publish images (push) Successful in 1m6s
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 6m6s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

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

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 13:50:45 -03:00
Cauê Faleiros
e9db9dec06 feat: Expedição profile, stamp sizes and the Montar folha screen (front 7a.1)
The new Expedição profile and the seller may assemble sheets (capability
assemble). Gestão edits the size table (letter and width). The Montar tab
reads Estampas/<code>-<size>.png or <code>.png from the orders folder,
checks the resolution with the Site's 96/200 DPI ruler, merges repeated
lines and estimates the metres. Montar itself is slice 2.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:59:37 -03:00
119 changed files with 13527 additions and 2507 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

@@ -22,6 +22,7 @@ jobs:
tests.test_staging_readiness \
deploy.test_production_preflight \
tests.test_pricing \
tests.test_coupons \
tests.test_secrets -v
sh -n infra/lock_dependencies.sh
@@ -73,7 +74,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 site_admin_test coupons_test stamps_test; do
echo "--- $suite"
$COMPOSE exec -T \
-e SITE_BASE_URL=http://site \
@@ -86,7 +87,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,8 +8,9 @@ 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.auth import can, can_any, operator
from ..core.models import ArtworkSubmission, UploadStart
from ..runtime import file_rows, operator_identity
from .uploads import begin_upload, cancel_upload, complete_upload, part_url, upload_status
@@ -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))
@@ -31,15 +38,15 @@ def final_status(uid: UUID, user=Depends(operator)):
# The parts of an upload its operator started: a final (produce) or the
# photo of a signed pickup receipt (deliver, which includes produce).
@router.post('/api/operator/uploads/{uid}/parts/{number}')
def final_part(uid: UUID, number: int, user=Depends(can('deliver'))):
def final_part(uid: UUID, number: int, user=Depends(can_any('deliver', 'assemble'))):
return part_url(uid,number,session_id=operator_identity(user))
@router.post('/api/operator/uploads/{uid}/complete')
def final_complete(uid: UUID, user=Depends(can('deliver'))):
def final_complete(uid: UUID, user=Depends(can_any('deliver', 'assemble'))):
return complete_upload(uid,session_id=operator_identity(user))
@router.delete('/api/operator/uploads/{uid}')
def final_cancel(uid: UUID, user=Depends(can('deliver'))):
def final_cancel(uid: UUID, user=Depends(can_any('deliver', 'assemble'))):
return cancel_upload(uid,session_id=operator_identity(user))
@router.get('/api/operator/orders/{oid}/files')
@@ -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

@@ -6,7 +6,7 @@ import httpx
from fastapi import APIRouter, HTTPException, Request, Response
from ..core import db
from .. import mail
from .. import catalog, 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
@@ -38,11 +38,23 @@ def session(request: Request, response: Response):
rate_limit('guest-sessions', client_ip(request), GUEST_SESSION_LIMIT, 900)
with db.connect() as c:
session_id = new_session(c, response)
with db.connect() as c:
products = catalog.current(c)
treatment = products['tratamento']
return {'environment': ENVIRONMENT, 'cart_scope': str(session_id), 'part_bytes': PART_BYTES,
'max_upload_bytes': upload_limit_bytes(), 'payment_provider': payment.name,
'password_recovery': mail.configured(),
# Per metre on a finished sheet someone opens by hand (app/core/pricing.py).
'manual_extra_cents': manual_extra_cents(),
# Zero keeps the designer's treatment hidden, as an off product does.
'treatment_cents': treatment['unit_cents'] if treatment['enabled'] else 0,
# What the Site sells now: a switched-off product is hidden there.
# Bands travel with the price; the Site reads them as numbers.
'products': {mode: {**products[mode],
'bands': [{'from_metres': float(band['from_metres']),
'unit_cents': band['unit_cents']}
for band in products[mode]['bands']]}
for mode in catalog.MODES},
# Public by design: 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,19 +1,20 @@
"""Quotes: the customer's cart, approved at once when it can be (app/quote_review.py)."""
import hashlib
import json
from datetime import datetime, timezone
from decimal import Decimal
from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException
from psycopg.types.json import Jsonb
from .. import payments
from .. import catalog, coupons, payments
from ..core import db
from ..core.auth import owner
from ..core.models import QuoteRequest
from ..core.pricing import price
from ..core.pricing import apply_bands, bill_splits, 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
@@ -25,18 +26,50 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
if abs(item.metres*100-item.production.height_cm) > Decimal('0.02'):
raise HTTPException(422, 'A metragem não confere com a montagem enviada. Monte o pedido de novo.')
require_delivery_available(body.freight.service)
# The coupon code is stored normalized, so a quote waiting for review keeps
# the code the operator will see (front 8.3).
code = (body.coupon or '').strip().upper() or None
draft = body.model_dump(mode='json', exclude={'request_key'})
draft['coupon'] = code
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
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.
try:
priced = [price(item.mode, str(item.metres), item.grade) for item in body.items]
freight.quote(body.freight.service, body.freight.postal_code,
sum(Decimal(i['billed_metres']) for i in priced), sum(i['total_cents'] for i in priced))
except ValueError as exc:
raise HTTPException(422, str(exc))
with db.connect() as c:
if reason is not None or code:
# Waits for review: check the delivery now, priced at approval. A
# coupon is checked on the same priced items (front 8.3).
try:
priced = []
for item in body.items:
catalog.require_enabled(c, item.mode)
priced.append({**price(item.mode, str(item.metres), item.grade,
minimum=Decimal('0') if item.split else Decimal('1'),
unit_cents=catalog.unit_cents(c, item.mode)),
**({'split': item.split.model_dump()} if item.split else {})})
bill_splits(priced)
# Progressive bands (front 8.2), by the order's total per mode.
totals = {}
for item in priced:
totals[item['mode']] = totals.get(item['mode'], Decimal('0')) + Decimal(item['billed_metres'])
banded = {}
for mode, total in totals.items():
price_for_total = catalog.unit_cents_for(c, mode, total)
if price_for_total != catalog.unit_cents(c, mode):
banded[mode] = price_for_total
apply_bands(priced, banded)
if reason is not None:
freight.quote(body.freight.service, body.freight.postal_code,
sum(Decimal(i['billed_metres']) for i in priced),
sum(i['total_cents'] for i in priced))
except ValueError as exc:
raise HTTPException(422, str(exc))
if code:
coupons.check(c, code, body.customer.cnpj, priced)
rows = {}
for item in body.items:
for uid in item.uploads:
@@ -51,7 +84,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'}

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

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

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

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

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

@@ -0,0 +1,70 @@
"""The montador's stamp sizes and its invoiced orders (Fase 2, front 7)."""
import hashlib
import json
from uuid import uuid4
from fastapi import APIRouter, Depends, HTTPException, Request
from psycopg.types.json import Jsonb
from .. import payments, quote_review
from ..core import db
from ..core.auth import audit, can
from ..core.models import Freight, MontadorOrder, QuoteRequest, StampSizeTable, UploadStart
from ..runtime import operator_identity
from .uploads import begin_upload
router = APIRouter()
@router.get('/api/operator/stamp-sizes')
def stamp_sizes(user=Depends(can('assemble'))):
with db.connect() as c:
rows = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall()
return {'sizes': rows}
@router.post('/api/operator/stamp-sizes')
def save_stamp_sizes(body: StampSizeTable, user=Depends(can('manage'))):
with db.connect() as c:
c.execute('DELETE FROM dtf_local.stamp_sizes')
c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm,updated_by) VALUES(%s,%s,%s)',
[(row.letter, row.width_cm, user) for row in body.sizes])
audit('stamp_sizes_changed', operator=user, sizes=len(body.sizes))
return {'ok': True}
@router.post('/api/operator/montador/uploads')
def montador_upload(body: UploadStart, user=Depends(can('assemble'))):
if not body.name.lower().endswith('.png'):
raise HTTPException(422, 'A estampa precisa ser um PNG.')
return begin_upload(body, session_id=operator_identity(user))
@router.post('/api/operator/montador/orders')
def montador_order(body: MontadorOrder, request: Request, user=Depends(can('assemble'))):
"""The order a montador sheet becomes, already invoiced (front 7a.2b):
typed customer, pickup, the Site's table price, and held out of Tiny until
Dropstar decides how it is invoiced there."""
origin = 'dropflow' if request.state.operator['role'] == 'expedicao' else 'atendimento'
draft = QuoteRequest(request_key=body.request_key, customer=body.customer, items=body.items,
freight=Freight(service='pickup')).model_dump(mode='json', exclude={'request_key'})
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
owner = operator_identity(user)
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft)
VALUES(%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING''',
(uuid4(), owner, body.request_key, digest, Jsonb(draft)))
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE owner=%s AND request_key=%s FOR UPDATE',
(owner, body.request_key)).fetchone()
if quote['request_hash'] != digest:
raise HTTPException(409, 'A montagem mudou durante o envio. Tente de novo.')
if not quote['approved']:
quote_review.approve(c, quote, body.items, user)
quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (quote['id'],)).fetchone()
receipt = {'provider': payments.MANUAL_PROVIDER, 'method': payments.INVOICED_METHOD, 'note': '',
'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user}
order, created = payments.create_order(c, quote, receipt, origin)
if not created:
raise HTTPException(409, f"Esta montagem já virou o pedido #{order['number']}.")
audit('montador_order_created', order=str(order['id']), origin=origin, operator=user)
return order

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

@@ -26,7 +26,7 @@ class UserIn(StrictModel):
# The profiles an administrator may give; superadmin only comes from the console.
name: str = Field(min_length=1, max_length=80)
email: str = Field(min_length=3, max_length=254)
role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro']
role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao']
password: str | None = Field(default=None, min_length=8, max_length=128)
active: bool = True
# No longer used: an operator's machine is the one chosen after signing in
@@ -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_admin, site_videos, stamps, 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, site_admin, reviews, machine_log, stamps):
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

96
app/catalog.py Normal file
View File

@@ -0,0 +1,96 @@
"""What the Site sells and at what price, edited in the Kanban's Site tab.
Dropstar, 2026-11-05 (Fase 2, front 8): the products and their prices leave the
code and live in the database, with a start date and a history. `PRICES` in
app/core/pricing.py stays as the seed and the fallback for the four modes;
`treatment_cents()` stays as the fallback for `tratamento`. A price row is never
changed or deleted once its start date has passed (the table is the history),
and an approved quote keeps the price it was approved with.
`tratamento` is the designer's treatment (front 5), a fixed amount per order:
it counts as offered only when it is switched on and priced above zero.
A price row may carry bands by the order's total metres of that product (front
8.2): below the first band the base price, then the highest band reached wins
and the whole quantity is charged at that one price. The bands travel with the
row, so they start and become history with it.
"""
from decimal import Decimal
from .core import pricing
# The four modes sold by the metre, and the treatment sold per order.
MODES = ('file', 'avulsa', 'uvfile', 'uv')
PRODUCTS = (*MODES, 'tratamento')
TITLES = {
'file': 'Têxtil folha pronta',
'avulsa': 'Têxtil artes avulsas',
'uvfile': 'UV folha pronta',
'uv': 'UV artes avulsas',
'tratamento': 'Tratamento pelo designer',
}
UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro',
'tratamento': 'pedido'}
def fallback_cents(product: str) -> int:
"""The price in the code, used until a row in the database takes over."""
return pricing.treatment_cents() if product == 'tratamento' else pricing.PRICES[product]
def band_price(base_cents: int, bands: list, metres: Decimal) -> int:
"""The per-metre price for this quantity: the base, or the highest band
reached. The whole quantity is charged at one price, not in steps."""
metres = Decimal(str(metres))
price = base_cents
best = None
for band in bands or []:
start = Decimal(str(band['from_metres']))
if metres >= start and (best is None or start >= best):
best = start
price = band['unit_cents']
return price
def current(c) -> dict:
"""{'file': {'enabled': bool, 'unit_cents': int, 'bands': [...]}, ...}."""
enabled = {row['id']: row['enabled'] for row in
c.execute('SELECT id, enabled FROM dtf_local.products').fetchall()}
prices = {row['product']: row for row in c.execute('''
SELECT DISTINCT ON (product) product, unit_cents, bands
FROM dtf_local.product_prices
WHERE starts_at <= now()
ORDER BY product, starts_at DESC, id DESC''').fetchall()}
return {product: {'enabled': bool(enabled.get(product, True)),
'unit_cents': prices[product]['unit_cents'] if product in prices else fallback_cents(product),
'bands': prices[product]['bands'] if product in prices else []}
for product in PRODUCTS}
def unit_cents(c, product: str) -> int:
"""The current base price of one product, or the fallback."""
row = c.execute('''SELECT unit_cents FROM dtf_local.product_prices
WHERE product=%s AND starts_at <= now()
ORDER BY starts_at DESC, id DESC LIMIT 1''', (product,)).fetchone()
return row['unit_cents'] if row else fallback_cents(product)
def unit_cents_for(c, product: str, metres: Decimal) -> int:
"""The current price of one product for this quantity, bands included."""
row = c.execute('''SELECT unit_cents, bands FROM dtf_local.product_prices
WHERE product=%s AND starts_at <= now()
ORDER BY starts_at DESC, id DESC LIMIT 1''', (product,)).fetchone()
if not row:
return fallback_cents(product)
return band_price(row['unit_cents'], row['bands'], metres)
def require_enabled(c, product: str) -> None:
"""Refuse a product someone switched off in the Kanban's Site tab."""
# Imported here so the pure helpers above load without the web framework
# (tests/test_pricing.py runs on the host, where FastAPI is not installed).
from fastapi import HTTPException
row = c.execute('SELECT enabled FROM dtf_local.products WHERE id=%s', (product,)).fetchone()
if row and not row['enabled']:
raise HTTPException(422, 'Este produto não está à venda agora.')

View File

@@ -114,18 +114,21 @@ 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
# backup, the Tiny log): the others see there only what is on and off.
# The designer approves and refuses artwork and asks for corrections, on every
# order whatever its machine. Which cards each profile moves is MOVES.
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro')
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao')
CAPABILITIES = {
'view': set(ROLES),
'produce': {'superadmin', 'admin', 'gestao', 'designer', '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,19 @@ 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'},
# Montar folha (Fase 2, front 7): the new Expedição profile and the seller,
# who gets this one action although otherwise view-only (D-30).
'assemble': {'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'},
}
# Who moves which card (Dropstar's flow, 2026-10-23, and their rules of
@@ -203,6 +215,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.
@@ -224,4 +241,15 @@ def can(capability):
return check
def can_any(*capabilities):
"""A dependency that lets through a profile with any of these capabilities,
and returns the operator's e-mail, as the routes record it."""
def check(request: Request):
account = signed_in(request)
if not any(account['role'] in CAPABILITIES[capability] for capability in capabilities):
raise HTTPException(403, 'Seu perfil não permite esta ação.')
return account['email']
return check
operator = can('view')

View File

@@ -1,4 +1,5 @@
import re
from datetime import date, datetime
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,17 @@ 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
# A coupon code typed at checkout (front 8.3); the server prices it.
coupon: str | None = Field(default=None, max_length=30)
# What the browser measured while the customer built the cart (item 0.12).
timings: ClientTimings | None = None
@model_validator(mode='after')
def splits_complete(self):
check_splits(self.items)
return self
@model_validator(mode='after')
def destination_matches_freight(self):
@@ -225,9 +288,27 @@ class QuoteRequest(StrictModel):
raise ValueError('The delivery address CEP must be the CEP freight was quoted for')
return self
class MontadorOrder(StrictModel):
"""What the montador sends (front 7a.2b): the typed customer, pickup only
and loose artwork only; the server prices and approves it as a quote."""
request_key: UUID
customer: Customer
items: list[Item] = Field(min_length=1, max_length=30)
@model_validator(mode='after')
def loose_art_only(self):
if any(item.mode != 'avulsa' for item in self.items):
raise ValueError('O montador só monta artes avulsas.')
return self
class Review(StrictModel):
items: list[Item] = Field(min_length=1, max_length=30)
@model_validator(mode='after')
def splits_complete(self):
check_splits(self.items)
return self
class Pay(StrictModel):
quote_id: UUID
@@ -264,6 +345,79 @@ 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 SiteProductToggle(StrictModel):
"""Ligar ou desligar um produto na aba Site (Fase 2, front 8)."""
enabled: bool
class PriceBand(StrictModel):
"""Uma faixa por metragem: a partir de X m, o metro passa a custar Y."""
from_metres: Decimal
unit_cents: int = Field(strict=True)
class SitePriceNew(StrictModel):
"""Um novo preço e a data em que começa; sem data, começa agora."""
unit_cents: int = Field(ge=0, le=10000000, strict=True)
starts_at: datetime | None = None
# As faixas viajam com o preço (front 8.2); vazio é o preço único.
bands: list[PriceBand] = Field(default_factory=list)
class CouponNew(StrictModel):
"""Um cupom novo, criado na aba Site (front 8.3)."""
code: str = Field(min_length=1, max_length=30)
kind: Literal['percent', 'per_metre']
value: int = Field(gt=0, le=10000000, strict=True)
valid_from: datetime | None = None
valid_until: datetime | None = None
min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1)
max_uses: int | None = Field(default=None, gt=0, strict=True)
max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True)
product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None
note: str = Field(default='', max_length=1000)
class CouponUpdate(StrictModel):
"""Os campos de um cupom que podem mudar; o código fica como foi criado."""
kind: Literal['percent', 'per_metre'] | None = None
value: int | None = Field(default=None, gt=0, le=10000000, strict=True)
valid_from: datetime | None = None
valid_until: datetime | None = None
min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1)
max_uses: int | None = Field(default=None, gt=0, strict=True)
max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True)
product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None
note: str | None = Field(default=None, max_length=1000)
paused: bool | None = None
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)
@@ -352,3 +506,19 @@ class ArtworkSubmission(StrictModel):
version: int = Field(ge=0, strict=True)
files: list[FileReference] = Field(min_length=1, max_length=60)
note: str = Field(min_length=1, max_length=1000)
class StampSize(StrictModel):
"""One row of the montador's size table (Fase 2, front 7)."""
letter: str = Field(pattern=r'^[A-Z]{1,2}$')
width_cm: Decimal = Field(gt=0, le=56, decimal_places=2)
class StampSizeTable(StrictModel):
"""The whole table, replaced in one go by Gestão."""
sizes: list[StampSize] = Field(min_length=1, max_length=26)
@model_validator(mode='after')
def letters_unique(self):
letters = [row.letter for row in self.sizes]
if len(letters) != len(set(letters)):
raise ValueError('Cada tamanho tem uma letra própria.')
return self

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,21 +44,55 @@ 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'),
unit_cents: int | None = None) -> dict:
"""The item's charge. The grade is validated and kept with the item; the
price does not depend on it."""
price does not depend on it. A split sheet has no minimum of its own: its
group has one (bill_splits). `unit_cents` is the current price from the
database (app/catalog.py); without it, the table above."""
length = Decimal(str(metres))
if mode not in 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
unit = (PRICES[mode] if unit_cents is None else unit_cents) + extra_cents
priced = {'mode': mode, 'metres': str(length), 'grade': grade,
'billed_metres': str(billed), 'unit_cents': unit,
'total_cents': int(billed * unit)}
if extra_cents:
priced['manual_extra_cents'] = extra_cents
return priced
def bill_splits(priced: list) -> list:
"""The order minimum of 1 m once per split group, on its first sheet: the
customer did not choose the split (item 17), so it never costs a metre more."""
for group in dict.fromkeys(i['split']['group'] for i in priced if i.get('split')):
parts = [i for i in priced if (i.get('split') or {}).get('group') == group]
short = Decimal('1') - sum(Decimal(i['billed_metres']) for i in parts)
if short > 0:
first = min(parts, key=lambda i: i['split']['part'])
billed = Decimal(first['billed_metres']) + short
first.update(billed_metres=str(billed), total_cents=int(billed * first['unit_cents']))
return priced
def apply_bands(priced: list, unit_by_mode: dict) -> list:
"""Rewrite the items of each mode to the band price for the order's total
metres of that product (front 8.2). The manual-file extra stays on top of
each item; a mode absent from `unit_by_mode` is untouched."""
for item in priced:
if item['mode'] in unit_by_mode:
unit = unit_by_mode[item['mode']] + item.get('manual_extra_cents', 0)
item['unit_cents'] = unit
item['total_cents'] = int(Decimal(str(item['billed_metres'])) * unit)
return priced
def sheet_label(item: dict) -> str:
"""' · folha 1 de 2' on a split sheet (item 17), for the customer's lists."""
split = item.get('split')
return f" · folha {split['part']} de {split['of']}" if split else ''

81
app/coupons.py Normal file
View File

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

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,11 +72,15 @@ 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),
('Total', money(snapshot.get('total_cents') or 0) + (f' · {paid}' if paid else ''))]
('Entrega', delivery)]
coupon = snapshot.get('coupon') or {}
if coupon:
rows.append((f"Cupom {coupon.get('code', '')}",
f"− {money(coupon.get('discount_cents') or 0)}"))
rows.append(('Total', money(snapshot.get('total_cents') or 0) + (f' · {paid}' if paid else '')))
number, link = order['number'], f"{origin}/conta/pedidos?order={order['id']}"
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
f'Seu pagamento foi aprovado e o pedido #{number} já está com a nossa equipe. '
@@ -90,6 +96,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
@@ -60,12 +60,20 @@ def is_test(order):
# (Dropstar's rule D-35, 2026-10-26; the user's answers of 2026-10-27).
MANUAL_PROVIDER = 'manual'
OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit')
# A montador order is invoiced, not paid at the counter: it is not one of the
# Cotações "registrar" methods.
INVOICED_METHOD = 'faturado'
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)."""
if (order.get('payment') or {}).get('method') == INVOICED_METHOD:
# Held until Dropstar decides how invoiced montador orders reach Tiny
# (asked 2026-11-09).
return False
return not is_test(order) and not order.get('parent_id')
# How long a file is kept while nothing has been paid for it. A cart's files
@@ -88,6 +96,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,10 +149,14 @@ 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)
# An invoiced montador order was not paid: no "pedido pago" e-mail until
# Dropstar says what the customer hears (asked 2026-11-09).
if payment.get('method') != INVOICED_METHOD:
mail.order_paid(c, order, PUBLIC_ORIGIN)
if not in_tiny(order):
return order, True
# How it was paid, for the order's payment in Tiny.

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

@@ -19,10 +19,10 @@ from decimal import Decimal
from fastapi import HTTPException
from psycopg.types.json import Jsonb
from . import payments
from . import catalog, coupons, 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 apply_bands, bill_splits, is_manual, manual_extra_cents, price
from .runtime import freight, upload_row
from .scanning import require_clean
@@ -64,30 +64,75 @@ 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:
upload = upload_row(c, upload_id, row['owner'])
require_clean(upload)
names[str(upload_id)] = upload['name']
catalog.require_enabled(c, item.mode)
extra = manual_extra_cents() if is_manual(original, names) else 0
priced.append({**price(item.mode, str(item.metres), item.grade, extra),
priced.append({**price(item.mode, str(item.metres), item.grade, extra,
minimum=Decimal('0') if item.split else Decimal('1'),
unit_cents=catalog.unit_cents(c, item.mode)),
'uploads': original['uploads'], 'production': original['production'],
'quality_status': original['quality_status'],
'quality_acknowledged': original['quality_acknowledged'],
'residue_accepted': original.get('residue_accepted', 0)})
'residue_accepted': original.get('residue_accepted', 0),
**({'residue_accepted_at': original['residue_accepted_at']}
if original.get('residue_accepted_at') else {}),
**({'stroke_px': original['stroke_px'], 'stroke_class': original['stroke_class']}
if original.get('stroke_class') else {}),
**({'stroke_choice': original['stroke_choice']} if original.get('stroke_choice') else {}),
**({'stroke_choice_at': original['stroke_choice_at']}
if original.get('stroke_choice_at') else {}),
**({'proof_y_fraction': original['proof_y_fraction']}
if original.get('proof_y_fraction') is not None else {}),
**({'source_dpi': original['source_dpi']} if original.get('source_dpi') else {}),
**({'split': original['split']} if original.get('split') else {})})
bill_splits(priced)
# Progressive bands (front 8.2): one price for the whole quantity of each
# product, chosen by the order's total billed metres of that mode.
totals = {}
for item in priced:
totals[item['mode']] = totals.get(item['mode'], Decimal('0')) + Decimal(item['billed_metres'])
banded = {}
for mode, total in totals.items():
price_for_total = catalog.unit_cents_for(c, mode, total)
if price_for_total != catalog.unit_cents(c, mode):
banded[mode] = price_for_total
apply_bands(priced, banded)
items_total = sum(i['total_cents'] for i in priced)
# The coupon discounts the items, after their bands, never freight or the
# treatment (front 8.3). It is checked again here: a quote that waited may
# have met an expiry or a use limit since it was created.
coupon = None
if draft.get('coupon'):
coupon = coupons.check(c, draft['coupon'], (draft.get('customer') or {}).get('cnpj'), priced)
discount = coupon['discount_cents'] if coupon else 0
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))
metres, items_total)
except ValueError as exc:
raise HTTPException(422, str(exc))
treatment = 0
if draft.get('treatment'):
# The designer's treatment is offered only when switched on and priced.
offer = catalog.current(c)['tratamento']
treatment = offer['unit_cents'] if offer['enabled'] else 0
approved = {'customer': draft['customer'], 'items': priced, 'freight': quoted_freight,
'destination': draft.get('destination'),
# The customer's proof only above 10 m (Dropstar, 2026-10-28).
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
'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 {}),
# The coupon used, for the order card, Números and Tiny (front 8.3).
**({'coupon': coupon} if coupon else {}),
# Browser timings are kept for Números, never for the price (0.12).
**({'timings': draft['timings']} if draft.get('timings') else {}),
'total_cents': items_total - discount + quoted_freight['total_cents'] + treatment}
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,10 @@ 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)]
coupon = snapshot.get('coupon') or {}
if coupon:
out.append((f"Cupom {coupon.get('code', '')}: - {money(coupon.get('discount_cents') or 0)}", 9, False, 4))
out += [('Valor', 7.5, False, 10), (money(snapshot.get('total_cents') or 0), 12, True, 1),
('Pagamento', 7.5, False, 6), (METHODS.get(paid_with, 'Teste' if paid_with == 'teste' else paid_with or '—'), 10, False, 1),
(f"Emitido em {issued.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')}", 8.5, False, 10),

131
app/reviews.py Normal file
View File

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

View File

@@ -12,6 +12,7 @@ from uuid import uuid5, NAMESPACE_URL
from fastapi import HTTPException
from psycopg.types.json import Jsonb
from . import catalog
from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime
from .freight import FreightOptions
from .core.secrets import load as load_secret_files
@@ -32,6 +33,7 @@ if os.environ.get('FREIGHT_ADAPTER') == 'jadlog':
from .jadlog import JadlogFreight
_carriers.append(JadlogFreight())
from . import correios as _correios
from . import prumo
if _correios.configured():
_carriers.append(_correios.CorreiosFreight())
freight = FreightOptions(_carriers or [FakeFreight()])
@@ -103,21 +105,51 @@ 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'):
offer = catalog.current(c)['tratamento']
if offer['enabled'] and offer['unit_cents'] > 0:
treatment = {'cents': offer['unit_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.
@@ -249,16 +284,14 @@ CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names (
-- from the console); administrators manage users and machines; gestão runs
-- the business; designers approve artwork; operadores print; revisores check
-- the printed sheet and are the only ones to release it to Finalizado;
-- vendedores only read.
-- vendedores only read; expedição assembles sheets in the Kanban's montador.
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin';
ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro'));
-- 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.
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao'));
-- 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,162 @@ 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)
);
-- Orders generated before the print file was a PNG with its strips (item 13)
-- open blank in the 100% viewer. Those not approved yet are generated again,
-- once: the same layout, now as PNG with strips. An approved final, a
-- customer's correction or a cancelled order is left as it is.
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='png-regenerate-v1') THEN
UPDATE dtf_local.print_files p SET status='pending', attempts=0, claimed_at=NULL, claim_token=NULL,
finished_at=NULL, upload_id=NULL, detail='{}'
FROM dtf_local.orders o
WHERE o.id=p.order_id AND o.state='rec' AND o.cancelled_at IS NULL
AND p.status='ready' AND NOT (p.detail ? 'format')
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=p.order_id
AND f.item_index=p.item_index AND f.active);
INSERT INTO dtf_local.migrations VALUES('png-regenerate-v1');
END IF;
END $$;
-- Front 8: what the Site sells and at what price, edited in the Kanban's Site tab.
CREATE TABLE IF NOT EXISTS dtf_local.products (
id text PRIMARY KEY CHECK (id IN ('file','avulsa','uvfile','uv','tratamento')),
enabled boolean NOT NULL DEFAULT true,
updated_by text NOT NULL DEFAULT 'sistema',
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO dtf_local.products(id) VALUES ('file'),('avulsa'),('uvfile'),('uv'),('tratamento')
ON CONFLICT (id) DO NOTHING;
CREATE TABLE IF NOT EXISTS dtf_local.product_prices (
id bigserial PRIMARY KEY,
product text NOT NULL REFERENCES dtf_local.products(id),
unit_cents integer NOT NULL CHECK (unit_cents >= 0 AND unit_cents <= 10000000),
starts_at timestamptz NOT NULL,
created_by text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS product_prices_current ON dtf_local.product_prices(product, starts_at DESC);
-- Front 7a: the stamp sizes of the Kanban's montador; Gestão edits them.
CREATE TABLE IF NOT EXISTS dtf_local.stamp_sizes (
letter text PRIMARY KEY CHECK (letter ~ '^[A-Z]{1,2}$'),
width_cm numeric(5,2) NOT NULL CHECK (width_cm > 0 AND width_cm <= 56),
updated_by text NOT NULL DEFAULT 'sistema',
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES ('A',20),('B',24),('C',27),('D',30)
ON CONFLICT (letter) DO NOTHING;
-- Front 8.2: a price may also have bands by the order's total metres of that
-- product: base price, then "from 5 m R$ Y", "from 20 m R$ Z" (jsonb list of
-- {"from_metres": "5", "unit_cents": 1990}, strictly increasing, at most 5).
ALTER TABLE dtf_local.product_prices ADD COLUMN IF NOT EXISTS bands jsonb NOT NULL DEFAULT '[]';
-- Front 8.3: discount coupons, created in the Kanban's Site tab. The id is
-- generated in Python (schema.sql does not use gen_random_uuid). A deleted
-- code may be created again; the orders that used it keep its id and code.
CREATE TABLE IF NOT EXISTS dtf_local.coupons (
id uuid PRIMARY KEY,
code text NOT NULL CHECK (code ~ '^[A-Z0-9-]{3,30}$'),
kind text NOT NULL CHECK (kind IN ('percent','per_metre')),
value integer NOT NULL CHECK (value > 0), -- percent: 1..90; per_metre: cents per billed metre
valid_from timestamptz NOT NULL DEFAULT now(),
valid_until timestamptz,
min_metres numeric(8,1),
max_uses integer CHECK (max_uses > 0),
max_uses_per_customer integer CHECK (max_uses_per_customer > 0),
product text CHECK (product IN ('file','avulsa','uvfile','uv')), -- NULL = every product
note text NOT NULL DEFAULT '',
paused boolean NOT NULL DEFAULT false,
deleted_at timestamptz,
created_by text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX IF NOT EXISTS coupons_live_code ON dtf_local.coupons(code) WHERE deleted_at IS NULL;

View File

@@ -51,6 +51,9 @@ from urllib.parse import urlencode
import httpx
from . import catalog
from .core import db
API = 'https://api.tiny.com.br/public-api/v3'
AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect'
# Not TINY_PRODUCT_<MODE>: app/core/secrets.py reads any variable ending in
@@ -166,8 +169,15 @@ 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.
with db.connect() as c:
treatment = catalog.current(c)['tratamento']
if treatment['enabled'] and treatment['unit_cents'] > 0:
required.append('TINY_PRODUCT_TREATMENT')
return required
# The stack passes every setting, empty when unset, so empty means "the
@@ -489,6 +499,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'
@@ -500,13 +518,18 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
'valorFrete': money(freight['total_cents']),
'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''),
'observacoesInternas': internal_note(payload)}
coupon = order.get('coupon') or {}
if coupon:
# Tiny's v3 order has the order-level discount next to valorFrete.
pedido['valorDesconto'] = money(coupon.get('discount_cents') or 0)
carrier = shipping(service) if shipping else None
if carrier:
pedido['transportador'] = {'fretePorConta': FREIGHT_PAID_BY, **carrier}
# The carrier's time already counts production; a pickup is ready after it.
days = freight.get('days') if not pickup else int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0)
if days is not None:
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

@@ -26,8 +26,8 @@ server {
add_header X-Content-Type-Options nosniff always;
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 Permissions-Policy "camera=(self), microphone=(), geolocation=()" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
location = /health { access_log off; return 200 'ok'; }
location /api/ {

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

@@ -8,8 +8,8 @@ server {
add_header X-Content-Type-Options nosniff always;
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 Permissions-Policy "camera=(self), microphone=(), geolocation=()" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
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="site"]');
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(', '));
}
}

152
tests/coupons_test.py Normal file
View File

@@ -0,0 +1,152 @@
"""Coupons: creation, the discount on one product, refused states and uses.
Run against the local stack: SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost
python -m tests.coupons_test
"""
import secrets
from datetime import datetime, timedelta, timezone
from uuid import uuid4
from psycopg.types.json import Jsonb
from app.core import db
from tests.print_file_test import artwork
from tests.smoke_test import Client, item_spec, upload_bytes
def quote(client, items, coupon, mail, expected=200):
body = {'request_key': str(uuid4()),
'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail},
'items': items, 'freight': {'service': 'pickup'}, 'coupon': coupon}
return client.call('/quotes', body, expected=expected)
def run():
tag = secrets.token_hex(4)
code = f'CUPOM-{tag.upper()}'
mail = f'coupon-{tag}@example.test'
client = Client()
client.call('/session')
manager = Client()
manager.call('/session')
manager.call('/operator/me', operator=True)
manager = manager.operator_client
coupon_id = None
quote_id = None
order_id = None
upload_id = None
try:
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-COUPON-{tag}.png')
sheet = {**item_spec('uvfile', '1', 0, upload_id),
'quality_status': 'warning', 'quality_acknowledged': True}
# The sheet is the customer's own file, not one someone opens by hand.
sheet['production']['sources'][0]['measurement'] = 'file'
art = {**item_spec('uv', '1', 0, upload_id),
'quality_status': 'warning', 'quality_acknowledged': True}
items = [sheet, art]
refused = quote(client, items, f'NAO-EXISTE-{tag.upper()}', mail, expected=422)
assert refused['detail'] == 'Cupom não encontrado.', refused
coupon_id = manager.call('/operator/site/coupons', {
'code': code, 'kind': 'percent', 'value': 10, 'product': 'uv'})['id']
# The discount is on the uv item only; the items keep their prices.
made = quote(client, items, code, mail)
quote_id = made['id']
assert made['status'] == 'approved', made
approved = client.call('/quotes/' + quote_id)['approved']
assert approved['coupon']['code'] == code, approved
assert approved['coupon']['discount_cents'] == 899, approved
assert [line['total_cents'] for line in approved['items']] == [7990, 8990], approved
assert approved['total_cents'] == 16081, approved
# One paid order spends a use (a fake payment, no print job).
order_id = uuid4()
with db.connect() as c:
owner = c.execute('SELECT owner FROM dtf_local.quotes WHERE id=%s', (quote_id,)).fetchone()['owner']
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
VALUES(%s,%s,%s,%s,%s,'site')''',
(order_id, quote_id, owner, Jsonb(approved),
Jsonb({'provider': 'fake', 'id': f'coupon-{tag}'})))
listed = next(row for row in manager.call('/operator/site/coupons')['coupons']
if row['id'] == coupon_id)
assert listed['uses'] == 1, listed
# Paused.
manager.call('/operator/site/coupons/' + coupon_id, {'paused': True})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Este cupom está pausado.', refused
manager.call('/operator/site/coupons/' + coupon_id, {'paused': False})
now = datetime.now(timezone.utc)
# Expired.
manager.call('/operator/site/coupons/' + coupon_id, {
'valid_from': (now - timedelta(days=2)).isoformat(),
'valid_until': (now - timedelta(days=1)).isoformat()})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Este cupom expirou.', refused
# Not started yet.
manager.call('/operator/site/coupons/' + coupon_id, {
'valid_from': (now + timedelta(days=1)).isoformat(), 'valid_until': None})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Este cupom ainda não começou.', refused
manager.call('/operator/site/coupons/' + coupon_id,
{'valid_from': now.isoformat(), 'valid_until': None})
# Minimum metres, counted on the eligible uv item only.
manager.call('/operator/site/coupons/' + coupon_id, {'min_metres': '5'})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Este cupom pede pelo menos 5 m.', refused
manager.call('/operator/site/coupons/' + coupon_id, {'min_metres': None})
# Only one product.
manager.call('/operator/site/coupons/' + coupon_id, {'product': 'file'})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Este cupom vale só para Têxtil folha pronta.', refused
manager.call('/operator/site/coupons/' + coupon_id, {'product': 'uv'})
# Max uses, then the per-customer limit on its own.
manager.call('/operator/site/coupons/' + coupon_id, {'max_uses': 1})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Este cupom já foi usado o máximo de vezes.', refused
manager.call('/operator/site/coupons/' + coupon_id,
{'max_uses': None, 'max_uses_per_customer': 1})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Você já usou este cupom.', refused
manager.call('/operator/site/coupons/' + coupon_id,
{'max_uses_per_customer': None})
# Números lists the coupon's paid order, metres, discount and money.
stats = manager.call('/operator/stats?days=30')
row = next(entry for entry in stats['coupons'] if entry['id'] == coupon_id)
assert row['orders'] == 1 and row['metres'] == 2.0, row
assert row['discount_cents'] == 899 and row['cents'] == 16081, row
# Soft delete: the code leaves the list, the paid order keeps it and
# Números keeps counting it.
manager.call('/operator/site/coupons/' + coupon_id + '/delete', {})
assert not any(entry['id'] == coupon_id
for entry in manager.call('/operator/site/coupons')['coupons'])
with db.connect() as c:
snapshot = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s',
(order_id,)).fetchone()['snapshot']
assert snapshot['coupon']['code'] == code, snapshot
stats = manager.call('/operator/stats?days=30')
assert any(entry['id'] == coupon_id for entry in stats['coupons']), stats['coupons']
print('PASS: a coupon discounts one product, refuses paused/expired/not-started/'
'minimum/product/use states, reaches Tiny data and Números, and soft delete keeps history')
finally:
with db.connect() as c:
if order_id:
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,))
if quote_id:
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote_id,))
if coupon_id:
c.execute('DELETE FROM dtf_local.coupons WHERE id=%s', (coupon_id,))
if upload_id:
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s', (upload_id,))
if __name__ == '__main__':
run()

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

141
tests/site_admin_test.py Normal file
View File

@@ -0,0 +1,141 @@
"""The Kanban's Site tab: products switched on and off, prices with a history.
Run against the local stack: SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost
python -m tests.site_admin_test
"""
import secrets
from datetime import datetime, timedelta, timezone
from uuid import uuid4
from app.core import db
from tests.print_file_test import artwork
from tests.smoke_test import Client, item_spec, upload_bytes
PASSWORD = 'senha-de-teste-123'
UV = 'uv'
def quote(client, item, mail):
return client.call('/quotes', {'request_key': str(uuid4()),
'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail},
'items': [item], 'freight': {'service': 'pickup'}})
def run():
tag = secrets.token_hex(4)
mail = f'site-admin-{tag}@example.test'
client = Client()
client.call('/session')
# The default operator login is the superadmin, which may manage the Site.
manager = Client()
manager.call('/session')
manager.call('/operator/me', operator=True)
manager = manager.operator_client
prices, user = [], None
try:
products = manager.call('/operator/site/products')['products']
assert {product['id'] for product in products} == {'file', 'avulsa', 'uvfile', 'uv', 'tratamento'}
assert all(product['unit'] in ('metro', 'pedido') and product['title'] for product in products)
manager.call(f'/operator/site/products/{UV}', {'enabled': True})
uid = upload_bytes(client, artwork(), name='LOCAL-SITE-ADMIN.png')
item = {**item_spec('uv', '1', 0, uid), 'quality_status': 'warning', 'quality_acknowledged': True}
before = client.call('/session')['products'][UV]['unit_cents']
# Switched off: the Site sees it off and the server refuses a new quote.
manager.call(f'/operator/site/products/{UV}', {'enabled': False})
assert client.call('/session')['products'][UV]['enabled'] is False
refused = client.call('/quotes', {'request_key': str(uuid4()),
'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail},
'items': [item], 'freight': {'service': 'pickup'}}, expected=422)
assert refused['detail'] == 'Este produto não está à venda agora.', refused
manager.call(f'/operator/site/products/{UV}', {'enabled': True})
assert client.call('/session')['products'][UV]['enabled'] is True
# A price in the future does not change today's and can be cancelled.
made = manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 23456,
'starts_at': (datetime.now(timezone.utc) + timedelta(minutes=1)).isoformat()})
prices.append(made['id'])
assert client.call('/session')['products'][UV]['unit_cents'] == before
entry = next(product for product in manager.call('/operator/site/products')['products']
if product['id'] == UV)
assert any(row['id'] == made['id'] for row in entry['scheduled']), entry
manager.call(f'/operator/site/prices/{made["id"]}/cancel', {})
entry = next(product for product in manager.call('/operator/site/products')['products']
if product['id'] == UV)
assert not any(row['id'] == made['id'] for row in entry['scheduled']), entry
# A start date in the past is refused.
manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 1000,
'starts_at': (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()}, expected=422)
# A price that starts now is what /api/session and a new quote charge.
made = manager.call(f'/operator/site/products/{UV}/prices', {'unit_cents': 12345})
prices.append(made['id'])
assert client.call('/session')['products'][UV]['unit_cents'] == 12345
created = quote(client, item, mail)
assert created['status'] == 'approved', created
approved = client.call('/quotes/' + created['id'])['approved']
assert approved['items'][0]['unit_cents'] == 12345, approved
assert approved['items'][0]['total_cents'] == 12345, approved
# Bands (front 8.2): from 2 m the metre costs less; two items of uv
# (2 m together) pay the band price on both.
made = manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 12345, 'bands': [{'from_metres': '2', 'unit_cents': 10000}]})
prices.append(made['id'])
bands = client.call('/session')['products'][UV]['bands']
assert bands == [{'from_metres': 2.0, 'unit_cents': 10000}], bands
entry = next(product for product in manager.call('/operator/site/products')['products']
if product['id'] == UV)
assert entry['bands'] == [{'from_metres': '2', 'unit_cents': 10000}], entry
banded = client.call('/quotes', {'request_key': str(uuid4()),
'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail},
'items': [item, item], 'freight': {'service': 'pickup'}})
assert banded['status'] == 'approved', banded
approved = client.call('/quotes/' + banded['id'])['approved']
assert [line['unit_cents'] for line in approved['items']] == [10000, 10000], approved
assert [line['total_cents'] for line in approved['items']] == [10000, 10000], approved
assert approved['total_cents'] == 20000, approved
# Invalid bands are refused with 422 and do not become prices.
manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 12345, 'bands': [{'from_metres': '5', 'unit_cents': 1900},
{'from_metres': '5', 'unit_cents': 1800}]}, expected=422)
manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 12345, 'bands': [{'from_metres': '0', 'unit_cents': 1900}]}, expected=422)
manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 12345, 'bands': [{'from_metres': str(i), 'unit_cents': 1900}
for i in range(1, 7)]}, expected=422)
manager.call('/operator/site/products/tratamento/prices', {
'unit_cents': 1000, 'bands': [{'from_metres': '5', 'unit_cents': 900}]}, expected=422)
# A profile without "manage" cannot see or change the Site tab.
email = f'site-staff-{tag}@example.test'
user = manager.call('/operator/users', {'name': 'Teste Site', 'email': email,
'role': 'operador', 'password': PASSWORD})
staff = Client()
staff.call('/session')
staff.call('/operator/login', {'email': email, 'password': PASSWORD})
staff.call('/operator/site/products', expected=403)
staff.call(f'/operator/site/products/{UV}', {'enabled': True}, expected=403)
staff.call(f'/operator/site/products/{UV}/prices', {'unit_cents': 1000}, expected=403)
staff.call(f'/operator/site/prices/{made["id"]}/cancel', {}, expected=403)
print('PASS: the Site tab switches a product off and refuses quotes, schedules and cancels prices,'
' charges the new price, and refuses a non-manage profile')
finally:
with db.connect() as c:
if prices:
c.execute('DELETE FROM dtf_local.product_prices WHERE id=ANY(%s::bigint[])', (prices,))
c.execute("UPDATE dtf_local.products SET enabled=true WHERE id=%s", (UV,))
if user:
try:
manager.call('/operator/users/' + str(user['id']) + '/delete', {}, expected=200)
except Exception:
pass
if __name__ == '__main__':
run()

89
tests/site_video_test.py Normal file
View File

@@ -0,0 +1,89 @@
"""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'])
# Captions are optional (front 8.4): the video alone is published. The
# published VTT copy stops being referenced, so keep it for cleanup.
with db.connect() as c:
old = c.execute("SELECT captions_key FROM dtf_local.site_videos WHERE id='sala'").fetchone()
if old and old['captions_key']:
keys.append(old['captions_key'])
operator.call('/operator/site-videos/sala', {'upload_id': video,
'product': 'file', 'enabled': True})
entry = next(row for row in client.call('/site/videos')['videos'] if row['id'] == 'sala')
assert entry['captions'] is None, entry
client.call('/site/videos/sala/captions', expected=404)
operator.call('/operator/site-videos/sala', {'upload_id': video,
'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 with signed media, with or without captions;'
' 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()

150
tests/stamps_test.py Normal file
View File

@@ -0,0 +1,150 @@
"""The montador: stamp sizes, and the invoiced order a sheet becomes.
Run against the local stack: python -m tests.stamps_test
"""
import secrets
import time
from pathlib import Path
from urllib.request import Request, urlopen
from uuid import UUID, uuid4
from app.core import db
from app.runtime import operator_identity
from tests.smoke_test import Client
PASSWORD = 'senha-de-teste-123'
PNG = (Path(__file__).resolve().parent / 'fixtures' / 'final-300.png').read_bytes()
def signed_in(email, password=PASSWORD):
client = Client()
client.call('/session')
client.call('/operator/login', {'email': email, 'password': password})
return client
def upload_stamp(client, name='LOCAL-ESTAMP.png'):
start = client.call('/operator/montador/uploads', {'name': name, 'size': len(PNG)})
uid = start['id']
url = client.call(f'/operator/uploads/{uid}/parts/1', {})['url']
with urlopen(Request(url, data=PNG, method='PUT'), timeout=30) as response:
assert response.status == 200
client.call(f'/operator/uploads/{uid}/complete', {})
deadline = time.monotonic() + 150
while client.call(f'/operator/uploads/{uid}')['scan_state'] != 'clean':
assert time.monotonic() < deadline, 'stamp scan did not finish'
time.sleep(0.5)
return uid
def montador_item(uid, mode='avulsa'):
"""One source, 3 copies in a row: a valid Item for the montador route."""
sheet = mode == 'file'
height = 1.75 if sheet else 1.25
return {
'mode': mode, 'metres': height / 100, 'grade': 100, 'uploads': [uid],
'production': {
'version': 3, 'film_width_cm': 57, 'height_cm': height,
'sources': [{'upload_id': uid, 'kind': 'sheet' if sheet else 'artwork',
'width_cm': 0.5, 'length_cm': 0.25, 'copies': 3,
'rotation_degrees': 0, 'mirrored': False, 'measurement': 'file'}],
'placements': [{'source_index': 0, 'copy_index': copy,
'x_cm': 0 if sheet else 0.5 + copy * 1.0, 'y_cm': 0.5 + copy * 0.5 if sheet else 0.5,
'width_cm': 0.5, 'length_cm': 0.25,
'rotation_degrees': 0, 'mirrored': False} for copy in range(3)]},
'quality_status': 'ok', 'quality_acknowledged': False, 'residue_accepted': 0}
def run():
tag = secrets.token_hex(3)
su = Client()
su.call('/session')
assert su.call('/operator/me', operator=True)['role'] == 'superadmin'
with db.connect() as c:
original = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall()
emails = {role: f'{role}-{tag}@example.test' for role in ('expedicao', 'designer', 'gestao')}
table = [(row['letter'], float(row['width_cm'])) for row in original]
customer = {'name': 'Cliente Montador', 'cnpj': '11222333000181', 'zap': '16999999999',
'mail': f'montador-{tag}@example.test'}
identity = operator_identity(emails['expedicao'])
made_orders, made_quotes = [], []
try:
for role, email in emails.items():
su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role,
'password': PASSWORD}, operator=True)
# The new profile creates through the users API and reads the table.
shipping = signed_in(emails['expedicao'])
me = shipping.call('/operator/me')
assert me['role'] == 'expedicao' and me['can'] == ['assemble', 'view'], me
read = shipping.call('/operator/stamp-sizes')['sizes']
assert [(row['letter'], float(row['width_cm'])) for row in read] == table, read
# The designer does not assemble: no reading the table.
designer = signed_in(emails['designer'])
designer.call('/operator/stamp-sizes', expected=403)
# Gestão replaces the whole table in one go and reads it back, by width.
manager = signed_in(emails['gestao'])
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'D', 'width_cm': 30},
{'letter': 'A', 'width_cm': 20},
{'letter': 'B', 'width_cm': 24.5}]})
read = manager.call('/operator/stamp-sizes')['sizes']
assert [(row['letter'], float(row['width_cm'])) for row in read] == [('A', 20), ('B', 24.5), ('D', 30)], read
# A repeated letter and a width out of range are refused.
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 20},
{'letter': 'A', 'width_cm': 24}]},
expected=422)
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 0}]},
expected=422)
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 57}]},
expected=422)
# Expedição only reads them; saving stays with Gestão.
shipping.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 20}]},
expected=403)
read = manager.call('/operator/stamp-sizes')['sizes']
assert [(row['letter'], float(row['width_cm'])) for row in read] == [('A', 20), ('B', 24.5), ('D', 30)], read
# The montador's order: the stamp upload, then the invoiced card in rec.
stamp = upload_stamp(shipping)
request_key = uuid4()
body = {'request_key': str(request_key), 'customer': customer,
'items': [montador_item(stamp)]}
order = shipping.call('/operator/montador/orders', body)
made_orders.append(UUID(order['id']))
made_quotes.append(UUID(order['quote_id']))
assert order['state'] == 'rec' and order['origin'] == 'dropflow', order
payment = order['payment']
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'faturado', 'paid'), payment
assert payment['total_cents'] == order['snapshot']['total_cents'], payment
with db.connect() as c:
assert c.execute('SELECT 1 FROM dtf_local.print_files WHERE order_id=%s',
(UUID(order['id']),)).fetchone()
assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s',
(f"{order['id']}:paid:tiny",)).fetchone()
# The same montagem cannot become a second order.
refused = shipping.call('/operator/montador/orders', body, expected=409)
assert refused['detail'] == f"Esta montagem já virou o pedido #{order['number']}.", refused
# A designer does not use the montador, and only loose art becomes one.
designer.call('/operator/montador/uploads', {'name': 'ESTAMPA.png', 'size': 1}, expected=403)
designer.call('/operator/montador/orders', body, expected=403)
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'customer': customer,
'items': [montador_item(stamp, 'file')]}, expected=422)
print('PASS: Expedição reads the sizes, uploads a stamp and gets the invoiced montador card; '
'Gestão edits the table; invalid rows, profiles and modes are refused')
finally:
with db.connect() as c:
for oid in made_orders:
c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (oid,))
c.execute('DELETE FROM dtf_local.order_files WHERE order_id=%s', (oid,))
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (oid,))
c.execute('DELETE FROM dtf_local.contact_waits WHERE order_id=%s', (oid,))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,))
if made_quotes:
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', (made_quotes,))
c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr=%s', (customer['mail'],))
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (identity,))
c.execute('DELETE FROM dtf_local.stamp_sizes')
c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES(%s,%s)', table)
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))
if __name__ == '__main__':
run()

38
tests/test_coupons.py Normal file
View File

@@ -0,0 +1,38 @@
"""Run from repository root: python3 -m unittest tests.test_coupons -v."""
import unittest
from app.coupons import discount_cents, eligible_items
def item(mode, billed_metres, total_cents):
return {'mode': mode, 'billed_metres': billed_metres, 'total_cents': total_cents}
class CouponTests(unittest.TestCase):
def test_percent_is_floored(self):
self.assertEqual(discount_cents('percent', 10, [item('file', '1', 1990)]), 199)
self.assertEqual(discount_cents('percent', 33, [item('file', '1', 1990)]), 656)
self.assertEqual(discount_cents('percent', 10, []), 0)
def test_per_metre_is_floored_to_the_cent(self):
items = [item('file', '2.5', 5475), item('file', '1.5', 3285)]
self.assertEqual(discount_cents('per_metre', 200, items), 800)
# 333 cents x 1.1 m = 366.3 cents: the customer gets 366.
self.assertEqual(discount_cents('per_metre', 333, [item('file', '1.1', 2409)]), 366)
def test_product_filter(self):
items = [item('file', '1', 1990), item('uv', '1', 8990)]
self.assertEqual(eligible_items(items, 'uv'), [items[1]])
self.assertEqual(eligible_items(items, None), items)
def test_never_more_than_the_items_total(self):
self.assertEqual(discount_cents('per_metre', 1000, [item('file', '2', 1500)]), 1500)
self.assertEqual(discount_cents('percent', 90, [item('file', '1', 100)]), 90)
def test_invalid_kind(self):
with self.assertRaises(ValueError):
discount_cents('other', 10, [item('file', '1', 1990)])
if __name__ == '__main__':
unittest.main()

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,7 +1,10 @@
"""Who moves which card on the Kanban: Dropstar's flow of 2026-10-23."""
import unittest
from unittest import mock
from app.core.auth import ROLES, may_move, may_reorder
from app import payments
from app.core import auth
from app.core.auth import CAPABILITIES, ROLES, may_move, may_reorder
from app.runtime import BACK, STATES, TRANSITIONS
@@ -41,6 +44,17 @@ class MovesTest(unittest.TestCase):
self.assertTrue(may_move('gestao', 'fin', 'rev', back=True))
self.assertFalse(may_move('vendedor', 'tra', 'rec', back=True))
def test_expedicao_moves_nothing(self):
# The new shipping profile assembles sheets (Fase 2, front 7) and reads
# the board; it moves no card and orders no column.
self.assertIn('expedicao', ROLES)
self.assertEqual(moves('expedicao'), set())
self.assertEqual([s for s in STATES if may_reorder('expedicao', s)], [])
def test_the_montador_is_open_to_exactly_five_profiles(self):
self.assertEqual(CAPABILITIES['assemble'],
{'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'})
def test_a_column_is_ordered_by_whoever_takes_its_cards_forward(self):
self.assertEqual([s for s in STATES if may_reorder('operador', s)], ['tra', 'imp'])
self.assertEqual([s for s in STATES if may_reorder('designer', s)], ['rec', 'cor'])
@@ -49,5 +63,29 @@ class MovesTest(unittest.TestCase):
self.assertTrue(all(may_reorder('gestao', s) for s in STATES))
class CanAnyTest(unittest.TestCase):
def test_a_profile_with_any_of_the_capabilities_gets_through(self):
# The montador's stamp uploads: deliver or assemble (Fase 2, front 7).
for role, allowed in (('operador', True), ('expedicao', True), ('vendedor', True),
('designer', True), ('financeiro', False)):
with mock.patch.object(auth, 'signed_in',
return_value={'role': role, 'email': role + '@example.test'}):
route = auth.can_any('deliver', 'assemble')
if allowed:
self.assertEqual(route(None), role + '@example.test')
else:
with self.assertRaises(auth.HTTPException):
route(None)
class InvoicedOrderTest(unittest.TestCase):
def test_an_invoiced_montador_order_is_held_out_of_tiny(self):
self.assertEqual(payments.INVOICED_METHOD, 'faturado')
# It is not one of the Cotações "registrar" methods.
self.assertNotIn(payments.INVOICED_METHOD, payments.OUTSIDE_METHODS)
self.assertFalse(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'faturado'}}))
self.assertTrue(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'pix'}}))
if __name__ == '__main__':
unittest.main()

View File

@@ -1,9 +1,13 @@
"""Run from repository root: python3 -m unittest tests.test_pricing -v."""
import json
import os
from decimal import Decimal
from pathlib import Path
from unittest.mock import patch
import subprocess
import unittest
from app.core.pricing import is_manual, price, PRICES
from app.catalog import band_price
from app.core.pricing import apply_bands, bill_splits, is_manual, price, PRICES, treatment_cents
class PricingTests(unittest.TestCase):
def test_every_length_against_actual_site_javascript(self):
@@ -53,6 +57,81 @@ class PricingTests(unittest.TestCase):
for bad in (-1, True, 1.5):
with self.assertRaises(ValueError):price('file', '1', 0, bad)
def test_the_catalog_price_replaces_the_table_price(self):
# The Kanban's Site tab sets the price in the database (front 8); the
# minimum and the ten-centimetre rounding stay the Site's.
priced = price('avulsa', '2.75', 90, unit_cents=1234)
self.assertEqual(price('avulsa', '2.75', 90)['unit_cents'], PRICES['avulsa'])
self.assertEqual(priced['unit_cents'], 1234)
self.assertEqual(priced['billed_metres'], '2.8')
self.assertEqual(priced['total_cents'], 3455)
# A hand-opened sheet still pays the extra on top of the new price.
extra = price('file', '1.01', 0, 500, unit_cents=1234)
self.assertEqual(extra['unit_cents'], 1734)
self.assertEqual(extra['billed_metres'], '1.1')
self.assertEqual(extra['total_cents'], 1907)
def test_band_price_below_at_between_and_above(self):
# Front 8.2: the highest band reached wins, and it charges the whole
# quantity, not a staircase.
bands = [{'from_metres': '5', 'unit_cents': 1990},
{'from_metres': '20', 'unit_cents': 1890}]
self.assertEqual(band_price(2190, bands, Decimal('4.9')), 2190)
self.assertEqual(band_price(2190, bands, Decimal('5')), 1990)
self.assertEqual(band_price(2190, bands, Decimal('19.9')), 1990)
self.assertEqual(band_price(2190, bands, Decimal('20')), 1890)
self.assertEqual(band_price(2190, bands, Decimal('12000')), 1890)
# No bands, or a number from the session, is the base price.
self.assertEqual(band_price(2190, [], Decimal('5')), 2190)
self.assertEqual(band_price(2190, [{'from_metres': 5, 'unit_cents': 1990}], Decimal('5')), 1990)
def test_apply_bands_prices_the_whole_product_together(self):
# Two items of the same mode reach the band together: both pay it.
priced = [{'mode': 'file', 'billed_metres': '2.5', 'unit_cents': 2190, 'total_cents': 5475},
{'mode': 'file', 'billed_metres': '2.5', 'unit_cents': 2190, 'total_cents': 5475}]
apply_bands(priced, {'file': 1990})
self.assertEqual([item['unit_cents'] for item in priced], [1990, 1990])
self.assertEqual([item['total_cents'] for item in priced], [4975, 4975])
# A split group counts its billed metres once, after bill_splits.
priced = [{'mode': 'avulsa', 'billed_metres': '0.2', 'unit_cents': 2190, 'total_cents': 438,
'split': {'group': 'g', 'part': 1, 'of': 2}},
{'mode': 'avulsa', 'billed_metres': '0.3', 'unit_cents': 2190, 'total_cents': 657,
'split': {'group': 'g', 'part': 2, 'of': 2}}]
bill_splits(priced)
self.assertEqual(priced[0]['billed_metres'], '0.7')
apply_bands(priced, {'avulsa': 1890})
self.assertEqual(priced[0]['total_cents'], 1323)
self.assertEqual(priced[1]['total_cents'], 567)
# The manual-file extra stays on top of the band price.
priced = [{'mode': 'file', 'billed_metres': '2', 'unit_cents': 2190,
'manual_extra_cents': 200, 'total_cents': 4380}]
apply_bands(priced, {'file': 1890})
self.assertEqual(priced[0]['unit_cents'], 2090)
self.assertEqual(priced[0]['total_cents'], 4180)
# Another mode is untouched.
uv = {'mode': 'uv', 'billed_metres': '1', 'unit_cents': 8990, 'total_cents': 8990}
priced = [{'mode': 'file', 'billed_metres': '1', 'unit_cents': 2190, 'total_cents': 2190}, uv]
apply_bands(priced, {'file': 1990})
self.assertEqual((uv['unit_cents'], uv['total_cents']), (8990, 8990))
def test_band_prices_against_actual_site_javascript(self):
# The Site must show the same band price the server charges: run its
# own precoNaMetragem for the same table and totals.
source = Path('web/site-config.js').read_text()
prices = source.split('const PRECO=')[1].split(';', 1)[0]
body = source.split('function precoNaMetragem', 1)[1].split('\n}', 1)[0]
bands = [{'from_metres': 5, 'unit_cents': 1990},
{'from_metres': 20, 'unit_cents': 1890}]
js = ('const PRECO=' + prices + ';const FAIXAS=' + json.dumps({'file': bands}) + ';'
'function precoNaMetragem' + body + '\n}'
';const results=[];for(const m of ["4.9","5","19.9","20","60"])'
'results.push([m,Math.round(precoNaMetragem("file",Number(m))*100)]);'
'process.stdout.write(JSON.stringify(results));')
cases = json.loads(subprocess.check_output(['node', '-e', js], text=True))
for metres, cents in cases:
with self.subTest(metres=metres):
self.assertEqual(cents, band_price(PRICES['file'], bands, Decimal(metres)))
def test_which_items_are_opened_by_hand(self):
def item(kind, measurement, uid='u1'):
return {'production': {'sources': [{'kind': kind, 'measurement': measurement, 'upload_id': uid}]}}
@@ -63,6 +142,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'] == ['assemble', '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

@@ -9,11 +9,14 @@
let shownCart = null;
let pixClock = null;
let busy = false;
// Every product switched off in the Kanban's Site tab (front 8).
let semPedidos = false;
let draftId = localStorage.getItem('dtf-quote');
let requestKey = localStorage.getItem('dtf-request-key');
let requestBody = localStorage.getItem('dtf-request-body');
let quotedCart = localStorage.getItem('dtf-quote-cart');
let refreshVersion = 0;
const cupomCode=()=>{const el=document.getElementById('fCupom');return el?el.value.trim().toUpperCase():'';};
function cartSnapshot() {
const items=itensAPagar();
return JSON.stringify({customer:cliente,delivery:entrega,items:items.map(item=>({
@@ -21,8 +24,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,coupon:cupomCode()});
}
// The quote this browser is paying, forgotten. clearDraft also empties the
// payment area; forgetDraft leaves on screen what is there (a confirmation).
@@ -72,6 +77,47 @@
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;
}
// What the Site sells and at what price, from the database (front 8). An
// older server sends no `products`: the page keeps PRECO.
if(session.products){
for(const [mode,product] of Object.entries(session.products)){
PRECO[mode]=product.unit_cents/100;
FAIXAS[mode]=product.bands||[];
const card=document.querySelector('button.ec[data-modo="'+mode+'"]');
if(card&&!product.enabled)card.hidden=true;
}
document.querySelectorAll('[data-preco]').forEach(el=>{
const product=session.products[el.dataset.preco];
el.textContent=product&&!product.enabled?'Indisponível':rs(PRECO[el.dataset.preco]);
});
// The home price table keeps the base price; the bands go under it.
const tabelaFaixas=document.getElementById('tabelaFaixas');
if(tabelaFaixas){
const linhas=Object.entries(session.products)
.filter(([,product])=>product.enabled && product.bands?.length)
.map(([mode,product])=>node('div',MODOS[mode].tit+': '+product.bands
.map(band=>'a partir de '+metrosCurto(band.from_metres)+' m: '+rs(band.unit_cents/100)).join(' · ')));
tabelaFaixas.replaceChildren(...linhas);
tabelaFaixas.hidden=!linhas.length;
}
window.dtfProducts=session.products;
if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha();
if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho();
if(typeof pintaTipoEnvio==='function')pintaTipoEnvio();
semPedidos=!Object.values(session.products).some(product=>product.enabled);
if(semPedidos)message('No momento não estamos recebendo pedidos pelo site.','warn');
}
if(typeof pintaPedido==='function')pintaPedido();
}).catch(()=>{});
window.dtfSessionReady=ready;
window.dtfApi=api;
@@ -95,6 +141,10 @@
if (className) el.className=className;
return el;
}
// "5" or "5,5": a band's metres as the customer reads them.
function metrosCurto(value){
return String(Number(value)).replace('.',',');
}
// What the customer is paying for, from the server's approval.
function pintaResumo(quote) {
const approved = quote ? quote.approved : null;
@@ -106,14 +156,31 @@
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)));
if(approved.coupon)
rows.push(linha('Cupom '+approved.coupon.code, '− '+rs(approved.coupon.discount_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 +203,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 +397,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,23 +416,41 @@
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.');
const content = {customer:{...cliente},items,freight:{service,postal_code:entrega.tipo==='retira'?'':entrega.cep}};
const cupom=cupomCode();
const content = {customer:{...cliente},items,freight:{service,postal_code:entrega.tipo==='retira'?'':entrega.cep},
...(cupom?{coupon:cupom}:{})};
const destination = destinoApi();
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 +488,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 +566,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);
}
@@ -666,6 +760,15 @@
window.addEventListener('dtf-page-changed',()=>{
if (naPagina()) refresh();
else if (!busy) { refreshVersion++; clearInterval(pixClock); message(''); actions.replaceChildren(); pintaResumo(null); }
if (!naPagina() && semPedidos) message('No momento não estamos recebendo pedidos pelo site.','warn');
});
// "Aplicar" sends the coupon with the cart: there is no public route to test
// a code, so the server's answer comes with the quote (front 8.3).
const aplicarCupom=document.getElementById('bCupom');
if(aplicarCupom)aplicarCupom.onclick=()=>window.dtfCheckout();
const campoCupom=document.getElementById('fCupom');
if(campoCupom)campoCupom.addEventListener('keydown',e=>{
if(e.key==='Enter'){e.preventDefault();window.dtfCheckout();}
});
refresh();
})();

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,10 +937,10 @@ 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>
<p class="cObs" id="cProxima"></p>
<div class="cTot"><span>Total</span><b id="cTotal">—</b></div>
<div id="qmsg" style="display:none"></div>
<div class="ciente" id="ciente">
@@ -947,6 +955,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 +979,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 +1036,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>
@@ -1075,13 +1089,34 @@ h2 em{font-style:normal;color:var(--laranja)}
</div>
</div>
<div class="cxE">
<h4>Cupom</h4>
<div class="campos">
<div class="cp larga">
<label for="fCupom">Código do cupom</label>
<div class="cepL">
<input id="fCupom" autocomplete="off" maxlength="30" placeholder="Ex.: REINA-2026">
<button type="button" id="bCupom">Aplicar</button>
</div>
</div>
</div>
</div>
<div class="cxE">
<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 +1161,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>
@@ -1134,6 +1169,7 @@ h2 em{font-style:normal;color:var(--laranja)}
<tr><td>Artes avulsas</td><td data-preco="avulsa">R$ 21,90</td><td data-preco="uv">R$ 89,90</td></tr>
</tbody>
</table>
<div class="nota2" id="tabelaFaixas" hidden></div>
<p class="nota2" id="tabelaManual">Arquivo em CDR, AI, PSD ou TIFF, que alguém abre na mão: + R$ 2,00 por metro.</p>
</div>
<div class="info2-vant">
@@ -1177,11 +1213,13 @@ 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>
<script src="/site-pdf.js"></script>
<script src="/site-quality.js"></script>
<script src="/packing.js"></script>
<script src="/site-packing.js"></script>
<script src="/site-cart.js"></script>
<script src="/site-flow.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

435
web/kanban-montador.js Normal file
View File

@@ -0,0 +1,435 @@
/* Kanban DTF: "Montar folha" (Fase 2, front 7). The stamps are the PNG files
in Estampas/ inside the folder chosen in Integrações; the sizes are the
table Gestão edits. The packing is the Site's own engine (web/packing.js).
Montar, which creates the card, is slice 2b. Uses the globals of kanban.js
and packing.js, loaded first. */
const MONTAR_CODE=/^[A-Za-z0-9_-]{1,40}$/;
// The Site's ruler (web/site-config.js): the same numbers, copied there too.
const MONTAR_DPI_REFUSE=96, MONTAR_DPI_WARN=200;
const MONTAR_FILM_CM=57, MONTAR_GAP_CM=0.5;
const MONTAR={sizes:[],lines:[],seq:0,preview:null,timer:null,dirty:false,token:0,
layout:null,layoutTimer:null,layoutToken:0,layoutPending:false,creating:false,requestKey:null};
const montarFolderReady=()=>!!FOLDER.handle&&!!FOLDER.granted;
const montarDpi=found=>found.width/(found.widthCm/2.54);
const montarHeight=found=>found.widthCm*(found.height/found.width);
const montarSelected=()=>MONTAR.sizes.find(size=>size.letter===$('montar-size').value)||null;
// Without the folder there is no Estampas/ to read: only the size table works.
function montarPaintFolder(){
const ok=montarFolderReady();
$('montar-nofolder').hidden=ok;
$('montar-setup').querySelector('.montar-add').hidden=!ok;
$('montar-preview').hidden=!ok;
$('montar-sheet').hidden=!ok;
$('montar-folder').textContent=ok?'Pasta “'+FOLDER.handle.name+'” · Estampas/':'';
if(!ok){montarDropPreview();$('montar-preview').replaceChildren();}
}
function montarFolderError(error){
if(error&&['NotAllowedError','SecurityError'].includes(error.name)){
say('Para ler as estampas, escolha a pasta dos pedidos em Integrações neste computador.',true);
return true;
}
return false;
}
// <code>-<SIZE>.png wins over <code>.png; only PNG.
async function montarRead(code,size){
const dir=await FOLDER.handle.getDirectoryHandle('Estampas',{create:true});
for(const name of [code+'-'+size.letter+'.png',code+'.png']){
let handle;
try{handle=await dir.getFileHandle(name);}
catch(e){if(e.name==='NotFoundError')continue;throw e;}
const file=await handle.getFile(),url=URL.createObjectURL(file);
try{const dim=await montarPicture(url);return {code,letter:size.letter,widthCm:Number(size.width_cm),file,name,url,width:dim.width,height:dim.height};}
catch(e){URL.revokeObjectURL(url);throw e;}
}
return null;
}
function montarPicture(url){
return new Promise((ok,fail)=>{
const img=new Image();
img.onload=()=>ok({width:img.naturalWidth,height:img.naturalHeight});
img.onerror=()=>fail(new Error('A estampa não pôde ser lida.'));
img.src=url;
});
}
function montarDropPreview(){
if(MONTAR.preview)URL.revokeObjectURL(MONTAR.preview.url);
MONTAR.preview=null;
}
function montarPaintPreview(found){
montarDropPreview();
MONTAR.preview=found;
const words=node('span',undefined,'montar-stampinfo');
words.append(node('b',found.code),
node('span',cm(found.widthCm)+' cm de largura · '+cm(montarHeight(found))+' cm de altura · '+Math.floor(montarDpi(found))+' DPI'));
const img=node('img');img.src=found.url;img.alt='Estampa '+found.code;
const wrap=node('div',undefined,'montar-stamp');wrap.append(img,words);
$('montar-preview').replaceChildren(wrap);
}
function montarPaintNotFound(){
montarDropPreview();
$('montar-preview').replaceChildren(node('p','Código não existe em Estampas/.','montar-missing'));
}
function montarPaintHint(){
montarDropPreview();
$('montar-preview').replaceChildren(node('p','Digite o código e escolha o tamanho para ver a estampa.','montar-hint'));
}
async function montarPreview(){
const token=++MONTAR.token;
const code=$('montar-code').value.trim(),size=montarSelected();
if(!montarFolderReady())return;
if(!code){montarPaintHint();return;}
if(!MONTAR_CODE.test(code)||!size){montarDropPreview();$('montar-preview').replaceChildren();return;}
let found;
try{found=await montarRead(code,size);}
catch(e){if(token===MONTAR.token&&!montarFolderError(e))say(e.message,true);return;}
if(token!==MONTAR.token){if(found)URL.revokeObjectURL(found.url);return;}
if(found)montarPaintPreview(found);else montarPaintNotFound();
}
function montarQueuePreview(){
clearTimeout(MONTAR.timer);
MONTAR.timer=setTimeout(()=>montarPreview().catch(e=>say(e.message,true)),250);
}
function montarEstimate(){
if(!MONTAR.lines.length)return 0;
let total=0;
for(const line of MONTAR.lines){
const perRow=Math.max(1,Math.floor((MONTAR_FILM_CM-MONTAR_GAP_CM)/(line.widthCm+MONTAR_GAP_CM)));
const rows=Math.ceil(line.qty/perRow);
total+=rows*(line.heightCm+MONTAR_GAP_CM);
}
return (MONTAR_GAP_CM+total)/100;
}
function montarPaintTotals(){
const done=MONTAR.layout&&!MONTAR.layoutPending;
$('montar-total').textContent=done
? 'Montagem: '+metres(MONTAR.layout.altura/100)
: 'Estimativa: '+metres(montarEstimate())+(MONTAR.layoutPending?' · montando…':'');
$('montar-count').textContent=MONTAR.lines.length?plural(MONTAR.lines.length,'estampa','estampas'):'';
$('montar-clear').disabled=!MONTAR.lines.length;
$('montar-warning').hidden=!(MONTAR.lines.length>20||MONTAR.lines.some(line=>line.qty>200));
montarPaintActions();
}
// The line's image, loaded once and kept for the packing and the preview.
function montarStampImage(url){
const img=new Image();
const loading=new Promise(ok=>{img.onload=()=>ok(img);img.onerror=()=>ok(null);});
img.src=url;
return {img,loading};
}
// Every list change shows the estimate at once and schedules the real packing,
// 300 ms later; a run that finishes after a newer change is thrown away.
function montarChanged(){
MONTAR.layoutToken+=1;
MONTAR.layout=null;
MONTAR.layoutPending=true;
MONTAR.requestKey=null;
montarPaintLines();
if(!MONTAR.lines.length)montarDrawPreview(null);
clearTimeout(MONTAR.layoutTimer);
MONTAR.layoutTimer=setTimeout(()=>montarLayout(MONTAR.layoutToken).catch(e=>say(e.message,true)),300);
}
async function montarLayout(token){
if(token!==MONTAR.layoutToken)return;
const lines=[...MONTAR.lines];
if(!lines.length){MONTAR.layout=null;MONTAR.layoutPending=false;montarPaintTotals();montarDrawPreview(null);return;}
const images=await Promise.all(lines.map(line=>line.loading));
if(token!==MONTAR.layoutToken)return;
if(images.some(image=>!image)){
MONTAR.layoutPending=false;montarPaintTotals();
say('A estampa não pôde ser lida.',true);return;
}
const cargas=lines.flatMap((line,sourceIndex)=>Array.from({length:line.qty},(_,copyIndex)=>({
a:{sourceIndex,giro:0,esp:false},img:line.img,copyIndex,w:line.widthCm,h:line.heightCm,travado:false})));
let enc;
try{enc=encaixar(cargas,MONTAR_FILM_CM);}
catch(e){
if(token!==MONTAR.layoutToken)return;
MONTAR.layoutPending=false;montarPaintTotals();say(e.message,true);return;
}
if(token!==MONTAR.layoutToken)return;
MONTAR.layout={token,altura:enc.altura,pos:enc.pos};
MONTAR.layoutPending=false;
montarPaintTotals();
montarDrawPreview(MONTAR.layout);
}
// The sheet's preview: 57 cm across the panel, white film and the outline.
function montarDrawPreview(layout){
const box=$('montar-layout'),canvas=$('montar-canvas');
if(!layout){box.hidden=true;return;}
box.hidden=false;
const width=box.clientWidth-24; // the box's padding
if(width<60)return;
const px=width/MONTAR_FILM_CM;
const height=Math.max(20,layout.altura*px);
const dpr=Math.min(2,window.devicePixelRatio||1);
canvas.width=Math.round(width*dpr);canvas.height=Math.round(height*dpr);
canvas.style.width=width+'px';canvas.style.height=height+'px';
const ctx=canvas.getContext('2d');
ctx.setTransform(dpr,0,0,dpr,0,0);
ctx.fillStyle='#fff';ctx.fillRect(0,0,width,height);
ctx.strokeStyle='#B4BAC5';ctx.lineWidth=1;
ctx.strokeRect(.5,.5,width-1,height-1);
for(const p of layout.pos){
const c=p.ref;
const giro=(p.rot===90?90:0)+(c.a&&c.a.giro?90:0);
ctx.save();
ctx.translate((p.x+p.w/2)*px,(p.y+p.h/2)*px);
ctx.rotate(giro*Math.PI/180);
if(c.a&&c.a.esp)ctx.scale(-1,1);
const dw=((giro%180===90)?p.h:p.w)*px, dh=((giro%180===90)?p.w:p.h)*px;
if(c.img)ctx.drawImage(c.img,-dw/2,-dh/2,dw,dh);
else{ctx.fillStyle='#E7E7E3';ctx.fillRect(-dw/2,-dh/2,dw,dh);}
ctx.restore();
}
}
// ---- Criar o pedido -------------------------------------------------------
// The typed customer, as the Site's own Customer model validates it.
const MONTAR_CUSTOMER=['montar-name','montar-doc','montar-zap','montar-mail'];
function montarCustomer(){
return {name:$('montar-name').value.trim(),cnpj:$('montar-doc').value.trim(),
zap:$('montar-zap').value.trim(),mail:$('montar-mail').value.trim()};
}
const montarCustomerFilled=()=>MONTAR_CUSTOMER.every(id=>$(id).value.trim());
function montarClearCustomer(){
for(const id of MONTAR_CUSTOMER)$(id).value='';
MONTAR.requestKey=null;
}
// Montar is the real thing now: a sheet, its layout and the customer.
function montarPaintActions(){
const build=$('montar-build');
const ready=!!(MONTAR.lines.length&&MONTAR.layout&&!MONTAR.layoutPending&&
montarCustomerFilled()&&!MONTAR.creating);
build.disabled=!ready;
build.title=ready?'':(MONTAR.lines.length?'Aguarde a montagem e preencha o cliente.':'Monte a folha primeiro.');
}
// The Site's grade for loose art (web/site-quality.js): each stamp's DPI over
// the ideal 200, from 6 to 100; the item's is the average of its stamps'.
const montarGrade=dpi=>Math.max(6,Math.min(100,Math.round(dpi/200*100)));
function montarItem(sources){
const cargas=[];
sources.forEach((source,sourceIndex)=>{
for(let copyIndex=0;copyIndex<source.copies;copyIndex++)
cargas.push({a:{sourceIndex,giro:0,esp:false},img:source.line.img,copyIndex,
w:source.line.widthCm,h:source.line.heightCm,travado:false});
});
const enc=encaixar(cargas,MONTAR_FILM_CM);
const height=+enc.altura.toFixed(4);
const grades=sources.map(source=>montarGrade(source.line.dpi));
const warning=sources.some(source=>source.line.dpi<MONTAR_DPI_WARN);
return {mode:'avulsa',metres:+(height/100).toFixed(4),
grade:Math.round(grades.reduce((sum,n)=>sum+n,0)/grades.length),
uploads:sources.map(source=>source.uploadId),
production:{version:3,film_width_cm:MONTAR_FILM_CM,height_cm:height,
sources:sources.map(source=>({upload_id:source.uploadId,kind:'artwork',
width_cm:source.line.widthCm,length_cm:+source.line.heightCm.toFixed(4),
copies:source.copies,rotation_degrees:0,mirrored:false,measurement:'file'})),
placements:placementsDe(enc.pos)},
quality_status:warning?'warning':'ok',quality_acknowledged:warning,residue_accepted:0};
}
// 20 sources and 4000 copies per item; a stamp above 200 copies becomes
// several sources of the same upload, 200 each; items in list order.
function montarItems(lines,uploads){
const pool=[];
for(const line of lines){
const uploadId=uploads.get(line.id);
for(let left=line.qty;left>0;left-=200)
pool.push({line,uploadId,copies:Math.min(200,left)});
}
const groups=[];let current=null;
for(const source of pool){
if(!current||current.sources.length>=20||current.copies+source.copies>4000){
current={sources:[],copies:0};groups.push(current);
}
current.sources.push(source);current.copies+=source.copies;
}
return groups.map(group=>montarItem(group.sources));
}
async function montarCreate(){
if(MONTAR.creating)return;
const customer=montarCustomer();
if(!montarCustomerFilled())return say('Preencha os dados do cliente.',true);
if(!MONTAR.lines.length)return say('Monte a folha primeiro.',true);
if(!MONTAR.layout||MONTAR.layoutPending)return say('A montagem ainda está sendo calculada.',true);
const lines=[...MONTAR.lines];
if(!await ask('Criar pedido','Criar o pedido com '+plural(lines.reduce((t,line)=>t+line.qty,0),'estampa','estampas')+
', '+metres(MONTAR.layout.altura/100)+', para '+customer.name+'?','Criar pedido'))return;
MONTAR.creating=true;montarPaintActions();
try{
const uploads=new Map();
for(let index=0;index<lines.length;index++){
const line=lines[index];
say('Enviando estampas '+(index+1)+' de '+lines.length+'…');
const id=await dtfUpload(line.file,{api,startPath:'/montador/uploads',
scope:'montador:'+line.code+'-'+line.letter,progress:say});
uploads.set(line.id,id);
}
say('Criando o pedido…');
if(!MONTAR.requestKey)MONTAR.requestKey=crypto.randomUUID();
const order=await api('/montador/orders',{request_key:MONTAR.requestKey,
customer,items:montarItems(lines,uploads)});
MONTAR.requestKey=null;
montarClear();
montarClearCustomer();
say('Pedido #'+order.number+' criado em Arte recebida.',false,10000);
load(true).catch(()=>{});
}catch(e){say(e.message,true);}
finally{MONTAR.creating=false;montarPaintActions();}
}
function montarLine(line){
const row=node('div',undefined,'montar-line');
const img=node('img',undefined,'montar-thumb');img.src=line.url;img.alt='';
const words=node('span',undefined,'montar-linemeta');
words.append(node('b',line.code),node('span',line.letter+' · '+cm(line.widthCm)+' cm'));
const qty=node('input',undefined,'montar-qty');qty.type='number';qty.min='1';qty.max='9999';qty.step='1';
qty.value=String(line.qty);qty.setAttribute('aria-label','Quantidade de '+line.code+' '+line.letter);
qty.onchange=()=>{
const value=Math.round(Number(qty.value));
if(!Number.isInteger(value)||value<1||value>9999){qty.value=String(line.qty);return;}
line.qty=value;qty.value=String(value);montarChanged();
};
const dpi=node('span',undefined,'montar-dpi');
if(line.dpi<MONTAR_DPI_WARN)dpi.append(badge(Math.floor(line.dpi)+' DPI','warn','Abaixo de '+MONTAR_DPI_WARN+' DPI.'));
row.append(img,words,qty,dpi,node('span',cm(line.heightCm)+' cm','montar-height'),
iconButton(IC.close,'Remover '+line.code+' '+line.letter,()=>montarRemoveLine(line)));
return row;
}
function montarPaintLines(){
const box=$('montar-lines');
box.replaceChildren(...(MONTAR.lines.length?MONTAR.lines.map(montarLine)
:[emptyState(IC.box,'Nenhuma estampa na folha','Digite o código, escolha o tamanho e Adicionar.')]));
montarPaintTotals();
}
function montarRemoveLine(line){
URL.revokeObjectURL(line.url);
MONTAR.lines=MONTAR.lines.filter(other=>other!==line);
montarChanged();
}
function montarClear(){
for(const line of MONTAR.lines)URL.revokeObjectURL(line.url);
MONTAR.lines=[];
montarChanged();
}
async function montarAdd(){
const code=$('montar-code').value.trim(),size=montarSelected();
if(!MONTAR_CODE.test(code))return say('Código inválido: use letras, números, hífen ou sublinhado, até 40.',true);
if(!size)return say('Nenhum tamanho na tabela. Peça à Gestão para cadastrar.',true);
const qty=Number($('montar-qty').value);
if(!Number.isInteger(qty)||qty<1||qty>9999)return say('A quantidade vai de 1 a 9999.',true);
if(!montarFolderReady())return;
let found;
try{found=await montarRead(code,size);}
catch(e){if(!montarFolderError(e))say(e.message,true);return;}
if(!found){montarPaintNotFound();return say('Código não existe em Estampas/.',true);}
montarPaintPreview(found);
if(found.widthCm>56)return say('A estampa tem '+cm(found.widthCm)+' cm de largura: o máximo é 56 cm.',true);
const dpi=montarDpi(found);
if(dpi<MONTAR_DPI_REFUSE)return say('A estampa tem só '+Math.floor(dpi)+' DPI em '+size.letter+': pequena demais.',true);
const existing=MONTAR.lines.find(line=>line.code===code&&line.letter===size.letter);
if(existing){existing.qty=Math.min(9999,existing.qty+qty);montarChanged();return;}
const url=URL.createObjectURL(found.file),picture=montarStampImage(url);
MONTAR.lines.push({id:++MONTAR.seq,code,letter:size.letter,widthCm:found.widthCm,qty,
heightCm:montarHeight(found),dpi,url,img:picture.img,loading:picture.loading,file:found.file});
montarChanged();
}
function montarPaintSelect(){
const select=$('montar-size'),current=select.value;
select.replaceChildren(...MONTAR.sizes.map(size=>{
const option=node('option',size.letter+' · '+cm(size.width_cm)+' cm');option.value=size.letter;return option;
}));
select.disabled=!MONTAR.sizes.length;
select.value=MONTAR.sizes.some(size=>size.letter===current)?current:(MONTAR.sizes[0]?.letter||'');
}
// A row of the table: the letter and its width in centimetres.
function montarSizeRow(size){
const row=node('div',undefined,'montar-size-row');
const letter=node('input',undefined,'montar-letter');letter.value=size?.letter||'';letter.maxLength=2;
letter.autocomplete='off';letter.setAttribute('aria-label','Letra do tamanho');
letter.oninput=()=>{letter.value=letter.value.toUpperCase().replace(/[^A-Z]/g,'');MONTAR.dirty=true;};
const width=node('input',undefined,'montar-width');width.type='number';width.min='0.01';width.max='56';width.step='0.01';
width.value=size?Number(size.width_cm):'';width.setAttribute('aria-label','Largura em centímetros');
width.oninput=()=>{MONTAR.dirty=true;};
const remove=iconButton(IC.close,'Remover tamanho',()=>{row.remove();MONTAR.dirty=true;});
row.append(letter,width,remove);
return row;
}
function montarPaintSizeEditor(){
const panel=$('montar-sizes-panel');
if(!may('manage')){panel.hidden=true;return;}
panel.hidden=false;
const head=node('div',undefined,'montar-size-head');
head.append(node('span','Letra'),node('span','Largura (cm)'),node('span'));
$('montar-sizes').replaceChildren(head,...MONTAR.sizes.map(montarSizeRow));
}
async function montarSaveSizes(){
const rows=[...$('montar-sizes').querySelectorAll('.montar-size-row')];
const sizes=[],seen=new Set();
for(const row of rows){
const letter=row.querySelector('.montar-letter').value.trim().toUpperCase();
const width=Number(row.querySelector('.montar-width').value);
if(!/^[A-Z]{1,2}$/.test(letter))return say('Cada tamanho precisa de uma letra de A a ZZ.',true);
if(seen.has(letter))return say('A letra '+letter+' aparece mais de uma vez.',true);
if(!(width>0&&width<=56))return say('A largura de '+letter+' vai de 0,01 a 56 cm.',true);
seen.add(letter);sizes.push({letter,width_cm:Number(width.toFixed(2))});
}
if(!sizes.length)return say('A tabela precisa de pelo menos um tamanho.',true);
await api('/stamp-sizes',{sizes});
MONTAR.dirty=false;
say('Tamanhos salvos.');
await montarLoadSizes(true);
montarQueuePreview();
}
async function montarLoadSizes(repaint){
MONTAR.sizes=(await api('/stamp-sizes')).sizes||[];
montarPaintSelect();
if(repaint||!MONTAR.dirty)montarPaintSizeEditor();
}
async function loadMontador(){
montarPaintFolder();
try{await montarLoadSizes(false);}
catch(e){say(e.message,true);return;}
if(montarFolderReady()){
if($('montar-code').value.trim()){if(!MONTAR.preview)montarQueuePreview();}
else montarPaintHint();
}
montarPaintLines();
if(MONTAR.layout)montarDrawPreview(MONTAR.layout);
}
// 2b splits an order that passes these limits into more than one sheet; from
// now on it only warns, it does not block.
const montarWarning=node('p','O pedido será dividido em mais de uma folha.','montar-warn');
montarWarning.id='montar-warning';montarWarning.hidden=true;
$('montar-sheet').insertBefore(montarWarning,$('montar-lines'));
let montarResize=null;
addEventListener('resize',()=>{
clearTimeout(montarResize);
montarResize=setTimeout(()=>{if(MONTAR.layout)montarDrawPreview(MONTAR.layout);},200);
});
$('montar-code').addEventListener('input',montarQueuePreview);
$('montar-size').addEventListener('change',()=>montarPreview().catch(e=>say(e.message,true)));
$('montar-qty').addEventListener('keydown',event=>{
if(event.key==='Enter'){event.preventDefault();$('montar-add').click();}
});
$('montar-add').onclick=async()=>{
$('montar-add').disabled=true;
try{await montarAdd();}catch(e){say(e.message,true);}finally{$('montar-add').disabled=false;}
};
$('montar-clear').onclick=()=>montarClear();
$('montar-build').onclick=()=>montarCreate();
for(const id of MONTAR_CUSTOMER)$(id).addEventListener('input',()=>{MONTAR.requestKey=null;montarPaintActions();});
$('montar-size-add').onclick=()=>{MONTAR.dirty=true;$('montar-sizes').append(montarSizeRow(null));};
$('montar-size-save').onclick=async()=>{
$('montar-size-save').disabled=true;
try{await montarSaveSizes();}catch(e){say(e.message,true);}finally{$('montar-size-save').disabled=false;}
};

348
web/kanban-site.js Normal file
View File

@@ -0,0 +1,348 @@
/* Kanban DTF: the Site tab. What the Site sells and at what price, edited by
Gestão and the administrators (Fase 2, front 8). Loaded after kanban.js,
which defines api, may, money, when, say, node and button.
A price is history: one that has started is never changed or deleted, so
only a scheduled (future) price may be cancelled. */
const SITE_UNIT_LABEL={metro:' /m',pedido:' por pedido'};
// Reais with a comma, as the Site shows them: "19,90" is 1990 cents.
function moneyInputCents(value){
let text=String(value||'').trim().replace(/R\$/g,'').replace(/\s/g,'');
if(!text)return null;
if(text.includes(','))text=text.replace(/\./g,'').replace(',','.');
const number=Number(text);
if(!Number.isFinite(number)||number<0)return null;
return Math.round(number*100);
}
// A price that already started is refused by the server (409).
const cancelScheduledPrice=id=>api('/site/prices/'+id+'/cancel',{});
// "5" or "5,5": a band's start in metres, as the table reads it.
function bandMetres(value){return String(Number(value)).replace('.',',');}
function bandsText(bands){
return (bands||[]).map(band=>' · '+bandMetres(band.from_metres)+' m: '+money(band.unit_cents)).join('');
}
function siteProductRow(product){
const tr=node('tr');
const name=node('td');name.append(node('b',product.title));
const price=node('td',money(product.unit_cents)+SITE_UNIT_LABEL[product.unit],'nowrap');
if(product.fallback)price.append(node('span',' · padrão','muted'));
const state=node('td');
const label=node('label',undefined,'siteSwitch');
const input=node('input');input.type='checkbox';input.checked=product.enabled;
const word=node('span',product.enabled?'Ligado':'Desligado');
input.onchange=async()=>{
input.disabled=true;
try{
await api('/site/products/'+product.id,{enabled:input.checked});
word.textContent=input.checked?'Ligado':'Desligado';
say(product.title+(input.checked?' ligado.':' desligado.'));
await loadSiteAdmin();
}catch(error){input.checked=!input.checked;say(error.message,true);}
finally{input.disabled=false;}
};
label.append(input,word);
state.append(label);
tr.append(name,state,price);
return tr;
}
function sitePriceBlock(product){
const block=node('div',undefined,'sitePriceBlock');
const heading=node('h3',product.title);
heading.append(node('span',' · '+product.unit,'muted'));
// Novo preço: reais with a comma; empty "A partir de" means now.
const form=node('div',undefined,'sitePriceForm');
const priceLabel=node('label');priceLabel.append(node('span','Novo preço'));
const price=node('input');price.type='text';price.inputMode='decimal';price.className='siteMoney';
price.placeholder=(product.unit_cents/100).toFixed(2).replace('.',',');
price.setAttribute('aria-label','Novo preço de '+product.title);
priceLabel.append(price);
const startsLabel=node('label');startsLabel.append(node('span','A partir de'));
const starts=node('input');starts.type='datetime-local';
starts.setAttribute('aria-label','Quando o novo preço de '+product.title+' começa');
startsLabel.append(starts);
// Faixas progressivas (front 8.2): a nova tabela começa vazia; as faixas
// viajam com este preço. O tratamento é um valor por pedido, sem faixas.
const bandRows=node('div',undefined,'siteBandRows');
const addBand=node('button','Adicionar faixa','btn ghost');addBand.type='button';
const paintAdd=()=>{addBand.disabled=bandRows.children.length>=5;};
const bandRow=()=>{
const row=node('div',undefined,'siteBandRow');
const fromLabel=node('label');fromLabel.append(node('span','A partir de (m)'));
const from=node('input');from.type='text';from.inputMode='decimal';from.className='siteBandFrom';
from.setAttribute('aria-label','Metragem da faixa de '+product.title);
fromLabel.append(from);
const priceLabel=node('label');priceLabel.append(node('span','R$ por metro'));
const bandPrice=node('input');bandPrice.type='text';bandPrice.inputMode='decimal';bandPrice.className='siteBandPrice';
bandPrice.setAttribute('aria-label','Preço da faixa de '+product.title);
priceLabel.append(bandPrice);
const remove=button('Remover',()=>{row.remove();paintAdd();},'btn ghost');
row.append(fromLabel,priceLabel,remove);
return row;
};
addBand.onclick=()=>{if(bandRows.children.length>=5)return;bandRows.append(bandRow());paintAdd();};
const bands=node('div',undefined,'siteBands');
const bandsHead=node('div',undefined,'siteBandsHead');
bandsHead.append(node('span','Faixas'),addBand);
bands.append(bandsHead,bandRows);
const formBands=()=>[...bandRows.children].map(row=>{
const from=Number(row.querySelector('.siteBandFrom').value.replace(',','.'));
const unit=moneyInputCents(row.querySelector('.siteBandPrice').value);
if(!Number.isFinite(from)||from<=0||unit===null||unit<=0)
throw new Error('Confira as faixas: metragem e preço maiores que zero.');
return {from_metres:String(from),unit_cents:unit};
});
const save=button('Salvar',async()=>{
const cents=moneyInputCents(price.value);
if(cents===null)throw new Error('Informe o preço em reais, como 19,90.');
const whenDate=starts.value?new Date(starts.value):null;
if(whenDate&&Number.isNaN(whenDate.getTime()))throw new Error('Data inválida.');
await api('/site/products/'+product.id+'/prices',
{unit_cents:cents,starts_at:whenDate?whenDate.toISOString():null,
bands:product.id==='tratamento'?[]:formBands()});
say(whenDate?'Preço salvo para '+when(whenDate)+'.':'Preço salvo. Vale a partir de agora.');
await loadSiteAdmin();
},'btn pri');
form.append(priceLabel,startsLabel,save);
if(product.id!=='tratamento')form.append(bands);
const scheduled=node('div',undefined,'siteScheduled');
if(product.scheduled.length){
for(const row of product.scheduled){
const line=node('div',undefined,'siteScheduledRow');
line.append(node('span',money(row.unit_cents)+SITE_UNIT_LABEL[product.unit]+bandsText(row.bands)+
' a partir de '+when(row.starts_at)));
line.append(button('Cancelar',async()=>{
await cancelScheduledPrice(row.id);
say('Preço agendado cancelado.');
await loadSiteAdmin();
},'btn ghost'));
scheduled.append(line);
}
}else scheduled.append(node('span','Nenhum preço agendado.','muted'));
const table=node('table',undefined,'table');
const head=node('thead');const headRow=node('tr');
for(const title of ['Valor','A partir de','Quem','Quando'])headRow.append(node('th',title));
head.append(headRow);
const body=node('tbody');
for(const row of product.history){
const tr=node('tr');
tr.append(node('td',money(row.unit_cents)+bandsText(row.bands),'nowrap'),node('td',when(row.starts_at),'nowrap'),
node('td',row.created_by),node('td',when(row.created_at),'nowrap'));
body.append(tr);
}
if(!product.history.length){
const tr=node('tr');const td=node('td','Nenhum preço registrado: vale o preço padrão.','muted');
td.colSpan=4;tr.append(td);body.append(tr);
}
table.append(head,body);
const history=node('div',undefined,'siteHistory');
history.append(node('h4','Histórico'),table);
block.append(heading,form,scheduled,history);
return block;
}
// ── Cupons (front 8.3) ──────────────────────────────────────────────────────
// A "ficha" of the date in the browser's timezone, for datetime-local inputs.
function couponDate(iso){
const d=new Date(iso),p=n=>String(n).padStart(2,'0');
return d.getFullYear()+'-'+p(d.getMonth()+1)+'-'+p(d.getDate())+'T'+p(d.getHours())+':'+p(d.getMinutes());
}
function ensureCouponsPanel(){
let panel=$('site-coupons-panel');
if(panel)return panel;
panel=node('section',undefined,'panel clip');panel.id='site-coupons-panel';
const head=node('div',undefined,'phead');
head.append(node('h2','Cupons'),button('Novo cupom',()=>couponDialog(null),'btn right'));
panel.append(head,node('p','Cupons de desconto do checkout: validade, mínimo de metros, limite de usos e produto. Um cupom por pedido.','phint'));
const list=node('div',undefined,'siteCouponList');list.id='site-coupons';panel.append(list);
const videos=$('site-videos-panel');
if(videos)videos.before(panel); else $('tab-site').append(panel);
return panel;
}
function couponRow(coupon){
const expired=coupon.valid_until && new Date(coupon.valid_until)<=new Date();
const status=coupon.paused?['Pausado','warn']:expired?['Expirado','']:['Ativo','ok'];
const row=node('div',undefined,'siteCouponRow');
const top=node('div',undefined,'siteCouponTop');
top.append(node('b',coupon.code),badge(status[0],status[1]),
node('span',coupon.kind==='percent'?coupon.value+'%':money(coupon.value)+'/m','siteCouponOffer'));
const meta=node('div',undefined,'siteCouponMeta');
meta.append(node('span','Validade: de '+when(coupon.valid_from)+
(coupon.valid_until?' até '+when(coupon.valid_until):' sem fim')),
node('span','Produto: '+(coupon.product?SHORT[coupon.product]:'todos')),
node('span','Usos: '+coupon.uses+(coupon.max_uses?' de '+coupon.max_uses:'')));
const actions=node('div',undefined,'siteCouponActions');
actions.append(button(coupon.paused?'Retomar':'Pausar',async()=>{
await api('/site/coupons/'+coupon.id,{paused:!coupon.paused});
say('Cupom '+coupon.code+(coupon.paused?' retomado.':' pausado.'));
await loadSiteCoupons();
},'btn'),
button('Editar',()=>couponDialog(coupon),'btn ghost'),
button('Apagar',async()=>{
if(!(await ask('Apagar cupom',
'O cupom '+coupon.code+' deixa de valer. Os pedidos que já o usaram continuam no histórico.',
'Apagar',{tone:'red'})))return;
await api('/site/coupons/'+coupon.id+'/delete',{});
say('Cupom '+coupon.code+' apagado.');
await loadSiteCoupons();
},'btn quiet'));
row.append(top,meta,actions);
if(coupon.note)row.append(node('p',coupon.note,'siteCouponNote'));
return row;
}
function couponDialog(coupon){
const editing=!!coupon;
const code=node('input');code.maxLength=30;code.value=coupon?coupon.code:'';code.placeholder='Ex.: REINA-2026';
if(editing)code.disabled=true;
const kind=node('select');
for(const [value,label] of [['percent','Porcentagem (%)'],['per_metre','Por metro (R$)']]){
const option=node('option',label);option.value=value;kind.append(option);
}
kind.value=coupon?coupon.kind:'percent';
const pct=node('input');pct.type='number';pct.min='1';pct.max='90';pct.step='1';
pct.value=coupon&&coupon.kind==='percent'?String(coupon.value):'';
const price=node('input');price.type='text';price.inputMode='decimal';price.placeholder='2,00';
if(coupon&&coupon.kind==='per_metre')price.value=(coupon.value/100).toFixed(2).replace('.',',');
const from=node('input');from.type='datetime-local';from.value=coupon?couponDate(coupon.valid_from):'';
const until=node('input');until.type='datetime-local';
until.value=coupon&&coupon.valid_until?couponDate(coupon.valid_until):'';
const min=node('input');min.type='text';min.inputMode='decimal';min.placeholder='5';
if(coupon&&coupon.min_metres!=null)min.value=String(coupon.min_metres).replace('.',',');
const max=node('input');max.type='number';max.min='1';max.step='1';
max.value=coupon&&coupon.max_uses?String(coupon.max_uses):'';
const per=node('input');per.type='number';per.min='1';per.step='1';
per.value=coupon&&coupon.max_uses_per_customer?String(coupon.max_uses_per_customer):'';
const product=node('select');
for(const [value,label] of [['','Todos os produtos'],...Object.entries(SHORT)]){
const option=node('option',label);option.value=value;product.append(option);
}
product.value=coupon?coupon.product||'':'';
const note=node('textarea');note.maxLength=1000;note.value=coupon?coupon.note:'';
const pctField=field('Desconto (%)',pct,'De 1 a 90.');
const priceField=field('Desconto por metro (R$)',price,'Valor em reais por metro, como 2,00.');
const paint=()=>{pctField.hidden=kind.value!=='percent';priceField.hidden=kind.value!=='per_metre';};
kind.onchange=paint;paint();
const fields=[
field('Código',code,editing?'O código não muda depois de criado.':'De 3 a 30 letras, números ou hífens.'),
field('Tipo de desconto',kind),
pctField,priceField,
field('Válido a partir de',from,'Vazio: agora.'),
field('Válido até',until,'Vazio: sem fim.'),
field('Mínimo de metros',min,'Vazio: sem mínimo. Conta só os metros dos itens do produto.'),
field('Limite de usos',max,'Vazio: sem limite.'),
field('Limite por cliente',per,'Vazio: sem limite.'),
field('Produto',product,'Todos os produtos, ou só um.'),
field('Observação',note,'Aparece só no Kanban.'),
];
formDialog(editing?'Editar cupom':'Novo cupom',{width:640,fields,label:'Salvar cupom',onsave:async()=>{
const rawMin=min.value.trim().replace(',','.');
const payload={
kind:kind.value,
value:kind.value==='percent'?Number(pct.value):moneyInputCents(price.value),
valid_from:from.value?new Date(from.value).toISOString():null,
valid_until:until.value?new Date(until.value).toISOString():null,
min_metres:rawMin||null,
max_uses:max.value.trim()?Number(max.value):null,
max_uses_per_customer:per.value.trim()?Number(per.value):null,
product:product.value||null,
note:note.value.trim(),
};
if(kind.value==='percent'&&(!Number.isInteger(payload.value)||payload.value<1||payload.value>90))
throw new Error('A porcentagem precisa ser de 1 a 90.');
if(kind.value==='per_metre'&&(payload.value===null||payload.value<=0))
throw new Error('Informe o desconto por metro em reais, como 2,00.');
if(rawMin&&!/^\d+([.,]\d)?$/.test(rawMin))
throw new Error('O mínimo de metros usa no máximo uma casa decimal.');
if(payload.min_metres!==null&&(!Number.isFinite(Number(payload.min_metres))||Number(payload.min_metres)<=0))
throw new Error('O mínimo de metros precisa ser maior que zero.');
if(payload.max_uses!==null&&(!Number.isInteger(payload.max_uses)||payload.max_uses<=0))
throw new Error('O limite de usos precisa ser um número inteiro maior que zero.');
if(payload.max_uses_per_customer!==null&&
(!Number.isInteger(payload.max_uses_per_customer)||payload.max_uses_per_customer<=0))
throw new Error('O limite por cliente precisa ser um número inteiro maior que zero.');
if(editing){
await api('/site/coupons/'+coupon.id,payload);
}else{
const clean=code.value.trim().toUpperCase();
if(!/^[A-Z0-9-]{3,30}$/.test(clean))
throw new Error('O código precisa ter de 3 a 30 letras, números ou hífens.');
await api('/site/coupons',{code:clean,...payload});
}
say(editing?'Cupom salvo.':'Cupom criado.');
await loadSiteCoupons();
}});
}
async function loadSiteCoupons(){
if(!may('manage'))return;
ensureCouponsPanel();
const data=await api('/site/coupons');
const host=$('site-coupons');
host.replaceChildren(...(data.coupons.length?data.coupons.map(couponRow)
:[node('p','Nenhum cupom criado ainda.','empty')]));
}
async function loadSiteAdmin(){
if(!may('manage'))return;
const data=await api('/site/products');
$('site-products').replaceChildren(...data.products.map(siteProductRow));
$('site-prices').replaceChildren(...data.products.map(sitePriceBlock));
await loadSiteCoupons();
await loadSiteVideos();
}
async function loadSiteVideos(){
const host=$('site-videos-list'),panel=$('site-videos-panel');
panel.hidden=!may('manage');
if(panel.hidden)return;
const data=await api('/site-videos');
host.replaceChildren(...data.videos.map(video=>{
const row=node('div',undefined,'siteVideoRow');
const heading=node('div',undefined,'siteVideoHeading');
heading.append(node('b',video.title),node('span',video.enabled?'Publicado':'Rascunho','pill'+(video.enabled?' ok':'')));
const videoInput=node('input');videoInput.type='file';videoInput.accept='.mp4,.webm,video/mp4,video/webm';
const captionsInput=node('input');captionsInput.type='file';captionsInput.accept='.vtt,text/vtt';
const videoLabel=node('label',undefined,'siteVideoField');
videoLabel.append(node('span','Vídeo · '+(video.video_name||'nenhum arquivo')),videoInput);
const captionsLabel=node('label',undefined,'siteVideoField');
captionsLabel.append(node('span','Legenda (opcional) · '+(video.captions_name||'nenhuma legenda')),captionsInput);
const product=node('select');product.setAttribute('aria-label','Produto do vídeo '+video.title);
for(const [value,title] of [['','Só na categoria DTF'],['file','Arquivo por metro'],
['avulsa','Artes avulsas'],['uvfile','Arquivo por metro UV'],['uv','Artes avulsas UV']]){
const option=node('option',title);option.value=value;product.append(option);
}
product.value=video.product||'';
const productLabel=node('label',undefined,'siteVideoField');productLabel.append(node('span','Vídeo flutuante'),product);
const enabled=node('input');enabled.type='checkbox';enabled.checked=video.enabled;
const publish=node('label',undefined,'siteVideoToggle');publish.append(enabled,node('span','Publicado no Site'));
const errorMessage=node('p',undefined,'siteVideoError');errorMessage.setAttribute('role','alert');
const save=button('Salvar vídeo',async()=>{
save.disabled=true;
errorMessage.textContent='';
try{
let uploadId=video.upload_id,captionsId=video.captions_id;
if(videoInput.files[0])uploadId=await dtfUpload(videoInput.files[0],{api,startPath:'/site-videos/uploads',
scope:'site-video:'+video.id+':video',progress:text=>say(text)});
if(captionsInput.files[0])captionsId=await dtfUpload(captionsInput.files[0],{api,startPath:'/site-videos/uploads',
scope:'site-video:'+video.id+':captions',progress:text=>say(text)});
await api('/site-videos/'+video.id,{upload_id:uploadId,captions_id:captionsId,
product:product.value||null,enabled:enabled.checked});
say('Vídeo salvo. O Site mostrará a nova versão na próxima abertura.');
await loadSiteVideos();
}catch(error){errorMessage.textContent=error.message;save.disabled=false;}
},'btn');
const fields=node('div',undefined,'siteVideoFields');
fields.append(videoLabel,captionsLabel,productLabel,publish,save,errorMessage);
row.append(heading,fields);return row;
}));
}

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

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