Compare commits

..

19 Commits

Author SHA1 Message Date
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
48 changed files with 5654 additions and 1845 deletions

View File

@@ -14,3 +14,14 @@ staging/staging.env
deploy/portainer.env deploy/portainer.env
portal portal
kanban 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

@@ -86,7 +86,7 @@ jobs:
# the generator's geometry. The provider suites use a fake transport: they # the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration. # prove the documented contract, not the integration.
- name: Print-file geometry and provider adapters - name: Print-file geometry and provider adapters
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_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 -v
- name: Runtime and retention regressions - name: Runtime and retention regressions
run: | run: |

View File

@@ -205,6 +205,8 @@ class ObjectStorage(Protocol):
def store(self, key: str, path: str, content_type: str): ... def store(self, key: str, path: str, content_type: str): ...
def health(self): ... def health(self): ...
def discard(self, key: str, upload_id: str, complete: bool): ... 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: class LocalS3Storage:
def __init__(self): def __init__(self):
@@ -266,6 +268,25 @@ class LocalS3Storage:
'ResponseContentDisposition': "attachment; filename*=UTF-8''" + quote(name, safe=''), 'ResponseContentDisposition': "attachment; filename*=UTF-8''" + quote(name, safe=''),
'ResponseContentType': 'application/octet-stream'}, ExpiresIn=300) '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): def discard(self, key, upload_id, complete):
if not complete: if not complete:
try: try:

View File

@@ -11,16 +11,17 @@ from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from fastapi.responses import RedirectResponse from fastapi.responses import RedirectResponse
from pydantic import Field from pydantic import Field
from psycopg.types.json import Jsonb
from ..core import db from ..core import db
from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can, client_ip, operator, from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can, client_ip, operator,
login_failed, may_move, may_reorder, password_matches, throttle) login_failed, may_move, may_reorder, password_matches, throttle)
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart from ..core.models import Contraction, Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart
from ..printjobs import file_prefix, queue as queue_print_files from ..printjobs import file_prefix, queue as queue_print_files
from .. import cnpj, machines, mail, payments, proof, quote_review, receipt from .. import cnpj, hotfolder, machines, mail, payments, proof, quote_review, receipt
from .. import tiny from .. import tiny
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES, from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES,
TRANSITIONS, payment, enqueue, freight, operator_identity, quote_view, storage, upload_row) TRANSITIONS, payment, enqueue, freight, operator_identity, quote_view, quote_views, storage, upload_row)
from .uploads import begin_upload from .uploads import begin_upload
from ..scanning import require_clean from ..scanning import require_clean
@@ -110,9 +111,10 @@ def board(user=Depends(operator)):
# card they can act on. Finished orders are terminal and only accumulate, # card they can act on. Finished orders are terminal and only accumulate,
# so the board carries a recent window of them and reports the true total. # so the board carries a recent window of them and reports the true total.
active = c.execute("SELECT * FROM dtf_local.orders WHERE state<>'fin' ORDER BY created_at").fetchall() active = c.execute("SELECT * FROM dtf_local.orders WHERE state<>'fin' ORDER BY created_at").fetchall()
finished = c.execute("SELECT * FROM dtf_local.orders WHERE state='fin' ORDER BY created_at DESC LIMIT %s", # A proof card that got its answer is done with (app/proof.py).
(BOARD_FINISHED_LIMIT,)).fetchall() finished = c.execute("""SELECT * FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL
finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin'").fetchone()['n'] ORDER BY created_at DESC LIMIT %s""", (BOARD_FINISHED_LIMIT,)).fetchall()
finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL").fetchone()['n']
pending = c.execute(f'''SELECT q.* FROM dtf_local.quotes q pending = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND q.approved IS NULL AND {LIVE_QUOTE} WHERE o.id IS NULL AND q.approved IS NULL AND {LIVE_QUOTE}
@@ -134,14 +136,15 @@ def board(user=Depends(operator)):
issues_total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events issues_total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events
WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') AND resolved_at IS NULL''').fetchone()['n'] WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') AND resolved_at IS NULL''').fetchone()['n']
backup = backup_status(c) backup = backup_status(c)
quotes = [quote_view(c, q) for q in pending + approved] quotes = quote_views(c, pending + approved)
return {'states': STATES, 'transitions': TRANSITIONS, 'back': BACK, return {'states': STATES, 'transitions': TRANSITIONS, 'back': BACK,
'orders': orders, 'payment_issues_total': issues_total, 'tiny': tiny_status(), 'operator': user, 'orders': orders, 'payment_issues_total': issues_total, 'tiny': tiny_status(), 'operator': user,
'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup, 'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup,
'mail': mail.status(c)}, 'mail': mail.status(c)},
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN, 'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
'finished_shown': len(finished), 'finished_total': finished_total, 'finished_shown': len(finished), 'finished_total': finished_total,
'machines': machines.rows(c), 'printing_cap': machines.PRINTING_CAP, # Who is on each machine now, for the machine question (item 12).
'machines': machines.rows(c, with_operators=True), 'printing_cap': machines.PRINTING_CAP,
'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes), 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
'names': company_names(c, orders, quotes), 'names': company_names(c, orders, quotes),
'pending_total': pending_total, 'approved_total': approved_total} 'pending_total': pending_total, 'approved_total': approved_total}
@@ -182,7 +185,7 @@ FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at
# their art, nor one of their originals, nor a correction they sent. `f` is # their art, nor one of their originals, nor a correction they sent. `f` is
# the final in dtf_local.order_files, `o` its order. # the final in dtf_local.order_files, `o` its order.
TREATED = """f.kind='final' TREATED = """f.kind='final'
AND NOT EXISTS (SELECT 1 FROM dtf_local.print_files p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id) AND NOT EXISTS (SELECT 1 FROM dtf_local.print_parts p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id)
AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(o.snapshot->'items') i WHERE i->'uploads' ? f.upload_id::text) AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(o.snapshot->'items') i WHERE i->'uploads' ? f.upload_id::text)
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files k WHERE k.order_id=f.order_id AND k.upload_id=f.upload_id AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files k WHERE k.order_id=f.order_id AND k.upload_id=f.upload_id
AND k.kind='correction')""" AND k.kind='correction')"""
@@ -209,6 +212,12 @@ def with_print_files(c, orders):
generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,u.name generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,u.name
FROM dtf_local.print_files p LEFT JOIN dtf_local.uploads u ON u.id=p.upload_id FROM dtf_local.print_files p LEFT JOIN dtf_local.uploads u ON u.id=p.upload_id
WHERE p.order_id=ANY(%s) ORDER BY p.item_index''', (ids,)).fetchall() WHERE p.order_id=ANY(%s) ORDER BY p.item_index''', (ids,)).fetchall()
# A film over 15 m is several PNGs, in order (item 13).
parts = c.execute('''SELECT p.order_id,p.item_index,p.part,p.upload_id,u.name FROM dtf_local.print_parts p
JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE p.order_id=ANY(%s) ORDER BY p.part''', (ids,)).fetchall()
for row in generated:
row['parts'] = [{'upload_id': part['upload_id'], 'name': part['name']} for part in parts
if part['order_id'] == row['order_id'] and part['item_index'] == row['item_index']]
finals = c.execute(f'''SELECT f.order_id,f.item_index,f.upload_id FROM dtf_local.order_files f finals = c.execute(f'''SELECT f.order_id,f.item_index,f.upload_id FROM dtf_local.order_files f
JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=ANY(%s) AND {FINAL_OK}''', (ids,)).fetchall() JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=ANY(%s) AND {FINAL_OK}''', (ids,)).fetchall()
# Expired ones too: once corrected, a generated file is no longer the artwork. # Expired ones too: once corrected, a generated file is no longer the artwork.
@@ -228,7 +237,21 @@ def with_print_files(c, orders):
# Why each order was last sent to correction, for the notice to the customer. # Why each order was last sent to correction, for the notice to the customer.
reasons = {row['order_id']: row['reason'] for row in c.execute('''SELECT DISTINCT ON (order_id) order_id,reason reasons = {row['order_id']: row['reason'] for row in c.execute('''SELECT DISTINCT ON (order_id) order_id,reason
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()} FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()}
# Where a printing order's files are in its machine's hot folder (item 10).
hot = hotfolder.progress(c, [o['id'] for o in orders if o['state'] == 'imp'])
# Each parent's latest proof card, and each card's parent (app/proof.py).
children = {r['parent_id']: r for r in c.execute('''SELECT DISTINCT ON (parent_id) parent_id,id,number,state,
proof_result,proof_decided_at,proof_decided_by,proof_reason FROM dtf_local.orders
WHERE parent_id=ANY(%s) AND cancelled_at IS NULL ORDER BY parent_id, created_at DESC''', (ids,)).fetchall()}
parents = {r['id']: r for r in c.execute('SELECT id,number,state FROM dtf_local.orders WHERE id=ANY(%s)',
([o['parent_id'] for o in orders if o.get('parent_id')],)).fetchall()}
for order in orders: for order in orders:
order['hot'] = hot.get(order['id'])
child = children.get(order['id'])
order['proof_card'] = child and {k: child[k] for k in ('id', 'number', 'state', 'proof_result',
'proof_decided_at', 'proof_decided_by', 'proof_reason')}
parent = parents.get(order.get('parent_id'))
order['proof_parent'] = parent and {'id': parent['id'], 'number': parent['number'], 'state': parent['state']}
order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None
order['print_files'] = [row for row in generated if row['order_id'] == order['id']] order['print_files'] = [row for row in generated if row['order_id'] == order['id']]
approved = [row for row in finals if row['order_id'] == order['id']] approved = [row for row in finals if row['order_id'] == order['id']]
@@ -260,7 +283,7 @@ def finished_page(before_created_at: datetime | None = None, before_id: UUID | N
"""Older finished orders, newest first, beyond the board's recent window.""" """Older finished orders, newest first, beyond the board's recent window."""
paged = cursor_pair(before_created_at, before_id) paged = cursor_pair(before_created_at, before_id)
with db.connect() as c: with db.connect() as c:
rows = c.execute('''SELECT * FROM dtf_local.orders WHERE state='fin' rows = c.execute('''SELECT * FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL
''' + ('AND (created_at,id)<(%s,%s) ' if paged else '') + ''' ''' + ('AND (created_at,id)<(%s,%s) ' if paged else '') + '''
ORDER BY created_at DESC,id DESC LIMIT %s''', ORDER BY created_at DESC,id DESC LIMIT %s''',
((before_created_at, before_id) if paged else ()) + (limit + 1,)).fetchall() ((before_created_at, before_id) if paged else ()) + (limit + 1,)).fetchall()
@@ -282,7 +305,31 @@ def payment_events(state: Literal['open','resolved','all'] = 'open',
ORDER BY received_at DESC,id DESC LIMIT %s OFFSET %s''', (limit, offset)).fetchall() ORDER BY received_at DESC,id DESC LIMIT %s OFFSET %s''', (limit, offset)).fetchall()
total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events
WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') ''' + where).fetchone()['n'] WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') ''' + where).fetchone()['n']
return {'issues': rows, 'total': total} for row in rows:
row.update(payment_context(c, row))
return {'issues': rows, 'total': total, 'thumbnails': thumbnails(c, [r['quote'] for r in rows if r.get('quote')])}
def payment_context(c, row):
"""Who tried to pay and for what: the quote the payment points to (its
customer, items and total), its order if there is one, the method of the
last attempt and Mercado Pago's own words about the payment."""
payload = c.execute('SELECT payload FROM dtf_local.payment_events WHERE id=%s', (row['id'],)).fetchone()['payload'] or {}
out = {'payment_id': payload.get('payment_id'), 'status_detail': payload.get('status_detail'), 'quote': None, 'order': None, 'method': None}
try:
quote_id = UUID(str(row.get('reference') or ''))
except ValueError:
return out
quote = c.execute('SELECT id,draft,approved,created_at,approved_at FROM dtf_local.quotes WHERE id=%s', (quote_id,)).fetchone()
if not quote:
return out
out['quote'] = {'id': quote['id'], 'draft': quote['draft'], 'created_at': quote['created_at'], 'approved_at': quote['approved_at'],
'total_cents': (quote['approved'] or {}).get('total_cents')}
out['order'] = c.execute('SELECT id,number,state,cancelled_at FROM dtf_local.orders WHERE quote_id=%s', (quote_id,)).fetchone()
attempt = c.execute('''SELECT method,status FROM dtf_local.payment_intents WHERE quote_id=%s
ORDER BY created_at DESC LIMIT 1''', (quote_id,)).fetchone()
out['method'] = attempt['method'] if attempt else None
return out
@router.get('/api/operator/events') @router.get('/api/operator/events')
@@ -378,7 +425,7 @@ def quote_page(kind: Literal['pending','approved'], before_created_at: datetime
total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE {where}''', params).fetchone()['n'] WHERE {where}''', params).fetchone()['n']
quotes = [quote_view(c,row) for row in rows[:limit]] quotes = quote_views(c, rows[:limit])
return {'quotes': quotes, 'has_more': len(rows)>limit, 'total': total, return {'quotes': quotes, 'has_more': len(rows)>limit, 'total': total,
'thumbnails': thumbnails(c, quotes), 'names': company_names(c, quotes)} 'thumbnails': thumbnails(c, quotes), 'names': company_names(c, quotes)}
@@ -401,14 +448,15 @@ def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator))
params.append(code + '%') params.append(code + '%')
quote_match, quote_params = customer_match('q.draft', q) quote_match, quote_params = customer_match('q.draft', q)
with db.connect() as c: with db.connect() as c:
orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE {sql} # Real orders: a proof card is found through its order (app/proof.py).
orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE ({sql}) AND parent_id IS NULL
ORDER BY created_at DESC LIMIT 8''', params).fetchall() ORDER BY created_at DESC LIMIT 8''', params).fetchall()
rows = c.execute(f'''SELECT q.* FROM dtf_local.quotes q rows = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
WHERE o.id IS NULL AND {LIVE_QUOTE} AND {quote_match} WHERE o.id IS NULL AND {LIVE_QUOTE} AND {quote_match}
ORDER BY q.created_at DESC LIMIT 8''', quote_params).fetchall() ORDER BY q.created_at DESC LIMIT 8''', quote_params).fetchall()
orders = with_print_files(c, orders) orders = with_print_files(c, orders)
quotes = [quote_view(c, row) for row in rows] quotes = quote_views(c, rows)
return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes), return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
'names': company_names(c, orders, quotes)} 'names': company_names(c, orders, quotes)}
@@ -564,11 +612,14 @@ def delete_order(uid: UUID, user=Depends(can('manage'))):
# order's). The worker deletes them within a minute. # order's). The worker deletes them within a minute.
originals = {str(u) for item in row['snapshot'].get('items') or [] for u in item.get('uploads') or []} originals = {str(u) for item in row['snapshot'].get('items') or [] for u in item.get('uploads') or []}
produced = {str(r['upload_id']) for r in c.execute('''SELECT upload_id FROM dtf_local.order_files WHERE order_id=%s produced = {str(r['upload_id']) for r in c.execute('''SELECT upload_id FROM dtf_local.order_files WHERE order_id=%s
UNION SELECT upload_id FROM dtf_local.print_files WHERE order_id=%s AND upload_id IS NOT NULL''', UNION SELECT upload_id FROM dtf_local.print_files WHERE order_id=%s AND upload_id IS NOT NULL
(uid, uid)).fetchall()} UNION SELECT upload_id FROM dtf_local.print_parts WHERE order_id=%s''',
(uid, uid, uid)).fetchall()}
candidates = produced - originals if test else produced | originals candidates = produced - originals if test else produced | originals
# Its proof cards (app/proof.py) go with it.
cards = [r['id'] for r in c.execute('SELECT id FROM dtf_local.orders WHERE parent_id=%s', (uid,)).fetchall()]
for table in ('movements', 'order_files', 'print_files'): for table in ('movements', 'order_files', 'print_files'):
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (uid,)) c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=ANY(%s)', ([uid] + cards,))
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',)) c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (uid,)) c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (uid,))
if not test: if not test:
@@ -587,12 +638,13 @@ def release_files(c, uploads):
for upload in uploads: for upload in uploads:
used = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE upload_id=%s 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_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 UNION ALL SELECT 1 FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i
WHERE i->'uploads' ? %s WHERE i->'uploads' ? %s
UNION ALL SELECT 1 FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i UNION ALL SELECT 1 FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i
WHERE q.discarded_at IS NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.orders x WHERE x.quote_id=q.id) WHERE q.discarded_at IS NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.orders x WHERE x.quote_id=q.id)
AND i->'uploads' ? %s AND i->'uploads' ? %s
LIMIT 1''', (upload, upload, upload, upload)).fetchone() LIMIT 1''', (upload,) * 5).fetchone()
if not used: if not used:
free.append(upload) free.append(upload)
if free: if free:
@@ -612,6 +664,7 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))):
(user, body.note, uid)).fetchone() (user, body.note, uid)).fetchone()
if not row: if not row:
raise HTTPException(404, 'Pedido não encontrado ou já cancelado.') raise HTTPException(404, 'Pedido não encontrado ou já cancelado.')
hotfolder.stop(c, uid)
if payments.in_tiny(row): if payments.in_tiny(row):
sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL", sale = c.execute("SELECT receipt FROM dtf_local.outbox WHERE event_key=%s AND delivered_at IS NOT NULL",
(f'{uid}:paid:tiny',)).fetchone() (f'{uid}:paid:tiny',)).fetchone()
@@ -649,6 +702,35 @@ def choose_machine(uid: UUID, body: MachineChoice, request: Request, user=Depend
return {'ok': True} return {'ok': True}
@router.post('/api/operator/orders/{uid}/contraction')
def choose_contraction(uid: UUID, body: Contraction, user=Depends(can('produce'))):
"""The contraction class of an item (Dropstar, 2026-10-30): the browser's
measure comes prefilled, and whoever prepares the art may change it until
the order prints. Both stay: the measure in the snapshot, the choice here."""
with db.connect() as c:
row = c.execute('SELECT snapshot,state,cancelled_at,contraction FROM dtf_local.orders WHERE id=%s FOR UPDATE',
(uid,)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
if body.item_index >= len(row['snapshot']['items']):
raise HTTPException(422, 'Item não encontrado no pedido.')
# Printing, the class still changes while the item's files wait to go
# into the hot folder: the class is its folder (item 10).
written = row['state'] == 'imp' and c.execute('''SELECT 1 FROM dtf_local.hot_parts WHERE order_id=%s
AND item_index=%s AND state NOT IN ('queued','gone') LIMIT 1''', (uid, body.item_index)).fetchone()
if row['cancelled_at'] or row['state'] not in ('rec', 'tra', 'cor', 'imp') or written:
raise HTTPException(409, 'A contração muda até o arquivo ir para a hot folder da máquina.')
chosen = dict(row['contraction'] or {})
key = str(body.item_index)
if body.value is None:
chosen.pop(key, None)
else:
chosen[key] = {'class': body.value, 'by': user, 'at': datetime.now(timezone.utc).isoformat()}
c.execute('UPDATE dtf_local.orders SET contraction=%s WHERE id=%s', (Jsonb(chosen), uid))
audit('order_contraction_chosen', order=str(uid), item=body.item_index, value=body.value or '', operator=user)
return {'ok': True, 'contraction': chosen}
class ContactWait(StrictModel): class ContactWait(StrictModel):
waiting: bool waiting: bool
note: str = Field(default='', max_length=500) note: str = Field(default='', max_length=500)
@@ -677,10 +759,78 @@ def contact(uid: UUID, body: ContactWait, user=Depends(can('produce'))):
return {'ok': True} return {'ok': True}
class ProofAnswer(StrictModel):
result: Literal['ok', 'rejected']
reason: str = Field(default='', max_length=500)
@router.post('/api/operator/orders/{uid}/proof-answer')
def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
"""The answer to a proof card in Revisão (Dropstar, 2026-11-03): Prova OK
puts its order in the queue; Prova reprovada, with its reason, sends the
order back to Arte recebida. Either way the card closes."""
reason = ' '.join(body.reason.split())
if body.result == 'rejected' and len(reason) < 3:
raise HTTPException(422, 'Diga por que a prova foi reprovada.')
with db.connect() as c:
card = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not card or not card.get('parent_id'):
raise HTTPException(404, 'Card de prova não encontrado.')
if card['cancelled_at'] or card['proof_result'] or card['state'] != 'rev':
raise HTTPException(409, 'A prova é respondida em Revisão, uma vez.')
parent = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (card['parent_id'],)).fetchone()
c.execute('''UPDATE dtf_local.orders SET proof_result=%s, proof_decided_at=now(), proof_decided_by=%s,
proof_reason=%s, state='fin', version=version+1, updated_at=now() WHERE id=%s''',
(body.result, user, reason or None, uid))
label = 'Prova OK' if body.result == 'ok' else 'Prova reprovada: ' + reason
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
VALUES(%s,'rev','fin',%s,%s)''', (uid, user, label))
if body.result == 'ok':
# The order enters the queue: Arte conferida, if its finals are approved.
ready = parent['state'] == 'rec' and all(c.execute('''SELECT 1 FROM dtf_local.order_files
WHERE order_id=%s AND kind='final' AND active AND item_index=%s LIMIT 1''', (parent['id'], i)).fetchone()
for i in range(len(parent['snapshot']['items'])))
c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1, updated_at=now(),
state=CASE WHEN %s THEN 'tra' ELSE state END WHERE id=%s''', (user, ready, parent['id']))
if ready:
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
VALUES(%s,'rec','tra',%s,'Prova OK')''', (parent['id'], user))
elif parent['state'] in ('rec', 'tra') and not parent['cancelled_at']:
# Back to Arte recebida with the reason; its final is approved again.
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (parent['id'],))
c.execute('''UPDATE dtf_local.orders SET state='rec', proof_ok_at=NULL, proof_ok_by=NULL, queue_key=NULL,
version=version+1, updated_at=now() WHERE id=%s''', (parent['id'],))
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
VALUES(%s,%s,'rec',%s,%s)''', (parent['id'], parent['state'], user, label))
audit('order_proof_answered', order=parent['number'], result=body.result, operator=user)
return {'ok': True}
@router.post('/api/operator/orders/{uid}/proof-card')
def new_proof_card(uid: UUID, user=Depends(can('produce'))):
"""A new proof card for an order whose proof was rejected, or that has
none yet (an order from before the cards)."""
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
if not row or row.get('parent_id'):
raise HTTPException(404, 'Pedido não encontrado.')
if row['cancelled_at'] or row['state'] not in ('rec', 'tra') or row['proof_ok_at'] or proof.open_child(c, uid):
raise HTTPException(409, 'Este pedido já tem uma prova em andamento ou aprovada.')
child = proof.create_child(c, row)
if not child:
raise HTTPException(409, 'Este pedido não leva prova.')
machines.route(c)
audit('order_proof_card', order=row['number'], operator=user)
return {'ok': True, 'id': child['id'], 'number': child['number']}
@router.post('/api/operator/orders/{uid}/proof') @router.post('/api/operator/orders/{uid}/proof')
def proof_ok(uid: UUID, user=Depends(can('print'))): def proof_ok(uid: UUID, user=Depends(can('print'))):
"""The print room checked the proof: the order may reach Finalizado.""" """An order from before the proof cards: the print room checked the
proof, and the order may reach Finalizado."""
with db.connect() as c: with db.connect() as c:
if proof.open_child(c, uid):
raise HTTPException(409, 'Este pedido tem um card de prova: a resposta vai nele.')
row = c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1 row = c.execute('''UPDATE dtf_local.orders SET proof_ok_at=now(), proof_ok_by=%s, version=version+1
WHERE id=%s AND cancelled_at IS NULL AND state<>'fin' RETURNING number, version''', (user, uid)).fetchone() WHERE id=%s AND cancelled_at IS NULL AND state<>'fin' RETURNING number, version''', (user, uid)).fetchone()
if not row: if not row:
@@ -869,7 +1019,22 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
raise HTTPException(409, 'Escolha a máquina em que você está.') raise HTTPException(409, 'Escolha a máquina em que você está.')
if not pulling and str(row['machine_id'] or '') != session_machine['id']: if not pulling and str(row['machine_id'] or '') != session_machine['id']:
raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.') raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.')
if pulling and session_machine and (account['role'] == 'operador' or not row['machine_chosen']): # Dropped on a machine's lane in Imprimindo: that machine, when it
# prints the product. The operator's pull stays their machine's.
if pulling and body.machine_id:
if account['role'] == 'operador':
if str(body.machine_id) != session_machine['id']:
raise HTTPException(409, f"Você está na {session_machine['name']}: o que você puxa vai para ela.")
else:
target = c.execute('SELECT name, products, active FROM dtf_local.machines WHERE id=%s',
(body.machine_id,)).fetchone()
if not target or not target['active']:
raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.')
if machines.product_family(row) not in target['products']:
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
row['machine_id'] = body.machine_id
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=true WHERE id=%s', (body.machine_id, uid))
if pulling and session_machine and not body.machine_id and (account['role'] == 'operador' or not row['machine_chosen']):
prints = c.execute('SELECT products FROM dtf_local.machines WHERE id=%s', (session_machine['id'],)).fetchone() prints = c.execute('SELECT products FROM dtf_local.machines WHERE id=%s', (session_machine['id'],)).fetchone()
if machines.product_family(row) in (prints or {}).get('products', []): if machines.product_family(row) in (prints or {}).get('products', []):
row['machine_id'] = session_machine['id'] row['machine_id'] = session_machine['id']
@@ -886,7 +1051,13 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
# Two at most per machine in Imprimindo (app/machines.py). # Two at most per machine in Imprimindo (app/machines.py).
if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)): if body.state == 'imp' and (name := machines.full(c, row['machine_id'], uid)):
raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.') raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.')
if body.state == 'fin' and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']: # A proof card ends with its answer, not in Finalizado; its order waits
# for that answer outside the queue (app/proof.py).
if row.get('parent_id') and body.state == 'fin':
raise HTTPException(409, 'A prova termina com Prova OK ou Prova reprovada, não em Finalizado.')
if body.state == 'imp' and proof.waiting(c, row):
raise HTTPException(409, 'Aguardando prova: o pedido entra na fila com Prova OK no card da prova.')
if body.state == 'fin' and not row.get('parent_id') and proof.needs_proof(row['snapshot']) and not row['proof_ok_at']:
raise HTTPException(409, 'Falta a prova: confira a prova impressa e marque Prova OK antes de finalizar.') raise HTTPException(409, 'Falta a prova: confira a prova impressa e marque Prova OK antes de finalizar.')
if body.state == 'cor': if body.state == 'cor':
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,)) c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,))
@@ -898,6 +1069,12 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
(row['machine_id'],)).fetchone() or {}).get('name') (row['machine_id'],)).fetchone() or {}).get('name')
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,machine) c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,machine)
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid,row['state'],body.state,user,body.reason,back,machine_name)) VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid,row['state'],body.state,user,body.reason,back,machine_name))
# Pulled to Imprimindo, its files go to its machine's hot folder; out
# of it, what Flexi did not take leaves (item 10).
if row['state'] == 'imp':
hotfolder.stop(c, uid)
if body.state == 'imp':
hotfolder.start(c, uid)
# A pickup reaching Finalizado has its receipt due (item 14), once. # A pickup reaching Finalizado has its receipt due (item 14), once.
due = body.state == 'fin' and not back and receipt.is_pickup(row['snapshot']) due = body.state == 'fin' and not back and receipt.is_pickup(row['snapshot'])
changed = c.execute('''UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL, changed = c.execute('''UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL,
@@ -1036,7 +1213,8 @@ def thumbnail(uid: UUID, user=Depends(operator)):
headers={'Cache-Control': 'private, max-age=86400', 'Content-Disposition': 'inline'}) headers={'Cache-Control': 'private, max-age=86400', 'Content-Disposition': 'inline'})
# Real work only: an operator's test order and a cancelled one are not production. # Real work only: an operator's test order and a cancelled one are not production.
REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste'" # A proof card (app/proof.py) is no sale either.
REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste' AND o.parent_id IS NULL"
# Where orders come from (D-21), in the order Números lists them. # Where orders come from (D-21), in the order Números lists them.
ORIGINS = ('site', 'dropflow', 'atendimento') ORIGINS = ('site', 'dropflow', 'atendimento')
LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date" LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date"
@@ -1294,21 +1472,64 @@ def print_ready(c, states, only=None, paid_after=None):
WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s))
AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.cancelled_at IS NULL AND {FINAL_OK} AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.cancelled_at IS NULL AND {FINAL_OK}
UNION ALL UNION ALL
SELECT o.id,o.state,o.number,p.item_index,p.upload_id,u.object_key,u.name, SELECT o.id,o.state,o.number,p.item_index,pp.upload_id,u.object_key,u.name,
COALESCE(o.queue_key, extract(epoch FROM o.created_at)) COALESCE(o.queue_key, extract(epoch FROM o.created_at))
FROM dtf_local.orders o FROM dtf_local.orders o
JOIN dtf_local.print_files p ON p.order_id=o.id JOIN dtf_local.uploads u ON u.id=p.upload_id JOIN dtf_local.print_files p ON p.order_id=o.id
JOIN dtf_local.print_parts pp ON pp.order_id=p.order_id AND pp.item_index=p.item_index
JOIN dtf_local.uploads u ON u.id=pp.upload_id
WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s))
AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.state IN ('rec','tra') AND o.cancelled_at IS NULL AND p.status='ready' AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.state IN ('rec','tra') AND o.cancelled_at IS NULL AND p.status='ready'
AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean' AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='final' AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='final'
AND f.active AND f.item_index=p.item_index) AND f.active AND f.item_index=p.item_index)
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='correction') AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='correction')
ORDER BY position,order_id,item_index''', ORDER BY position,order_id,item_index,name''',
(list(states), ids, ids, paid_after, paid_after, list(states), ids, ids, paid_after, paid_after)).fetchall() (list(states), ids, ids, paid_after, paid_after, list(states), ids, ids, paid_after, paid_after)).fetchall()
return rows return rows
@router.get('/api/operator/orders/{uid}/view')
def view_files(uid: UUID, user=Depends(operator)):
"""What "Abrir e conferir" shows (item 7): each item's generated PNG, part
by part, with links to its pieces, then the customer's originals, which
have only their picture."""
with db.connect() as c:
order = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
made = c.execute('''SELECT item_index, detail FROM dtf_local.print_files WHERE order_id=%s AND status='ready'
ORDER BY item_index''', (uid,)).fetchall()
parts = c.execute('''SELECT p.item_index, p.part, p.upload_id, u.name FROM dtf_local.print_parts p
JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE p.order_id=%s AND u.purged_at IS NULL
ORDER BY p.item_index, p.part''', (uid,)).fetchall()
pictured = {str(r['upload_id']) for r in c.execute(
'SELECT upload_id FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s)',
([UUID(u) for item in order['snapshot']['items'] for u in item['uploads']],)).fetchall()}
items = order['snapshot']['items']
many = len(items) > 1
files = []
for row in made:
mine = [p for p in parts if p['item_index'] == row['item_index']]
details = {d.get('name'): d for d in row['detail'].get('parts') or []}
for part in mine:
tiles = (details.get(part['name']) or {}).get('tiles')
label = (f"Item {row['item_index'] + 1}" if many else 'Arquivo') + \
(f" · parte {part['part']}/{len(mine)}" if len(mine) > 1 else '')
files.append({'name': part['name'], 'label': label, 'item': row['item_index'],
'manifest': tiles and {**tiles, 'urls': [
[storage.view(f"originals/tiles/{part['upload_id']}/{k}/{i}.png", 'image/png')
for i in range(level['strips'])] for k, level in enumerate(tiles['levels'])]}})
for index, item in enumerate(items):
for n, upload in enumerate(item['uploads']):
files.append({'name': ('Original ' + str(n + 1)) if len(item['uploads']) > 1 else 'Original',
'label': (f'Item {index + 1} · ' if many else '') + 'original' +
(f' {n + 1}' if len(item['uploads']) > 1 else ''),
'item': index, 'manifest': None,
'picture': f'/api/operator/uploads/{upload}/thumbnail' if upload in pictured else None})
return {'files': files}
@router.get('/api/operator/orders/{uid}/folder-files') @router.get('/api/operator/orders/{uid}/folder-files')
def folder_files(uid: UUID, user=Depends(can('produce'))): def folder_files(uid: UUID, user=Depends(can('produce'))):
"""What each item's file is called in the order's stage folder, as the """What each item's file is called in the order's stage folder, as the
@@ -1342,6 +1563,42 @@ class FolderSync(StrictModel):
since: datetime | None = None since: datetime | None = None
@router.post('/api/operator/queue/hot')
def queue_hot(user=Depends(can('print'))):
"""For a computer with the automatic folders: the parts it should write
into the machines' hot folders now, claimed for it alone; those written
and not yet taken by Flexi, to see whether they still are; and those to
delete, withdrawn from cards that left Imprimindo (item 10)."""
with db.connect() as c:
due = hotfolder.claim(c, user)
keys = {str(r['upload_id']): r['object_key'] for r in c.execute(
'SELECT id AS upload_id, object_key FROM dtf_local.uploads WHERE id=ANY(%s)',
([r['upload_id'] for r in due],)).fetchall()} if due else {}
watched = hotfolder.watched(c)
return {'folder': hotfolder.PRINTING_FOLDER,
'write': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name'],
'url': storage.download(keys[str(r['upload_id'])], r['name'])} for r in due],
'watch': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']}
for r in watched if r['state'] == 'written'],
'withdraw': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']}
for r in watched if r['state'] == 'withdraw']}
class HotReport(StrictModel):
state: Literal['written', 'released', 'consumed', 'gone']
@router.post('/api/operator/queue/hot/{part_id}')
def report_hot(part_id: int, body: HotReport, user=Depends(can('print'))):
"""What a computer saw of a part: written, not written, taken by Flexi,
or deleted after it was withdrawn."""
with db.connect() as c:
applied = hotfolder.report(c, part_id, body.state, user)
if applied and body.state == 'written':
audit('hot_folder_written', part=part_id, operator=user)
return {'ok': applied}
@router.post('/api/operator/queue/folder') @router.post('/api/operator/queue/folder')
def queue_folder(body: FolderSync, user=Depends(can('print'))): def queue_folder(body: FolderSync, user=Depends(can('print'))):
"""What the Kanban's automatic folders should hold. `early` is Dropstar's """What the Kanban's automatic folders should hold. `early` is Dropstar's

View File

@@ -129,7 +129,10 @@ def change_password(body: PasswordChange, request: Request):
def user_rows(c): def user_rows(c):
"""Every account, with the machines its open sessions are on now (item 12).""" """Every account, with the machines its open sessions are on now (item 12)."""
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at, rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at,
COALESCE(array_agg(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 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 ON s.username=o.email AND s.expires_at>now() AND s.machine_id IS NOT NULL
GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall() GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()

View File

@@ -20,8 +20,9 @@ def generated_owner(c, order, ref, kind):
from, and only while that item still has its original artwork: after a from, and only while that item still has its original artwork: after a
customer correction it reproduces a layout nobody wants printed. customer correction it reproduces a layout nobody wants printed.
""" """
generated = c.execute('''SELECT item_index FROM dtf_local.print_files generated = c.execute('''SELECT p.item_index FROM dtf_local.print_parts p JOIN dtf_local.print_files f
WHERE order_id=%s AND upload_id=%s AND status='ready' ''', (order['id'], ref.upload_id)).fetchone() 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: if not generated:
return None return None
if kind != 'final' or generated['item_index'] != ref.item_index: if kind != 'final' or generated['item_index'] != ref.item_index:
@@ -29,7 +30,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", if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1",
(order['id'],)).fetchone(): (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.') 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'] return c.execute('SELECT owner FROM dtf_local.uploads WHERE id=%s', (ref.upload_id,)).fetchone()['owner']

View File

@@ -114,8 +114,11 @@ def login_failed(email):
"""Count a failed sign-in (or registration attempt) against the account.""" """Count a failed sign-in (or registration attempt) against the account."""
rate_limit('auth-account', email, 1_000_000) rate_limit('auth-account', email, 1_000_000)
# What each Kanban profile may do. "view" is reading; "produce" moves cards and # What each Kanban profile may do. "view" is reading; "produce" handles the
# handles artwork; "print" is the print room's side of it (the machine, 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 # queue's order, its files and folder); "manage" covers quotes, cancellations
# and payments; "users" is the Usuários page; "integrations" is everything in # 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 # Integrações but the print room's folder (connecting Tiny, the checks, the
@@ -125,7 +128,7 @@ def login_failed(email):
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro') ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro')
CAPABILITIES = { CAPABILITIES = {
'view': set(ROLES), 'view': set(ROLES),
'produce': {'superadmin', 'admin', 'gestao', 'designer', 'operador'}, 'produce': {'superadmin', 'admin', 'gestao', 'designer'},
'print': {'superadmin', 'admin', 'gestao', 'operador'}, 'print': {'superadmin', 'admin', 'gestao', 'operador'},
'manage': {'superadmin', 'admin', 'gestao'}, 'manage': {'superadmin', 'admin', 'gestao'},
# Registering an order paid outside the system, from its Site quote (D-35). # Registering an order paid outside the system, from its Site quote (D-35).
@@ -142,9 +145,12 @@ CAPABILITIES = {
# file. Resolving a payment stays with "manage". # file. Resolving a payment stays with "manage".
'payments': {'superadmin', 'admin', 'gestao', 'financeiro'}, 'payments': {'superadmin', 'admin', 'gestao', 'financeiro'},
'cancel': {'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 # "Retirado" at the counter (Dropstar's third round, item 14): everyone
# but the seller, who only views (D-30). It includes everyone who produces, # 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'}, 'deliver': {'superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor'},
} }
@@ -203,6 +209,11 @@ def signed_in(request: Request):
JOIN dtf_local.operators o ON o.email=s.username AND o.active JOIN dtf_local.operators o ON o.email=s.username AND o.active
LEFT JOIN dtf_local.machines m ON m.id=s.machine_id LEFT JOIN dtf_local.machines m ON m.id=s.machine_id
WHERE s.token_hash=%s AND s.expires_at>now()''', (digest,)).fetchone() WHERE s.token_hash=%s AND s.expires_at>now()''', (digest,)).fetchone()
if row:
# 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: if not row:
raise HTTPException(401, 'Sua sessão expirou. Entre de novo.') raise HTTPException(401, 'Sua sessão expirou. Entre de novo.')
# The machine this session works on (item 12), or None. # The machine this session works on (item 12), or None.

View File

@@ -150,6 +150,28 @@ class ProductionSpec(StrictModel):
sources: list[ProductionSource] = Field(min_length=1, max_length=20) sources: list[ProductionSource] = Field(min_length=1, max_length=20)
placements: list[ProductionPlacement] = Field(min_length=1, max_length=4000) 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): class Item(StrictModel):
mode: Literal['file','avulsa','uvfile','uv'] mode: Literal['file','avulsa','uvfile','uv']
metres: Decimal = Field(gt=0, le=12000) metres: Decimal = Field(gt=0, le=12000)
@@ -161,9 +183,19 @@ class Item(StrictModel):
# Residue dots under 2 mm the customer accepted printing on a ready sheet, # Residue dots under 2 mm the customer accepted printing on a ready sheet,
# rather than erasing them (Dropstar, 2026-10-29): 0 when none. # rather than erasing them (Dropstar, 2026-10-29): 0 when none.
residue_accepted: int = Field(default=0, ge=0, le=1000000, strict=True) 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
split: Split | None = None
@model_validator(mode='after') @model_validator(mode='after')
def production_matches_uploads(self): 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: if [source.upload_id for source in self.production.sources] != self.uploads:
raise ValueError('Production sources must match uploaded files in order') raise ValueError('Production sources must match uploaded files in order')
is_sheet = self.mode in ('file', 'uvfile') is_sheet = self.mode in ('file', 'uvfile')
@@ -214,6 +246,11 @@ class QuoteRequest(StrictModel):
# "Quero aprovar uma prova antes de imprimir": the order waits for the customer. # "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
proof: bool = False proof: bool = False
@model_validator(mode='after')
def splits_complete(self):
check_splits(self.items)
return self
@model_validator(mode='after') @model_validator(mode='after')
def destination_matches_freight(self): def destination_matches_freight(self):
if self.freight.service == 'pickup': if self.freight.service == 'pickup':
@@ -228,6 +265,11 @@ class QuoteRequest(StrictModel):
class Review(StrictModel): class Review(StrictModel):
items: list[Item] = Field(min_length=1, max_length=30) 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): class Pay(StrictModel):
quote_id: UUID quote_id: UUID
@@ -264,6 +306,13 @@ class Move(StrictModel):
state: Literal['rec','tra','imp','cor','rev','fin'] state: Literal['rec','tra','imp','cor','rev','fin']
version: int = Field(ge=0) version: int = Field(ge=0)
reason: str = Field(default='', max_length=1000) reason: str = Field(default='', max_length=1000)
# Pulled into Imprimindo onto a machine's lane: the machine it prints on.
machine_id: UUID | 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): class Resolution(StrictModel):
note: str = Field(min_length=3, max_length=1000) note: str = Field(min_length=3, max_length=1000)

View File

@@ -32,15 +32,16 @@ def is_manual(item, names) -> bool:
for source in item['production']['sources']) for source in item['production']['sources'])
def price(mode: str, metres: str, grade: int, extra_cents: int = 0) -> dict: def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Decimal = Decimal('1')) -> dict:
"""The item's charge. The grade is validated and kept with the item; the """The item's charge. The grade is validated and kept with the item; the
price does not depend on it.""" price does not depend on it. A split sheet has no minimum of its own: its
group has one (bill_splits)."""
length = Decimal(str(metres)) length = Decimal(str(metres))
if mode not in PRICES or not length.is_finite() or not 0 < length <= 12000: if mode not in PRICES or not length.is_finite() or not 0 < length <= 12000:
raise ValueError('Invalid product or length') raise ValueError('Invalid product or length')
if isinstance(grade, bool) or not isinstance(grade, int) or not 0 <= grade <= 100: if isinstance(grade, bool) or not isinstance(grade, int) or not 0 <= grade <= 100:
raise ValueError('Grade must be an integer between 0 and 100') raise ValueError('Grade must be an integer between 0 and 100')
billed = max(Decimal('1'), (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10) billed = max(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: if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0:
raise ValueError('Invalid extra charge') raise ValueError('Invalid extra charge')
unit = PRICES[mode] + extra_cents unit = PRICES[mode] + extra_cents
@@ -50,3 +51,22 @@ def price(mode: str, metres: str, grade: int, extra_cents: int = 0) -> dict:
if extra_cents: if extra_cents:
priced['manual_extra_cents'] = extra_cents priced['manual_extra_cents'] = extra_cents
return priced return priced
def bill_splits(priced: list) -> list:
"""The order minimum of 1 m once per split group, on its first sheet: the
customer did not choose the split (item 17), so it never costs a metre more."""
for group in dict.fromkeys(i['split']['group'] for i in priced if i.get('split')):
parts = [i for i in priced if (i.get('split') or {}).get('group') == group]
short = Decimal('1') - sum(Decimal(i['billed_metres']) for i in parts)
if short > 0:
first = min(parts, key=lambda i: i['split']['part'])
billed = Decimal(first['billed_metres']) + short
first.update(billed_metres=str(billed), total_cents=int(billed * first['unit_cents']))
return priced
def sheet_label(item: dict) -> str:
"""' · folha 1 de 2' on a split sheet (item 17), for the customer's lists."""
split = item.get('split')
return f" · folha {split['part']} de {split['of']}" if split else ''

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}

View File

@@ -23,6 +23,8 @@ import ssl
from email.message import EmailMessage from email.message import EmailMessage
from email.utils import formataddr, formatdate, make_msgid, parseaddr from email.utils import formataddr, formatdate, make_msgid, parseaddr
from .core.pricing import sheet_label
ADAPTER = os.environ.get('MAIL_ADAPTER', 'off') ADAPTER = os.environ.get('MAIL_ADAPTER', 'off')
RESET_MINUTES = 60 RESET_MINUTES = 60
CODE_MINUTES = 15 CODE_MINUTES = 15
@@ -70,7 +72,7 @@ def order_paid(c, order, origin):
delivery = freight.get('description') or 'Entrega' delivery = freight.get('description') or 'Entrega'
if freight.get('days'): if freight.get('days'):
delivery += f" · até {freight['days']} dias úteis" 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" f"{str(i.get('billed_metres') or i.get('metres')).replace('.', ',')} m"
for i in snapshot.get('items', []))), for i in snapshot.get('items', []))),
('Entrega', delivery), ('Entrega', delivery),

View File

@@ -63,9 +63,10 @@ OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit')
def in_tiny(order): def in_tiny(order):
"""Whether the order goes to Tiny: every order but a test. A Dropflow """Whether the order goes to Tiny: every order but a test or a proof card
order goes in its own revenue category (app/tiny.py, CATEGORIES).""" (app/proof.py), which is no sale. A Dropflow order goes in its own revenue
return not is_test(order) category (app/tiny.py, CATEGORIES)."""
return not is_test(order) and not order.get('parent_id')
# How long a file is kept while nothing has been paid for it. A cart's files # How long a file is kept while nothing has been paid for it. A cart's files
@@ -118,6 +119,8 @@ def create_order(c, quote, payment, origin):
order = c.execute('''UPDATE dtf_local.orders SET contact_since=now(), contact_by='Site', contact_note=%s 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() 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'],)) c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (order['id'],))
# An order with a proof gets its proof card (app/proof.py).
proof.create_child(c, order)
machines.route(c) machines.route(c)
if is_test(order): if is_test(order):
return order, True return order, True

View File

@@ -5,19 +5,20 @@ 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 lock or a database connection. A claim older than CLAIM_TIMEOUT is assumed to
belong to a worker that died and is taken again. belong to a worker that died and is taken again.
The result is an ordinary upload row owned by an identity derived from the The result is a 300 DPI PNG (item 13, app/printpng.py), or its parts for a
order, already marked clean: its only inputs are artwork that passed the film over 15 m: ordinary upload rows owned by an identity derived from the
malware scan, and the bytes are written here. The operator still decides order, already marked clean, since their only inputs are artwork that passed
whether it becomes the final file; generation never approves anything. 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 Sheets of several GB are the normal order: a PNG or a PDF is read band by
memory than the worker has. A source above LARGE_SOURCE_BYTES is never band, so its size does not matter. Any other file above LARGE_SOURCE_BYTES
opened: a finished sheet placed whole on the film is already its own print is prepared by hand from the original.
file, so the original becomes the print file; any other layout is prepared
by hand from the original.
""" """
import logging import logging
import os import os
import shutil
import tempfile import tempfile
import time import time
from datetime import timedelta from datetime import timedelta
@@ -29,16 +30,19 @@ from psycopg.types.json import Jsonb
from .core.auth import audit from .core.auth import audit
from .core.db import connect from .core.db import connect
from .printfile import Unsupported, render from .printfile import Unsupported
from .printpng import render
from .proof import PROOF_SHEET_CM
from .tiny import purchase_order from .tiny import purchase_order
LOCAL = ZoneInfo('America/Sao_Paulo') LOCAL = ZoneInfo('America/Sao_Paulo')
CLAIM_TIMEOUT = timedelta(minutes=15) # A 15 m part takes minutes to write; a long film, several parts.
CLAIM_TIMEOUT = timedelta(minutes=60)
MAX_ATTEMPTS = 3 MAX_ATTEMPTS = 3
LARGE_SOURCE_BYTES = int(os.environ.get('PRINT_DECODE_MAX_BYTES', str(300 * 1024 * 1024))) LARGE_SOURCE_BYTES = int(os.environ.get('PRINT_DECODE_MAX_BYTES', str(300 * 1024 * 1024)))
# Formats the operator can import as they are. # Read band by band, whatever their size.
PRINTABLE_ORIGINAL = ('.png', '.jpg', '.jpeg', '.tif', '.tiff', '.pdf') STREAMED = ('.png', '.pdf')
def generated_identity(order_id): def generated_identity(order_id):
@@ -81,16 +85,8 @@ def render_one(storage):
expiry = c.execute('SELECT min(created_at)+interval \'30 days\' AS e FROM dtf_local.uploads WHERE id=ANY(%s)', 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'] ([UUID(u) for u in item['uploads']],)).fetchone()['e']
by_id = {str(row['id']): row for row in uploads} by_id = {str(row['id']): row for row in uploads}
if any(row['size'] > LARGE_SOURCE_BYTES for row in uploads): if any(row['size'] > LARGE_SOURCE_BYTES and not row['name'].lower().endswith(STREAMED) for row in uploads):
original = whole_sheet(item, by_id) finish(job, 'manual', {'reason': f'arquivo acima de {LARGE_SOURCE_BYTES // 1048576} MB que não é PNG nem PDF: '
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'}) 'monte a folha a partir do original'})
audit('print_file_manual', order=str(job['order_id']), item=job['item_index']) audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
return True return True
@@ -105,41 +101,49 @@ def render_one(storage):
final = job['attempts'] + 1 >= MAX_ATTEMPTS final = job['attempts'] + 1 >= MAX_ATTEMPTS
finish(job, 'failed' if final else 'pending', {'error': type(exc).__name__}) finish(job, 'failed' if final else 'pending', {'error': type(exc).__name__})
return True return True
path, name, size, detail = result scratch, parts, detail = result
stored = []
try: try:
for path, name in parts:
uid = uuid4() uid = uuid4()
key = f'originals/{uid}' key = f'originals/{uid}'
storage.store(key, path, 'application/pdf') 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: 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: with connect() as c:
for uid, name, size, key in stored:
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete, c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state,scan_reason,scanned_at) expires_at,scan_state,scan_reason,scanned_at)
VALUES(%s,%s,%s,%s,%s,'',true,%s,'clean','generated from scanned artwork',now())''', VALUES(%s,%s,%s,%s,%s,'',true,%s,'clean','generated from scanned artwork',now())''',
(uid, generated_identity(job['order_id']), name, size, key, expiry)) (uid, generated_identity(job['order_id']), name, size, key, expiry))
c.execute('''UPDATE dtf_local.print_files SET status='ready', upload_id=%s, detail=%s, 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'])) finished_at=now() WHERE id=%s''', (stored[0][0], Jsonb(detail), job['id']))
audit('print_file_ready', order=str(job['order_id']), item=job['item_index']) 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))
audit('print_file_ready', order=str(job['order_id']), item=job['item_index'], parts=len(stored))
return True return True
def whole_sheet(item, uploads): def store_tiles(storage, folder, upload_id):
"""The original, when the item is one finished sheet placed whole, once, """A part's pieces for the Kanban's viewer (item 7), beside the files the
unrotated and unmirrored, across the film: then it is the print file.""" storage policy lets the service write: originals/tiles/<upload>/<level>/<index>.png."""
spec = item.get('production') or {} if not os.path.isdir(folder):
sources, placements = spec.get('sources') or [], spec.get('placements') or [] return
if len(item['uploads']) != 1 or len(sources) != 1 or len(placements) != 1: for level in sorted(os.listdir(folder)):
return None for strip in sorted(os.listdir(os.path.join(folder, level))):
source, place = sources[0], placements[0] storage.store(f'originals/tiles/{upload_id}/{level}/{strip}', os.path.join(folder, level, strip), 'image/png')
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 file_prefix(number, item_index): def file_prefix(number, item_index):
@@ -156,6 +160,10 @@ def footer(job, item):
count = len(job['snapshot']['items']) count = len(job['snapshot']['items'])
day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y') day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y')
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',') 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 pedido {purchase_order(proof_of)}',
f'Item {job["item_index"] + 1}/{count}', day])
fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}', fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}',
f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m'] 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 # A mirrored artwork (UV only) is named on the sheet, for the room to see
@@ -166,30 +174,34 @@ def footer(job, item):
def produce(storage, job, item, uploads): def produce(storage, job, item, uploads):
"""Fetch the item's artwork and render it. Returns (pdf path, name, size, evidence).""" """Fetch the item's artwork and render it. Returns (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']: for upload_id in item['uploads']:
row = uploads.get(upload_id) row = uploads.get(upload_id)
if not row or row['scan_state'] != 'clean': if not row or row['scan_state'] != 'clean':
raise Unsupported('um arquivo original está ausente ou não foi liberado pelo antivírus') raise Unsupported('um arquivo original está ausente ou não foi liberado pelo antivírus')
if row['purged_at'] or row['expired']: if row['purged_at'] or row['expired']:
raise Unsupported('um arquivo original passou do prazo de guarda') raise Unsupported('um arquivo original passou do prazo de guarda')
number = job['number'] output = tempfile.mkdtemp(prefix='print-')
name = f'{file_prefix(number, job["item_index"])}.pdf' try:
with tempfile.TemporaryDirectory(prefix='print-') as scratch: with tempfile.TemporaryDirectory(prefix='print-') as scratch:
files = {} files = {}
for index, upload_id in enumerate(item['uploads']): for index, upload_id in enumerate(item['uploads']):
local = os.path.join(scratch, f'source-{index}') local = os.path.join(scratch, f'source-{index}')
storage.fetch(uploads[upload_id]['object_key'], local) storage.fetch(uploads[upload_id]['object_key'], local)
files[index] = (local, uploads[upload_id]['name']) files[index] = (local, uploads[upload_id]['name'])
handle, output = tempfile.mkstemp(prefix='print-', suffix='.pdf') proof_of = job['snapshot'].get('proof_of')
try: # A proof card's file: the first 30 cm, DTF-N-item-1-prova.png (app/proof.py).
with os.fdopen(handle, 'wb') as out: prefix = (file_prefix(proof_of, job['item_index']) + '-prova' if proof_of
detail = render(item, files, out, f'Pedido {number} - item {job["item_index"] + 1}', else file_prefix(job['number'], job['item_index']))
footer=footer(job, item)) parts, detail = render(item, files, output, prefix, footer=footer(job, item), tiles=True,
limit_cm=PROOF_SHEET_CM if proof_of else None)
except BaseException: except BaseException:
os.unlink(output) shutil.rmtree(output, ignore_errors=True)
raise raise
return output, name, os.path.getsize(output), detail return output, parts, detail
def finish(job, status, detail): def finish(job, status, detail):

521
app/printpng.py Normal file
View File

@@ -0,0 +1,521 @@
"""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 _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):
"""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).
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)
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 the film's first `limit_cm` (app/proof.py).
cuts = ([Decimal(0), min(Decimal(str(production['height_cm'])), Decimal(str(limit_cm)))] 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

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

@@ -11,6 +11,9 @@ marks "Prova OK" once the proof is checked, and without it the order does not
reach Finalizado. reach Finalizado.
""" """
from decimal import Decimal from decimal import Decimal
from uuid import NAMESPACE_URL, uuid4, uuid5
from psycopg.types.json import Jsonb
PROOF_ABOVE_METRES = Decimal('10') PROOF_ABOVE_METRES = Decimal('10')
CUSTOMER_NOTE = ('O cliente pediu uma prova antes de imprimir: mande a foto da prova pelo WhatsApp ' CUSTOMER_NOTE = ('O cliente pediu uma prova antes de imprimir: mande a foto da prova pelo WhatsApp '
@@ -24,3 +27,50 @@ def billed_metres(snapshot):
def needs_proof(snapshot): def needs_proof(snapshot):
"""Whether the order prints a proof first: asked for, or above 10 m.""" """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 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 30 cm, DTF-N-item-1-prova.png, 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('30')
# 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
snapshot = {**parent['snapshot'], 'items': parent['snapshot']['items'][:MAX_PROOFS],
'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']))

View File

@@ -22,7 +22,7 @@ from psycopg.types.json import Jsonb
from . import payments from . import payments
from .proof import PROOF_ABOVE_METRES from .proof import PROOF_ABOVE_METRES
from .core.models import PRODUCTION_VERSIONS from .core.models import PRODUCTION_VERSIONS
from .core.pricing import is_manual, manual_extra_cents, price from .core.pricing import bill_splits, is_manual, manual_extra_cents, price
from .runtime import freight, upload_row from .runtime import freight, upload_row
from .scanning import require_clean from .scanning import require_clean
@@ -64,7 +64,7 @@ def approve(c, row, items, reviewer):
for item, original in zip(items, draft['items']): for item, original in zip(items, draft['items']):
if item.mode != original['mode'] or list(map(str, item.uploads)) != original['uploads']: if item.mode != original['mode'] or list(map(str, item.uploads)) != original['uploads']:
raise HTTPException(422, 'O produto e os arquivos não podem mudar na revisão.') raise HTTPException(422, 'O produto e os arquivos não podem mudar na revisão.')
if item.production.model_dump(mode='json') != original['production'] or item.quality_status != original['quality_status'] or item.quality_acknowledged != original['quality_acknowledged'] 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.') raise HTTPException(422, 'A montagem e a confirmação do cliente não podem mudar na revisão.')
names = {} names = {}
for upload_id in item.uploads: for upload_id in item.uploads:
@@ -72,11 +72,17 @@ def approve(c, row, items, reviewer):
require_clean(upload) require_clean(upload)
names[str(upload_id)] = upload['name'] names[str(upload_id)] = upload['name']
extra = manual_extra_cents() if is_manual(original, names) else 0 extra = manual_extra_cents() if is_manual(original, names) else 0
priced.append({**price(item.mode, str(item.metres), item.grade, extra), priced.append({**price(item.mode, str(item.metres), item.grade, extra,
minimum=Decimal('0') if item.split else Decimal('1')),
'uploads': original['uploads'], 'production': original['production'], 'uploads': original['uploads'], 'production': original['production'],
'quality_status': original['quality_status'], 'quality_status': original['quality_status'],
'quality_acknowledged': original['quality_acknowledged'], 'quality_acknowledged': original['quality_acknowledged'],
'residue_accepted': original.get('residue_accepted', 0)}) 'residue_accepted': original.get('residue_accepted', 0),
**({'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 {}),
**({'split': original['split']} if original.get('split') else {})})
bill_splits(priced)
metres = sum(Decimal(i['billed_metres']) for i in priced) metres = sum(Decimal(i['billed_metres']) for i in priced)
try: try:
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''), quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),

View File

@@ -11,6 +11,7 @@ import io
import unicodedata import unicodedata
from datetime import datetime from datetime import datetime
from .core.pricing import sheet_label
from .printfile import Name, PdfWriter, deflate, serialize, _HELVETICA, _HELVETICA_BOLD from .printfile import Name, PdfWriter, deflate, serialize, _HELVETICA, _HELVETICA_BOLD
from .printjobs import LOCAL, file_prefix from .printjobs import LOCAL, file_prefix
@@ -95,7 +96,7 @@ def lines(order, paid_with, issued):
out.append(('Produto', 7.5, False, 10)) out.append(('Produto', 7.5, False, 10))
for item in snapshot.get('items') or []: for item in snapshot.get('items') or []:
metres = str(item.get('billed_metres') or item.get('metres') or '').replace('.', ',') metres = str(item.get('billed_metres') or item.get('metres') or '').replace('.', ',')
out += [(part, 9.5, False, 2) for part in wrap(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))} — {metres} m", 9.5)] out += [(part, 9.5, False, 2) for part in wrap(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))}{sheet_label(item)} — {metres} m", 9.5)]
out += [('Valor', 7.5, False, 10), (money(snapshot.get('total_cents') or 0), 12, True, 1), 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), ('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), (f"Emitido em {issued.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')}", 8.5, False, 10),

View File

@@ -103,8 +103,24 @@ def order_code(order_id):
return str(order_id).replace('-', '')[:8].upper() 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 from .quote_review import review_reason # it imports this module
if not known:
order = c.execute('SELECT id,number,state FROM dtf_local.orders WHERE quote_id=%s', (row['id'],)).fetchone() 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 latest payment attempt, so the payment page can tell a refused card
# (the notification updates it) from one still waiting. # (the notification updates it) from one still waiting.

View File

@@ -203,6 +203,36 @@ 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) CREATE INDEX IF NOT EXISTS print_files_open ON dtf_local.print_files(created_at)
WHERE status IN ('pending','rendering'); 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. -- 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; ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS back boolean NOT NULL DEFAULT false;
@@ -423,6 +453,37 @@ 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_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_at timestamptz;
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_answered boolean NOT NULL DEFAULT false; 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 · -- The machine of whoever moved a card, as it was named then: "Imprimindo ·
-- Thales · máquina2". -- Thales · máquina2".
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS machine text; ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS machine text;

View File

@@ -39,6 +39,9 @@ def cleanup():
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 50""").fetchall() ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 50""").fetchall()
for row in rows: for row in rows:
storage.discard(row['object_key'],row['multipart_id'],row['complete']) 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('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s', (row['id'],))
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (row['id'],)) c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (row['id'],))
c.execute('DELETE FROM dtf_local.sessions WHERE expires_at<=now()') c.execute('DELETE FROM dtf_local.sessions WHERE expires_at<=now()')

View File

@@ -579,6 +579,31 @@ pydantic-core==2.46.5 \
--hash=sha256:fc8515076c11f3cfdf4fb142dcca0fe384b1230a3b5415458ac84f3e0903ec13 \ --hash=sha256:fc8515076c11f3cfdf4fb142dcca0fe384b1230a3b5415458ac84f3e0903ec13 \
--hash=sha256:ff218293c9c806138dca139765e3b067621be52bcd93cdc14c7711be7ddc90a9 --hash=sha256:ff218293c9c806138dca139765e3b067621be52bcd93cdc14c7711be7ddc90a9
# via pydantic # 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 \ python-dateutil==2.9.0.post0 \
--hash=sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3 \ --hash=sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3 \
--hash=sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427 --hash=sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427

View File

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

View File

@@ -159,6 +159,16 @@ try{
stale:/14,90|conforme a nota|desconto|escada|menor preço da tabela/i.test(document.body.textContent)};})()`), 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'], {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}); 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"]'); await click('[data-modo="file"]');
// Opening a product paints on the next frame; on a busy runner the check // Opening a product paints on the next frame; on a busy runner the check
// must wait for it rather than race it. // must wait for it rather than race it.
@@ -340,13 +350,10 @@ try{
await waitFor(()=>evaluate(`$('aoVivo').textContent.includes('ponto de recorte') && itemAtual===null`),'residue stops the order'); 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); 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'); 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, // A ready sheet takes no acceptance (Dropstar, 2026-11-03): the designer
// the sheet goes on and the item says how many dots were accepted. // cannot clean a closed sheet, so the dot always sends it back.
assert.equal(await evaluate(`$('lista').textContent.includes('Esta arte tem 1 ponto menor que 2 mm. Estou ciente e aceito imprimir assim')`),true); assert.deepEqual(await evaluate(`({box:!!document.querySelector('[data-residuo]'),
await click('[data-residuo="0"]'); text:$('lista').textContent.includes('Estou ciente'),stopped:itemAtual===null})`),{box:false,text:false,stopped:true});
await waitFor(()=>evaluate(`itemAtual?.residueAccepted===1 && !$('lista').textContent.includes('Sobrou 1 ponto')`),'accepted residue lets the sheet go on');
await click('[data-residuo="0"]');
await waitFor(()=>evaluate(`itemAtual===null && $('aoVivo').textContent.includes('ponto de recorte')`),'unticked, the residue stops it again');
await evaluate(`folhas=[];pintaFolha()`); await evaluate(`folhas=[];pintaFolha()`);
await evaluate('sendSheet({fundo:true})'); 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'); await waitFor(()=>evaluate(`folhas[0]?.an?.fundoChapado===true && itemAtual===null && $('aoVivo').textContent.includes('fundo transparente')`),'solid background stops the order');

View File

@@ -9,17 +9,29 @@ Kanban until someone records what was done.
Run inside the API container (it needs Pillow): python -m tests.print_file_test Run inside the API container (it needs Pillow): python -m tests.print_file_test
""" """
import io import io
import re
import time import time
from urllib.request import urlopen from urllib.request import urlopen
from uuid import uuid4 from uuid import uuid4
from PIL import Image from PIL import Image
from app.core import db
from tests.payment_test import deliver from tests.payment_test import deliver
from tests.smoke_test import Client, approved_quote as approval, upload_bytes 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'} CUSTOMER = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'print-test@example.test'}
@@ -82,15 +94,27 @@ def run():
order = paid_order(client, loose_item(uid)) order = paid_order(client, loose_item(uid))
order, row = wait_print(client, order['id'], 'ready') order, row = wait_print(client, order['id'], 'ready')
assert row['detail']['placements'] == 2 and row['detail']['min_dpi'] == round(600 / (20 / 2.54)) 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) # A 300 DPI PNG on a transparent background (item 13): the layout's 10 cm
with urlopen(link['url'], timeout=30) as response: # and the 1,5 cm footer band, outside the billed length.
pdf = response.read() film = download_png(client, row['upload_id'])
assert pdf.startswith(b'%PDF-') and pdf.rstrip().endswith(b'%%EOF') assert film.size == (px(57), px(10) + px(1.5)), film.size
width, height = map(float, re.search(rb'/MediaBox \[0 0 ([\d.]+) ([\d.]+)\]', pdf).groups()) assert [p['name'] for p in row['parts']] == ['DTF-%d-item-1.png' % order['number']], row['parts']
# The layout's 10 cm and the 1,5 cm footer band, outside the billed length. for copy in range(2):
assert abs(width - 57 * PT_PER_CM) < 0.01 and abs(height - 11.5 * PT_PER_CM) < 0.01, (width, height) 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'] 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 # The automatic folder, downloading on arrival, gets the generated file
# before anyone approves it; at the queue only, it does not. # before anyone approves it; at the queue only, it does not.
@@ -140,16 +164,96 @@ def run():
'note': 'again'}, operator=True, expected=409) 'note': 'again'}, operator=True, expected=409)
print('PASS: generated file approved as final without re-uploading; order queued for printing') 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.
tag = uuid4().hex[:6]
machine = client.call('/operator/machines', {'name': f'Hot {tag}', 'products': ['textil']}, operator=True)['id']
try:
client.call('/operator/orders/' + oid + '/machine', {'machine_id': machine}, operator=True)
# 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_upload = upload_bytes(client, artwork('PDF'), name='LOCAL-PRINT-TEST.pdf')
pdf_order = paid_order(client, loose_item(pdf_upload)) pdf_order = paid_order(client, loose_item(pdf_upload))
_, pdf_row = wait_print(client, pdf_order['id'], 'ready') _, 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 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) drawn = download_png(client, pdf_row['upload_id'])
with urlopen(link['url'], timeout=30) as response: red = drawn.getpixel((px(10), px(5)))
generated = response.read() assert red[3] == 255 and red[0] > 200 and red[1] < 60, red
assert b'/Subtype /Form' in generated or b'/Subtype/Form' in generated print('PASS: PDF artwork drawn into the PNG print file at 300 DPI')
print('PASS: PDF artwork generated as a vector print file')
# 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['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'}
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 = upload_bytes(client, b'LOCAL PROOF FINAL FIXTURE', order_id=parent['id'])
version = 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)['version']
version = client.call('/operator/orders/' + parent['id'] + '/move', {'state': 'tra', 'version': version},
operator=True)['version']
held = client.call('/operator/orders/' + parent['id'] + '/move', {'state': 'imp', 'version': version},
operator=True, expected=409)
assert 'Aguardando prova' in held['detail'], 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 [o for o in board if o['id'] == card['id']], 'an answered proof card leaves the board'
# 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', mine
print('PASS: an order with a proof waits for its proof card, which is answered OK or rejected in Revisão')
# A customer cannot see or reuse another order's generated file. # A customer cannot see or reuse another order's generated file.
other = Client() other = Client()

View File

@@ -18,7 +18,12 @@ def run():
with connect() as c: 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)', 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)) (uid,uuid4(),'LOCAL-RETENTION-TEST.txt',len(b'LOCAL RETENTION TEST'),key,upload,expiry))
# 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() 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: with connect() as c:
assert c.execute('SELECT purged_at FROM dtf_local.uploads WHERE id=%s',(ids[0],)).fetchone()['purged_at'] 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'] assert not c.execute('SELECT purged_at FROM dtf_local.uploads WHERE id=%s',(ids[1],)).fetchone()['purged_at']

View File

@@ -214,6 +214,29 @@ def run():
kept=client.call('/quotes',accepted) kept=client.call('/quotes',accepted)
assert kept['status']=='approved' assert kept['status']=='approved'
assert client.call('/quotes/'+kept['id'])['approved']['items'][0]['residue_accepted']==3 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 # 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. # is checked against the file like any other, and this one cannot be.
claimed={**item_spec('avulsa','2.75',0,uid),'grade':90} claimed={**item_spec('avulsa','2.75',0,uid),'grade':90}
@@ -249,10 +272,17 @@ def run():
files=[{'item_index':i,'upload_id':upload_bytes(client,b'LOCAL FINAL FIXTURE '+str(i).encode(),order_id=oid)} for i in range(4)] files=[{'item_index':i,'upload_id':upload_bytes(client,b'LOCAL FINAL FIXTURE '+str(i).encode(),order_id=oid)} for i in range(4)]
result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True) result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True)
version=result['version'] version=result['version']
if state=='fin': if state=='imp':
# Above 10 m the proof comes first: no Finalizado before Prova OK (app/proof.py). # Above 10 m the proof comes first (app/proof.py): the order waits
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':version},operator=True,expected=409) # outside the queue for Prova OK on its proof card in Revisão.
version=client.call('/operator/orders/'+oid+'/proof',{},operator=True)['version'] held=client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version},operator=True,expected=409)
assert 'Aguardando prova' in held['detail'], held
card=next(o for o in client.call('/operator/board',operator=True)['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+=1
moved=client.call('/operator/orders/'+oid+'/move',{'state':state,'version':version,'reason':'Local test correction' if state=='cor' else ''},operator=True) moved=client.call('/operator/orders/'+oid+'/move',{'state':state,'version':version,'reason':'Local test correction' if state=='cor' else ''},operator=True)
version+=1;assert moved['version']==version version+=1;assert moved['version']==version
client.call('/operator/orders/'+oid+'/move',{'state':'rec','version':0},operator=True,expected=409) client.call('/operator/orders/'+oid+'/move',{'state':'rec','version':0},operator=True,expected=409)

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 import unittest
from app.printjobs import whole_sheet
from app.scanning import check_large, format_matches, real_name 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): class FormatTest(unittest.TestCase):
def test_bytes_must_match_the_name(self): def test_bytes_must_match_the_name(self):

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

@@ -153,6 +153,11 @@ def run():
assert (me['machine_question'], me['machine_answered'], me['machine']) == ('required', False, None), me 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 {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']] 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) op.call(f'/operator/orders/{uv_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403)
with db.connect() as c: with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='imp' WHERE id=%s", (uv_o,)) c.execute("UPDATE dtf_local.orders SET state='imp' WHERE id=%s", (uv_o,))
@@ -194,7 +199,8 @@ def run():
seller.call(f'/operator/orders/{textil_o}/machine', {'machine_id': None}, expected=403) 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) 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. # The seller only views the board (D-30): no order registered by hand either.
assert seller.call('/operator/me')['can'] == ['view'] # The seller only views, but answers a proof card (Dropstar, 2026-11-03).
assert seller.call('/operator/me')['can'] == ['proof', 'view']
seller.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=403) 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 # Financeiro (Dropstar, 2026-10-30): the board, Pagamentos, Números and
# Cotações, and cancels an order with its reason; moves nothing. # Cotações, and cancels an order with its reason; moves nothing.
@@ -399,7 +405,7 @@ def run():
cap = admin.call('/operator/machines', {'name': f'Cap {tag}', 'products': ['textil']})['id'] cap = admin.call('/operator/machines', {'name': f'Cap {tag}', 'products': ['textil']})['id']
machines.append(cap) machines.append(cap)
with db.connect() as c: 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) made.extend(pulled)
for _, oid in pulled: for _, oid in pulled:
upload = uuid4() upload = uuid4()
@@ -410,7 +416,7 @@ def run():
VALUES(%s,%s,%s,0,'final','ok','t')''', (uuid4(), oid, upload)) 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", c.execute("UPDATE dtf_local.orders SET state='tra', machine_id=%s, machine_chosen=true WHERE id=%s",
(cap, oid)) (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, pull = lambda oid, version=0: su.call(f'/operator/orders/{oid}/move', {'state': 'imp', 'version': version,
'reason': ''}, operator=True) 'reason': ''}, operator=True)
running = pull(first) running = pull(first)
@@ -418,6 +424,25 @@ def run():
refused = su.call(f'/operator/orders/{third}/move', {'state': 'imp', 'version': 0, 'reason': ''}, refused = su.call(f'/operator/orders/{third}/move', {'state': 'imp', 'version': 0, 'reason': ''},
operator=True, expected=409) operator=True, expected=409)
assert refused['detail'] == f'Cap {tag} já tem 2 em Imprimindo.', refused 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) loaded = su.call('/operator/board', operator=True)
board = {o['id']: o for o in loaded['orders']} board = {o['id']: o for o in loaded['orders']}
assert (board[first]['printing'], board[second_in]['printing'], board[third]['printing']) == \ assert (board[first]['printing'], board[second_in]['printing'], board[third]['printing']) == \

View File

@@ -21,6 +21,8 @@
quality:item.qualityStatus, quality:item.qualityStatus,
acknowledged:item.qualityAcknowledged, acknowledged:item.qualityAcknowledged,
residue:item.residueAccepted||0, 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})) files:(item.localFiles||[]).map(file=>({name:file.name,size:file.size,lastModified:file.lastModified}))
}))}); }))});
} }
@@ -106,8 +108,16 @@
const amount=document.createElement('b'); amount.textContent=value; const amount=document.createElement('b'); amount.textContent=value;
row.append(name,amount); return row; row.append(name,amount); return row;
}; };
const rows = approved.items.map(item => linha( // The sheets of a split (item 17) are one line, as in the cart.
(MODOS[item.mode]?.tit || item.mode)+' · '+fmtM(Number(item.billed_metres))+' m', rs(item.total_cents/100))); 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 pickup = approved.freight.service === 'pickup';
const prazo = approved.freight.days ? ' · até '+approved.freight.days+' dias úteis' : ''; const prazo = approved.freight.days ? ' · até '+approved.freight.days+' dias úteis' : '';
rows.push(linha(pickup ? 'Retirada em Franca' : (approved.freight.description || 'Frete')+prazo, rows.push(linha(pickup ? 'Retirada em Franca' : (approved.freight.description || 'Frete')+prazo,
@@ -327,7 +337,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.'); 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=[]; const items=[];
pintaEnvio(); 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.'); if (!item.localFiles?.length) throw new Error('Selecione novamente os arquivos deste item.');
const uploads=[]; const uploads=[];
for (const [index,file] of item.localFiles.entries()) { for (const [index,file] of item.localFiles.entries()) {
@@ -341,7 +356,10 @@
production:{...item.production,sources:item.production.sources.map((source,index)=>({ production:{...item.production,sources:item.production.sources.map((source,index)=>({
upload_id:uploads[index],...source}))}, upload_id:uploads[index],...source}))},
quality_status:item.qualityStatus,quality_acknowledged:item.qualityAcknowledged, 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.split?{split:item.split}:{})});
} }
const service = entrega.tipo==='retira' ? 'pickup' : entrega.servico; 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.'); if (!service) throw new Error('A entrega ainda não está disponível. Escolha a retirada em Franca.');

View File

@@ -947,6 +947,13 @@ h2 em{font-style:normal;color:var(--laranja)}
</div> </div>
</aside> </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"> <dialog class="ampliaDlg" id="ampliaDlg" aria-labelledby="ampliaTit">
<div class="ampliaCab"><b id="ampliaTit">Sua folha</b> <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> <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>

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

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

After

Width:  |  Height:  |  Size: 287 B

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

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

File diff suppressed because it is too large Load Diff

View File

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

File diff suppressed because it is too large Load Diff

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

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

After

Width:  |  Height:  |  Size: 46 KiB

View File

@@ -29,6 +29,8 @@ function icone(nome){
} }
const PRODUTO={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas', const PRODUTO={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',
uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'}; uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'};
// Artes avulsas que o Site separou por traço (item 17): uma folha por item.
const nomeItem=item=>(PRODUTO[item.mode]||item.mode)+(item.split?' · folha '+item.split.part+' de '+item.split.of:'');
// The order's steps as the customer sees them (Dropstar's flow, 2026-10-23). // The order's steps as the customer sees them (Dropstar's flow, 2026-10-23).
const TRILHA=['rec','tra','imp','rev','fin']; const TRILHA=['rec','tra','imp','rev','fin'];
const TAMANHO=10; const TAMANHO=10;
@@ -199,7 +201,7 @@ function itensPedido(snapshot){
const ul=node('ul',null,'itensPed'); const ul=node('ul',null,'itensPed');
for(const item of snapshot.items){ for(const item of snapshot.items){
const li=node('li'); const li=node('li');
li.append(node('span',PRODUTO[item.mode]||item.mode,'nome'),node('span',metros(item.billed_metres),'qt'),node('b',money(item.total_cents))); li.append(node('span',nomeItem(item),'nome'),node('span',metros(item.billed_metres),'qt'),node('b',money(item.total_cents)));
ul.append(li); ul.append(li);
} }
const f=snapshot.freight; const f=snapshot.freight;
@@ -247,7 +249,7 @@ async function details(id,container,criado){
if(order.state==='cor'){ if(order.state==='cor'){
const form=node('form',null,'secao correcaoForm');form.append(node('h4','Enviar arte corrigida')); const form=node('form',null,'secao correcaoForm');form.append(node('h4','Enviar arte corrigida'));
const inputs=order.snapshot.items.map((item,index)=>{ const inputs=order.snapshot.items.map((item,index)=>{
const label=node('label',(index+1)+'. '+(PRODUTO[item.mode]||item.mode)); const label=node('label',(index+1)+'. '+nomeItem(item));
const input=node('input');input.type='file';input.multiple=true;input.dataset.item=index; const input=node('input');input.type='file';input.multiple=true;input.dataset.item=index;
form.append(label,input);return input; form.append(label,input);return input;
}); });

View File

@@ -81,13 +81,17 @@ function pintaPedido(){
} }
// Um preço por produto (Dropstar, 23/10/2026): a nota aparece, mas não entra na conta. // Um preço por produto (Dropstar, 23/10/2026): a nota aparece, mas não entra na conta.
// A arte avulsa como fonte da montagem: largura, comprimento, cópias e giro.
const fonteDaArte=x=>({kind:'artwork',width_cm:x.cm,length_cm:+(x.cm*propDe(x)).toFixed(4),
copies:x.q,rotation_degrees:x.giro||0,mirrored:!!x.esp,
measurement:(x.src||x.semPrevia)?'file':'customer'});
function carrinho(){ function carrinho(){
const base=precoMetro(), cob=cobrar(metros); const base=precoMetro(), cob=cobrarMontagem();
const extra=folhaManual()? TAXA_MANUAL : 0; const extra=folhaManual()? TAXA_MANUAL : 0;
const unit=base+extra, tot=cob*unit, sobra=+(cob-metros).toFixed(2); const unit=base+extra, tot=cob*unit, sobra=+(cob-metros).toFixed(2);
$('carr').classList.add('on'); $('carr').classList.add('on');
let l='<div class="l"><span>'+MODOS[modo].tit+'</span><b>'+rs(base)+'/m</b></div>'; let l='<div class="l"><span>'+MODOS[modo].tit+'</span><b>'+rs(base)+'/m</b></div>';
if(!ehFolha()) l += '<div class="l" style="color:#8D9AB0"><span>Montagem da folha</span><b>inclusa</b></div>'; if(!ehFolha()) l += '<div class="l" style="color:#8D9AB0"><span>'+(montagemFolhas?'Montagem em '+montagemFolhas.length+' folhas, pela espessura do traço':'Montagem da folha')+'</span><b>inclusa</b></div>';
if(extra) l += '<div class="l"><span>Arquivo aberto na mão</span><b>+'+rs(extra)+'/m</b></div>'; if(extra) l += '<div class="l"><span>Arquivo aberto na mão</span><b>+'+rs(extra)+'/m</b></div>';
l += '<div class="l"><span>Metragem'+(sobra>0.001?' · arredondada para 10 cm':'')+ l += '<div class="l"><span>Metragem'+(sobra>0.001?' · arredondada para 10 cm':'')+
'</span><b>'+fmtM(cob)+' m</b></div>'; '</span><b>'+fmtM(cob)+' m</b></div>';
@@ -99,10 +103,8 @@ function carrinho(){
? {kind:'sheet',width_cm:x.med?.larg||larguraFilme(),length_cm:+(x.m*100).toFixed(4), ? {kind:'sheet',width_cm:x.med?.larg||larguraFilme(),length_cm:+(x.m*100).toFixed(4),
copies:x.rep||1,rotation_degrees:0,mirrored:false, copies:x.rep||1,rotation_degrees:0,mirrored:false,
measurement:x.med?'file':'customer'} measurement:x.med?'file':'customer'}
: {kind:'artwork',width_cm:x.cm,length_cm:+(x.cm*propDe(x)).toFixed(4), : fonteDaArte(x));
copies:x.q,rotation_degrees:x.giro||0,mirrored:!!x.esp, let layout, partes=null;
measurement:(x.src||x.semPrevia)?'file':'customer'});
let layout;
if(ehFolha()){ if(ehFolha()){
let y=0; let y=0;
const placements=[]; const placements=[];
@@ -115,6 +117,14 @@ function carrinho(){
} }
}); });
layout={height_cm:+y.toFixed(4),placements}; layout={height_cm:+y.toFixed(4),placements};
}else if(montagemFolhas){
// Item 17: one order item per sheet, each with its files, layout and class.
partes=montagemFolhas.map((f,i)=>({rotulo:'Folha '+(i+1)+' · '+f.nome,
localFiles:f.artes.map(x=>x.f), fotos:f.artes.map(x=>x.fotoSrc||null),
metros:+(f.layout.height_cm/100).toFixed(4),
production:{version:3,film_width_cm:larguraFilme(),sources:f.artes.map(fonteDaArte),...f.layout},
residueAccepted:residuosDasArtes(f.artes), ...tracoDoItem(f.artes)}));
layout=null;
}else{ }else{
if(!montagemLayout) return; if(!montagemLayout) return;
layout=montagemLayout; layout=montagemLayout;
@@ -125,13 +135,16 @@ function carrinho(){
fotos:(ehFolha()?folhas:artes).map(x=>x.fotoSrc||null), fotos:(ehFolha()?folhas:artes).map(x=>x.fotoSrc||null),
ext:extDe(((ehFolha()?folhas:artes)[0]||{f:{name:''}}).f.name), ext:extDe(((ehFolha()?folhas:artes)[0]||{f:{name:''}}).f.name),
arquivos:(ehFolha()?folhas:artes).length, arquivos:(ehFolha()?folhas:artes).length,
production:{version:3,film_width_cm:larguraFilme(),sources,...layout}, production:layout?{version:3,film_width_cm:larguraFilme(),sources,...layout}:null,
partes,
qualityStatus:$('ciente').classList.contains('recusa')?'rejected': qualityStatus:$('ciente').classList.contains('recusa')?'rejected':
$('ciente').classList.contains('on')?'warning':nota===0?'unverified':'ok', $('ciente').classList.contains('on')?'warning':nota===0?'unverified':'ok',
qualityAcknowledged:false, qualityAcknowledged:false,
// The residue dots the customer accepted printing (Dropstar, 2026-10-29). // The residue dots the customer accepted printing (Dropstar, 2026-10-29).
residueAccepted:ehFolha()?residuosAceitos():0, residueAccepted:residuosAceitos(),
desc:fmtM(cob)+' m · '+rs(unit)+'/m · nota '+nota}; // The thinnest stroke and its contraction class (item 9), for the room.
...tracoDoItem(),
desc:(partes?partes.length+' folhas · ':'')+fmtM(cob)+' m · '+rs(unit)+'/m · nota '+nota};
pintaPedido(); pintaPedido();
previa(); previa();
} }

View File

@@ -85,6 +85,7 @@ const folhaTotalM=()=>folhas.reduce((t,x)=>t+(x.m||0)*(x.rep||1),0);
const PAR={file:'avulsa', avulsa:'file', uvfile:'uv', uv:'uvfile'}; const PAR={file:'avulsa', avulsa:'file', uvfile:'uv', uv:'uvfile'};
let montagemCm=0; // altura da folha montada pelo motor, em cm let montagemCm=0; // altura da folha montada pelo motor, em cm
let montagemLayout=null; // posições aprovadas de cada cópia, em cm let montagemLayout=null; // posições aprovadas de cada cópia, em cm
let montagemFolhas=null; // artes avulsas separadas por traço (item 17)
let montagemFolgaCm=0.5; // a menor folga da montagem na largura let montagemFolgaCm=0.5; // a menor folga da montagem na largura
const ZOOMS=[1,1.5,2,3,4]; let zoomI=0; // ampliação da montagem ao vivo const ZOOMS=[1,1.5,2,3,4]; let zoomI=0; // ampliação da montagem ao vivo
let pedido=[]; // itens já fechados · o pagamento é um só let pedido=[]; // itens já fechados · o pagamento é um só
@@ -155,6 +156,10 @@ function faltaLeitura(l){
const larguraFilme=()=>MODOS[modo].larg; const larguraFilme=()=>MODOS[modo].larg;
// cobrança proporcional: arredonda para cima em 10 cm · 2,75 m vira 2,80 m // cobrança proporcional: arredonda para cima em 10 cm · 2,75 m vira 2,80 m
const cobrar=m=>Math.max(MINIMO_M, Math.ceil(m*10)/10); const cobrar=m=>Math.max(MINIMO_M, Math.ceil(m*10)/10);
// Com as artes em folhas separadas por traço (item 17), cada folha arredonda
// a 10 cm e o mínimo de 1 m vale para a soma: o cliente não escolheu separar.
const cobrarFolhas=fs=>Math.max(MINIMO_M, +fs.reduce((t,f)=>t+Math.ceil(+(f.alturaCm/100).toFixed(4)*10)/10,0).toFixed(1));
const cobrarMontagem=()=>!ehFolha() && montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(metros);
const fmtM=m=>m.toFixed(2).replace('.',','); const fmtM=m=>m.toFixed(2).replace('.',',');
const cls=n=>n>=85?'ok':n>=50?'av':'er'; const cls=n=>n>=85?'ok':n>=50?'av':'er';
const dpiDe=a=>a.cm>0? (a.giro?a.py:a.px)/(a.cm/2.54) : 0; const dpiDe=a=>a.cm>0? (a.giro?a.py:a.px)/(a.cm/2.54) : 0;

View File

@@ -426,6 +426,9 @@ function previaAoVivo(){
const prontas=artes.filter(a=>a.cm>0 && a.cm<=larguraFilme() && (a.src||a.semPrevia)); const prontas=artes.filter(a=>a.cm>0 && a.cm<=larguraFilme() && (a.src||a.semPrevia));
const W=Math.round(300*ZOOMS[zoomI]); const W=Math.round(300*ZOOMS[zoomI]);
$('vArea').classList.toggle('ampliado', zoomI>0); $('vArea').classList.toggle('ampliado', zoomI>0);
montagemFolhas=null;
const grupos=gruposDeTraco(prontas);
if(grupos.length>1){ montaFolhasDeTraco(grupos,W); $('vArea').scrollTop=0; return; }
desenhaMontagem($('vArea'), prontas, 0, W, $('vUso'), r=>{ desenhaMontagem($('vArea'), prontas, 0, W, $('vUso'), r=>{
montagemCm = r.alturaCm; // altura real da folha montada montagemCm = r.alturaCm; // altura real da folha montada
montagemFolgaCm = r.folgaCm ?? MARGEM_CM; montagemFolgaCm = r.folgaCm ?? MARGEM_CM;
@@ -439,6 +442,43 @@ function previaAoVivo(){
},140); },140);
} }
// Item 17 (Dropstar, 30/10/2026): artes de traço fino (C1, C2) e de traço
// grosso (C3) saem em folhas separadas, cada uma com a sua contração; o
// cliente não escolhe nada. Uma arte que o navegador não mediu fica nas finas.
const NOMES_TRACO=['traço fino','chapado'];
function gruposDeTraco(lista){
const grossa=a=>(tracoDaArte(a)||{}).classe==='C3';
const grupos=[lista.filter(a=>!grossa(a)), lista.filter(grossa)];
return grupos.every(g=>g.length) ? grupos : [lista];
}
function montaFolhasDeTraco(grupos,W){
const area=$('vArea'), versao=area.montagemVersao, feitas=[];
$('vUso').innerHTML='';
const painel=document.createElement('div'); painel.className='folhasTraco';
grupos.forEach((lista,i)=>{
const figura=document.createElement('figure'); figura.className='folhaTraco';
// Sem a nota de aproveitamento de cada folha: quem separou fomos nós.
const legenda=document.createElement('figcaption'), desenho=document.createElement('div'), uso=document.createElement('div');
legenda.textContent='Folha '+(i+1)+' · '+NOMES_TRACO[i];
figura.append(legenda,desenho); painel.append(figura);
desenhaMontagem(desenho, lista, 0, W, uso, r=>{
if(area.montagemVersao!==versao) return; // a montagem mudou nesse meio-tempo
legenda.textContent='Folha '+(i+1)+' · '+NOMES_TRACO[i]+' · '+fmtM(Math.ceil(+(r.alturaCm/100).toFixed(4)*10)/10)+' m';
feitas[i]={nome:NOMES_TRACO[i], artes:lista, alturaCm:r.alturaCm, folgaCm:r.folgaCm ?? MARGEM_CM,
layout:r.placements ? {height_cm:+r.alturaCm.toFixed(4), placements:r.placements} : null};
if(feitas.filter(Boolean).length<grupos.length) return;
montagemFolhas=feitas.every(f=>f.layout) ? feitas : null;
montagemLayout=null;
montagemCm=feitas.reduce((t,f)=>t+f.alturaCm,0);
montagemFolgaCm=Math.min(...feitas.map(f=>f.folgaCm));
$('vMt').textContent=montagemFolhas ? fmtM(cobrarFolhas(montagemFolhas))+' m' : '—';
resumoArtes();
agendaAvaliacao();
});
});
area.replaceChildren(painel);
}
function motivoNota(){ function motivoNota(){
if(!nota) return 'sem nota ainda · a conferência roda na sala antes de imprimir'; if(!nota) return 'sem nota ainda · a conferência roda na sala antes de imprimir';
if(!ehFolha()){ if(!ehFolha()){
@@ -457,7 +497,7 @@ function previa(){
// olhou dentro dela. Largura e metragem — o que de fato medimos — já aparecem // olhou dentro dela. Largura e metragem — o que de fato medimos — já aparecem
// na coluna ao lado e no carrinho. // na coluna ao lado e no carrinho.
if(ehFolha()){ $('prev').classList.remove('on'); return; } if(ehFolha()){ $('prev').classList.remove('on'); return; }
const cob=cobrar(metros), sobra=+(cob-metros).toFixed(2); const cob=cobrarMontagem(), sobra=+(cob-metros).toFixed(2);
$('pMt').innerHTML=fmtM(cob)+'<small> m</small>'; $('pMt').innerHTML=fmtM(cob)+'<small> m</small>';
$('pSub').textContent='folha montada por nós com as artes que você enviou'; $('pSub').textContent='folha montada por nós com as artes que você enviou';
const linhas=[ const linhas=[

View File

@@ -454,8 +454,9 @@ function chipsDaFolha(a,aceito){
// Resíduo e fundo chapado barram o pedido (Dropstar, 21/10/2026): o texto diz // Resíduo e fundo chapado barram o pedido (Dropstar, 21/10/2026): o texto diz
// quantos pontos, onde estão e o que fazer, sem "arquivo com problema". O // quantos pontos, onde estão e o que fazer, sem "arquivo com problema". O
// resíduo o cliente pode aceitar imprimir (29/10/2026); marcado, o aviso sai // resíduo o cliente pode aceitar imprimir (29/10/2026); marcado, o aviso sai
// e fica só o aceite. // e fica só o aceite. Só na arte avulsa (Dropstar, 03/11/2026): a folha pronta
function avisosDaFolha(a,nome,i,aceito){ // com resíduo volta, porque o designer não limpa folha fechada.
function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
if(a.grande) return ''; if(a.grande) return '';
if(a.fundoChapado) return /\.jpe?g$/i.test(nome||'') if(a.fundoChapado) return /\.jpe?g$/i.test(nome||'')
? '<p class="avisoF"><b>JPG não tem fundo transparente.</b> O que parece branco na tela sai branco '+ ? '<p class="avisoF"><b>JPG não tem fundo transparente.</b> O que parece branco na tela sai branco '+
@@ -467,12 +468,12 @@ function avisosDaFolha(a,nome,i,aceito){
const aceite='<label class="aceiteRes"><input type="checkbox" data-residuo="'+i+'"'+(aceito?' checked':'')+'>'+ const aceite='<label class="aceiteRes"><input type="checkbox" data-residuo="'+i+'"'+(aceito?' checked':'')+'>'+
'<span>Esta arte tem '+n+(varios?' pontos menores':' ponto menor')+' que 2 mm. Estou ciente e aceito '+ '<span>Esta arte tem '+n+(varios?' pontos menores':' ponto menor')+' que 2 mm. Estou ciente e aceito '+
'imprimir assim — '+(varios?'eles podem':'ele pode')+' se perder no recorte.</span></label>'; 'imprimir assim — '+(varios?'eles podem':'ele pode')+' se perder no recorte.</span></label>';
if(aceito) return aceite; if(aceitavel && aceito) return aceite;
return '<p class="avisoF"><b>'+(varios?'Sobraram ':'Sobrou ')+n+(varios?' pontos':' ponto')+ return '<p class="avisoF"><b>'+(varios?'Sobraram ':'Sobrou ')+n+(varios?' pontos':' ponto')+
' de recorte na sua folha.</b> São restos da remoção de fundo: não aparecem na sua tela, mas a '+ ' de recorte na sua folha.</b> São restos da remoção de fundo: não aparecem na sua tela, mas a '+
'impressora enxerga e imprime. Apague '+(varios?'os pontos':'o ponto')+' na ferramenta que você '+ 'impressora enxerga e imprime. Apague '+(varios?'os pontos':'o ponto')+' na ferramenta que você '+
'usou e envie de novo. '+(varios?'Os círculos vermelhos na prévia mostram onde estão.':'O círculo vermelho na prévia mostra onde está.')+ 'usou e envie de novo. '+(varios?'Os círculos vermelhos na prévia mostram onde estão.':'O círculo vermelho na prévia mostra onde está.')+
' Se '+(varios?'os pontos são':'o ponto é')+' da própria arte, marque abaixo.</p>'+aceite; (aceitavel?' Se '+(varios?'os pontos são':'o ponto é')+' da própria arte, marque abaixo.</p>'+aceite:'</p>');
} }
function detalhesDaFolha(a,i,aberto){ function detalhesDaFolha(a,i,aberto){
const linhas = a.grande const linhas = a.grande
@@ -664,6 +665,10 @@ function pintaArtes(){
n1(sug.cm)+' cm.<button data-usar="'+i+'" data-cm="'+sug.alvo+'">Usar '+n1(sug.alvo)+' cm</button></div>' n1(sug.cm)+' cm.<button data-usar="'+i+'" data-cm="'+sug.alvo+'">Usar '+n1(sug.alvo)+' cm</button></div>'
: ''; : '';
} }
// Item 4: the art's dots under 2 mm, with the same warning and acceptance as a sheet.
const an=analiseDaArte(a);
if(an && an.residuos) aviso+=avisosDaFolha({residuos:an.residuos},a.f.name,i,!!a.residuoAceito,true).replace('data-residuo=','data-residuoa=')
.replace('na sua folha','nesta arte');
if(a.semPrevia && !a.decodeError) if(a.semPrevia && !a.decodeError)
aviso+='<p class="repTxt"><b>Sem prévia para '+escapeHTML(extDe(a.f.name))+' deste tamanho.</b> '+ aviso+='<p class="repTxt"><b>Sem prévia para '+escapeHTML(extDe(a.f.name))+' deste tamanho.</b> '+
'A arte entra na folha pela medida, e a equipe confere antes de imprimir. Em PNG, a prévia aparece.</p>'; 'A arte entra na folha pela medida, e a equipe confere antes de imprimir. Em PNG, a prévia aparece.</p>';
@@ -700,6 +705,8 @@ function pintaArtes(){
el.dispatchEvent(new Event('change')); el.dispatchEvent(new Event('change'));
})); }));
$('lista').querySelectorAll('[data-rm]').forEach(b=>b.addEventListener('click',()=>{artes.splice(+b.dataset.rm,1);pintaArtes();})); $('lista').querySelectorAll('[data-rm]').forEach(b=>b.addEventListener('click',()=>{artes.splice(+b.dataset.rm,1);pintaArtes();}));
$('lista').querySelectorAll('[data-residuoa]').forEach(el=>el.addEventListener('change',()=>{
artes[+el.dataset.residuoa].residuoAceito=el.checked; pintaArtes();}));
$('lista').querySelectorAll('[data-cm]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.cm].cm=+i.value||0;pintaArtes();})); $('lista').querySelectorAll('[data-cm]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.cm].cm=+i.value||0;pintaArtes();}));
$('lista').querySelectorAll('[data-q]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.q].q=Math.max(1,Math.min(200,Math.floor(+i.value||1)));pintaArtes();})); $('lista').querySelectorAll('[data-q]').forEach(i=>i.addEventListener('change',()=>{artes[+i.dataset.q].q=Math.max(1,Math.min(200,Math.floor(+i.value||1)));pintaArtes();}));
$('lista').querySelectorAll('[data-cm], [data-q]').forEach(i=>i.addEventListener('input',()=>{ $('lista').querySelectorAll('[data-cm], [data-q]').forEach(i=>i.addEventListener('input',()=>{
@@ -728,6 +735,7 @@ function resumoArtes(){
const r=$('rA'), prontas=artes.filter(a=>a.cm>0 && a.cm<=larguraFilme() && (a.src||a.semPrevia)); const r=$('rA'), prontas=artes.filter(a=>a.cm>0 && a.cm<=larguraFilme() && (a.src||a.semPrevia));
if(!prontas.length){ r.style.display='none'; return; } if(!prontas.length){ r.style.display='none'; return; }
const m=montagemCm/100; // a mesma folha que aparece ao lado const m=montagemCm/100; // a mesma folha que aparece ao lado
const cob=montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(m);
const notas=prontas.map(a=>Math.max(6,Math.min(100,Math.round(dpiDe(a)/300*100)))); const notas=prontas.map(a=>Math.max(6,Math.min(100,Math.round(dpiDe(a)/300*100))));
const media=Math.round(notas.reduce((s,n)=>s+n,0)/notas.length), pior=Math.min(...notas); const media=Math.round(notas.reduce((s,n)=>s+n,0)/notas.length), pior=Math.min(...notas);
const falta=artes.length-prontas.length; const falta=artes.length-prontas.length;
@@ -736,8 +744,8 @@ function resumoArtes(){
'<div class="r"><span>qualidade média</span><b style="color:'+ '<div class="r"><span>qualidade média</span><b style="color:'+
(media>=85?'var(--verde)':media>=50?'var(--laranja)':'var(--vermelho)')+'">'+media+'%</b></div>'+ (media>=85?'var(--verde)':media>=50?'var(--laranja)':'var(--vermelho)')+'">'+media+'%</b></div>'+
(pior<media?'<div class="r"><span>a pior arte</span><b>'+pior+'%</b></div>':'')+ (pior<media?'<div class="r"><span>a pior arte</span><b>'+pior+'%</b></div>':'')+
(m>0?'<div class="r"><span>folha montada</span><b>'+fmtM(m)+' m</b></div>'+ (m>0?'<div class="r"><span>'+(montagemFolhas?montagemFolhas.length+' folhas montadas':'folha montada')+'</span><b>'+fmtM(m)+' m</b></div>'+
(cobrar(m)>m+0.001?'<div class="r"><span>cobrança</span><b>'+fmtM(cobrar(m))+ (cob>m+0.001?'<div class="r"><span>cobrança</span><b>'+fmtM(cob)+
' m'+(cobrar(m)===MINIMO_M?' · mínimo':'')+'</b></div>':''):'')+ ' m'+(cob===MINIMO_M?' · mínimo':'')+'</b></div>':''):'')+
(falta?'<div class="r" style="color:var(--laranja)"><span>faltam informar</span><b>'+falta+'</b></div>':''); (falta?'<div class="r" style="color:var(--laranja)"><span>faltam informar</span><b>'+falta+'</b></div>':'');
} }

View File

@@ -7,10 +7,56 @@
// transparente. Só vale para o que o navegador conferiu. O resíduo que o // transparente. Só vale para o que o navegador conferiu. O resíduo que o
// cliente aceita imprimir (Dropstar, 29/10/2026: às vezes os pontos são da // cliente aceita imprimir (Dropstar, 29/10/2026: às vezes os pontos são da
// arte) não barra; o fundo chapado barra sempre. // arte) não barra; o fundo chapado barra sempre.
const residuoAceito=x=>!!(x.residuoAceito && x.an && x.an.residuos); // A folha pronta não aceita resíduo (Dropstar, 03/11/2026): só a arte avulsa.
const residuoAceito=()=>false;
const folhaBarrada=x=>!!(x.an && !x.an.grande && (x.an.fundoChapado || (x.an.residuos && !residuoAceito(x)))); const folhaBarrada=x=>!!(x.an && !x.an.grande && (x.an.fundoChapado || (x.an.residuos && !residuoAceito(x))));
// Quantos pontos o cliente aceitou imprimir, somadas as folhas: vai no item. // Quantos pontos o cliente aceitou imprimir, somadas as folhas: vai no item.
const residuosAceitos=()=>folhas.filter(residuoAceito).reduce((t,x)=>t+x.an.residuos,0); // the sheet of loose art inherits what each artwork accepted
const residuosDasArtes=lista=>lista.filter(a=>a.residuoAceito).reduce((t,a)=>t+((analiseDaArte(a)||{}).residuos||0),0);
const residuosAceitos=()=>ehFolha()
? folhas.filter(residuoAceito).reduce((t,x)=>t+x.an.residuos,0)
: residuosDasArtes(artes);
// Item 16 (Dropstar, 03/11/2026): um detalhe fino pequeno que leva a arte
// inteira para C1, numa arte quase toda chapada. Os três ao mesmo tempo: o
// menor traço até 4 px, pelo menos 60% da tinta em áreas de 20 px ou mais e
// no máximo 10% da tinta em traços de até 4 px.
const mista=t=>!!(t && t.px<=4 && t.largos>=0.6 && t.finos<=0.10);
const tracoDoArquivo=x=>ehFolha()?x.an&&x.an.traco:tracoDaArte(x);
const TEXTO_MISTA={
arte:'Esta arte tem traços finos e áreas chapadas no mesmo arquivo. O branco por baixo precisa de ajuste diferente pra cada um. '+
'Vamos proteger os traços finos; as áreas chapadas podem mostrar uma borda branca muito fina. Quer evitar? Suba esta arte em dois '+
'arquivos, um com os traços finos e outro com as áreas chapadas; a gente monta cada um na folha certa. Pode dar alguns centímetros a mais de filme.',
folha:'Esta folha tem traços finos e áreas chapadas no mesmo arquivo. O branco por baixo precisa de ajuste diferente pra cada um. '+
'Vamos proteger os traços finos; as áreas chapadas podem mostrar uma borda branca muito fina. Quer evitar? Mande em duas folhas, '+
'uma com os traços finos e outra com as áreas chapadas. Pode dar alguns centímetros a mais de filme.'};
// O aviso não barra e aparece uma vez por arquivo, na folha pronta e na arte
// avulsa: imprimir assim mesmo (C1), ou trocar o arquivo por dois.
function perguntaMista(){
const dlg=$('mistaDlg');
if(!dlg || dlg.open) return;
const lista=ehFolha()?folhas:artes;
const x=lista.find(y=>!y.mistaVista && mista(tracoDoArquivo(y)));
if(!x) return;
x.mistaVista=true;
$('mistaTit').textContent=x.f.name;
$('mistaTxt').textContent=ehFolha()?TEXTO_MISTA.folha:TEXTO_MISTA.arte;
$('mistaSep').onclick=()=>{ dlg.close(); const i=lista.indexOf(x);
if(i>=0){ lista.splice(i,1); ehFolha()?pintaFolha():pintaArtes(); } $('inp').click(); };
$('mistaSegue').onclick=()=>{ dlg.close(); agendaAvaliacao(); };
dlg.showModal();
}
// O traço mais fino do item (item 9, Dropstar 30/10/2026): o menor entre as
// folhas que o navegador mediu. Não aparece para o cliente; vai para a sala,
// que confere a classe de contração ao aprovar o arquivo final.
function tracoDoItem(lista){
const arquivos=lista||(ehFolha()?folhas:artes);
const medidas=arquivos.map(x=>lista?tracoDaArte(x):tracoDoArquivo(x)).filter(Boolean);
if(!medidas.length) return {strokePx:null, strokeClass:null, strokeChoice:null};
const fino=medidas.reduce((a,b)=>b.px<a.px?b:a);
// Avisado do item 16, o cliente quis imprimir assim: fica a medida, C1.
const avisado=arquivos.some(x=>x.mistaVista && mista(lista?tracoDaArte(x):tracoDoArquivo(x)));
return {strokePx:fino.px, strokeClass:fino.classe, strokeChoice:avisado?'measured':null};
}
// Avalia sozinho conforme o cliente sobe e preenche. Devolve o que ainda falta, // Avalia sozinho conforme o cliente sobe e preenche. Devolve o que ainda falta,
// para a fila dizer em texto em vez de travar num botão. // para a fila dizer em texto em vez de travar num botão.
function avaliar(){ function avaliar(){
@@ -32,8 +78,9 @@ function avaliar(){
if(barrada) return {pronto:false, falta:barrada.an.fundoChapado if(barrada) return {pronto:false, falta:barrada.an.fundoChapado
? barrada.f.name+' está sem fundo transparente. Exporte a folha com fundo transparente, em PNG ou PDF, e envie de novo.' ? barrada.f.name+' está sem fundo transparente. Exporte a folha com fundo transparente, em PNG ou PDF, e envie de novo.'
: barrada.f.name+' tem '+barrada.an.residuos+' ponto'+(barrada.an.residuos>1?'s':'')+ : barrada.f.name+' tem '+barrada.an.residuos+' ponto'+(barrada.an.residuos>1?'s':'')+
' de recorte. Apague e envie de novo, ou marque que aceita imprimir assim.'}; ' de recorte. Apague e envie de novo.'};
metros=folhaTotalM(); metros=folhaTotalM();
setTimeout(perguntaMista);
reencaixado=false; reencaixado=false;
const ans=folhas.map(x=>x.an).filter(Boolean); const ans=folhas.map(x=>x.an).filter(Boolean);
if(ans.length!==folhas.length){ if(ans.length!==folhas.length){
@@ -87,6 +134,14 @@ function avaliar(){
const sem=artes.filter(a=>!a.cm).length; const sem=artes.filter(a=>!a.cm).length;
if(sem) return {pronto:false, falta:'Informe a largura de '+sem+' arte'+(sem>1?'s':'')+ if(sem) return {pronto:false, falta:'Informe a largura de '+sem+' arte'+(sem>1?'s':'')+
' para ver a nota e o preço.'}; ' para ver a nota e o preço.'};
// Item 4: a dot under 2 mm in a loose artwork holds the order like on a
// sheet, until the customer erases it or accepts printing that artwork so.
if(artes.some(a=>a.lendoArte)) return {pronto:false, falta:'Conferindo as artes…'};
const comPontos=artes.find(a=>{const an=analiseDaArte(a);return an&&an.residuos&&!a.residuoAceito;});
if(comPontos){const n=analiseDaArte(comPontos).residuos;
return {pronto:false, falta:comPontos.f.name+' tem '+n+' ponto'+(n>1?'s':'')+
' de recorte. Apague e envie de novo, ou marque que aceita imprimir assim.'};}
setTimeout(perguntaMista);
// metragem = altura da folha depois de montada, com os 5 mm entre peças // metragem = altura da folha depois de montada, com os 5 mm entre peças
metros=+(montagemCm/100).toFixed(4); metros=+(montagemCm/100).toFixed(4);
if(!(metros>0)) return {pronto:false, falta:'Montando a folha…'}; if(!(metros>0)) return {pronto:false, falta:'Montando a folha…'};

View File

@@ -60,10 +60,168 @@ function novoMapa(wPx,hPx,larguraCm){
const colDe=new Uint32Array(wPx); const colDe=new Uint32Array(wPx);
for(let x=0;x<wPx;x++) colDe[x]=Math.min(cw-1,Math.floor(x/pxCel)); for(let x=0;x<wPx;x++) colDe[x]=Math.min(cw-1,Math.floor(x/pxCel));
return {wPx,hPx,larguraCm,pxPorCm,passo,pxCel,cw,ch,colDe,bits:new Uint8Array(n), return {wPx,hPx,larguraCm,pxPorCm,passo,pxCel,cw,ch,colDe,bits:new Uint8Array(n),
x0:new Uint32Array(n),x1:new Uint32Array(n),y0:new Uint32Array(n),y1:new Uint32Array(n),tinta:0}; x0:new Uint32Array(n),x1:new Uint32Array(n),y0:new Uint32Array(n),y1:new Uint32Array(n),tinta:0,
traco:novoTraco(wPx,wPx/(larguraCm/2.54))};
}
// ── Traço mais fino (Dropstar, 30/10/2026): a contração do Flexi vem dele.
// Tinta é alfa acima de 40; a distância de cada pixel de tinta ao fundo sai de
// um chanfro 10/14, e no eixo do traço a largura é o dobro da distância (menos
// um quando a largura é ímpar). O mais fino da folha é o 1º percentil dessas
// larguras, em pixels a 300 DPI: até 4 é C1, de 5 a 19 é C2, 20 ou mais é C3.
// A folha passa em faixas, linha a linha: cada faixa guarda 20 linhas antes e
// depois, o alcance da distância, e nada maior que uma faixa fica na memória.
const ALFA_TRACO=40, TRACO_D=20, TRACO_FAIXA=256, TRACO_CISCO=30;
// Quanta tinta das linhas medidas fica a até r px (num quadrado) de um pixel a
// lim ou mais do fundo. Com lim de 10 px e r de 10 px, é a tinta das áreas de
// 20 px ou mais, bordas incluídas; com 3 px e 2 px, a que não é traço fino.
function tintaPerto(t,lim,r,de,ate){
const {w,n,dist}=t, h=t.rot, prox=t.prox; // os rótulos já serviram
for(let y=0;y<n;y++){ const o=y*w;
let ult=-1e9; for(let x=0;x<w;x++){ if(dist[o+x]>=lim) ult=x; h[o+x]=x-ult<=r?1:0; }
ult=1e9; for(let x=w-1;x>=0;x--){ if(dist[o+x]>=lim) ult=x; if(ult-x<=r) h[o+x]=1; } }
let c=0;
for(let x=0;x<w;x++){
let ult=1e9; for(let y=n-1;y>=0;y--){ if(h[y*w+x]) ult=y; prox[y]=ult; }
ult=-1e9; for(let y=0;y<ate;y++){ const p=y*w+x; if(h[p]) ult=y;
if(y>=de&&dist[p]&&(y-ult<=r||prox[y]-y<=r)) c++; } }
return c;
}
// O contexto de cada faixa: as linhas acima e abaixo que ela lê sem medir. Um
// cisco (menos de 30 px de tinta a 300 DPI) tem menos linhas que isso, então
// a faixa sempre o vê inteiro; o que encosta na borda cortada é traço.
function novoTraco(wPx,dpi){
const cisco=Math.ceil(TRACO_CISCO*(dpi/300)**2), ctx=Math.min(120,Math.max(TRACO_D,cisco));
const linhas=TRACO_FAIXA+2*ctx;
return {w:wPx,dpi,linhas,ctx,cisco,tinta:new Uint8Array(wPx*linhas),dist:new Uint16Array(wPx*linhas),
rot:new Int32Array(wPx*linhas),pai:new Int32Array((wPx*linhas>>1)+2),area:new Int32Array((wPx*linhas>>1)+2),
prox:new Int32Array(TRACO_FAIXA+2*ctx),
n:0,inicio:0,hist:new Float64Array(2*TRACO_D+2),total:0,tintaPx:0,largosPx:0,finosPx:0};
}
// Como a sala mede (Dropstar, 30/10/2026): componentes de tinta com menos de
// 30 px não são traço e saem antes da distância. Vizinhos nas oito direções.
function tiraCiscos(t,topo,fim){
const {w,n,tinta,rot,pai,area,cisco}=t;
let prox=1;
const raiz=a=>{while(pai[a]!==a){pai[a]=pai[pai[a]];a=pai[a];}return a;};
const une=(a,b)=>{a=raiz(a);b=raiz(b);if(a===b)return a;if(a<b){pai[b]=a;return a;}pai[a]=b;return b;};
// O pixel de cima já encosta nos outros três vizinhos lidos; sem ele, o da
// esquerda encosta no de cima à esquerda. Só sobra unir o de cima à direita.
for(let y=0;y<n;y++){ const o=y*w;
for(let x=0;x<w;x++){ const p=o+x;
if(!tinta[p]){ rot[p]=0; continue; }
const a=p-w, cima=y>0&&tinta[a], dir=y>0&&x<w-1&&tinta[a+1];
let r=0;
if(cima) r=rot[a];
else{
if(x>0&&tinta[p-1]) r=rot[p-1];
else if(y>0&&x>0&&tinta[a-1]) r=rot[a-1];
if(dir) r=r?une(r,rot[a+1]):rot[a+1];
}
if(!r){ r=prox++; pai[r]=r; area[r]=0; }
rot[p]=r; } }
if(prox===1) return;
// Cada rótulo aponta para um menor: em ordem, um passo só leva à raiz.
for(let r=1;r<prox;r++) pai[r]=pai[pai[r]];
for(let p=0;p<w*n;p++) if(rot[p]) area[pai[rot[p]]]++;
// Encostar numa borda que não é a da folha: o componente continua fora da faixa.
if(!topo) for(let x=0;x<w;x++) if(rot[x]) area[pai[rot[x]]]=cisco;
if(!fim) for(let x=0,o=(n-1)*w;x<w;x++) if(rot[o+x]) area[pai[rot[o+x]]]=cisco;
let ciscos=0;
for(let r=1;r<prox;r++) if(pai[r]===r&&area[r]<cisco) ciscos++;
if(!ciscos) return;
for(let p=0;p<w*n;p++) if(rot[p]&&area[pai[rot[p]]]<cisco) tinta[p]=0;
}
function tracoLinha(t,alfa,inicio,de){
const o=t.n*t.w, ink=t.tinta;
for(let x=0,i=inicio;x<t.w;x++,i+=de) ink[o+x]=alfa[i]>ALFA_TRACO?1:0;
t.n++;
if(t.n===t.linhas) tracoFaixa(t,false);
}
// A distância na faixa, e as larguras das linhas que ela já mede inteiras.
function tracoFaixa(t,fim){
const {w,n,tinta,dist,ctx}=t, CAP=TRACO_D*10+10, topo=t.inicio===0;
if(!n) return;
tiraCiscos(t,topo,fim);
for(let p=0;p<w*n;p++) dist[p]=tinta[p]?CAP:0;
// ida: de cima para baixo; fora da folha é fundo
for(let y=0;y<n;y++){ const o=y*w, a=o-w;
for(let x=0;x<w;x++){ const p=o+x; if(!dist[p]) continue;
let d=dist[p];
const l=x>0?dist[p-1]:0; if(l+10<d) d=l+10;
if(y>0){ const u=dist[a+x]; if(u+10<d) d=u+10;
const ul=x>0?dist[a+x-1]:0; if(ul+14<d) d=ul+14;
const ur=x<w-1?dist[a+x+1]:0; if(ur+14<d) d=ur+14; }
else if(topo) d=10;
dist[p]=d; } }
// volta: de baixo para cima
for(let y=n-1;y>=0;y--){ const o=y*w, b=o+w;
for(let x=w-1;x>=0;x--){ const p=o+x; if(!dist[p]) continue;
let d=dist[p];
const r=x<w-1?dist[p+1]:0; if(r+10<d) d=r+10;
if(y<n-1){ const dn=dist[b+x]; if(dn+10<d) d=dn+10;
const dl=x>0?dist[b+x-1]:0; if(dl+14<d) d=dl+14;
const dr=x<w-1?dist[b+x+1]:0; if(dr+14<d) d=dr+14; }
else if(fim) d=Math.min(d,10);
dist[p]=d; } }
// As linhas medidas por inteiro: longe das bordas da faixa, salvo as da folha.
const de=topo?0:ctx, ate=fim?n:n-ctx;
const escala=300/t.dpi, hist=t.hist, max=hist.length-1;
const at=(x,y)=>(x<0||x>=w||y<0||y>=n)?0:dist[y*w+x];
// Item 16: tinta em áreas de 20 px ou mais (a 300 DPI) é a que fica a 10 px
// ou mais do fundo; a conta é da tinta das linhas medidas.
let tintaFaixa=0;
for(let y=de;y<ate;y++){ const o=y*w; for(let x=0;x<w;x++) if(dist[o+x]) tintaFaixa++; }
t.tintaPx+=tintaFaixa;
if(tintaFaixa){
t.largosPx+=tintaPerto(t,100/escala,Math.round(10/escala),de,ate);
// Traço fino, até 4 px: nada a 3 px do fundo a até 2 px dele.
t.finosPx+=tintaFaixa-tintaPerto(t,30/escala,Math.max(1,Math.round(2/escala)),de,ate);
}
for(let y=de;y<ate;y++) for(let x=0;x<w;x++){
const d=dist[y*w+x]; if(!d) continue;
// Mais largo que a distância medida (uns 40 px): o eixo dessa área também
// conta, na última faixa, ou dois pixels soltos de borda viram o menor
// traço de uma arte toda chapada. O comprimento do eixo é cerca de metade
// do contorno da região além do limite.
if(d>=CAP){ if(at(x-1,y)<CAP||at(x+1,y)<CAP||at(x,y-1)<CAP||at(x,y+1)<CAP){hist[max]+=0.5;t.total+=0.5;} continue; }
// No eixo do traço a distância não é menor que a de nenhum vizinho; perto
// de um canto sempre há um vizinho mais fundo, e o canto não conta.
let iguais=0, eixo=true;
for(let dy=-1;dy<=1&&eixo;dy++) for(let dx=-1;dx<=1;dx++){
if(!dx&&!dy) continue;
const v=at(x+dx,y+dy);
if(v>d){ eixo=false; break; }
if(v===d) iguais++;
}
if(!eixo) continue;
// Largura par: o eixo tem dois pixels, e os iguais passam de dois.
const larg=iguais>=4?2*d/10:2*d/10-1;
const i=Math.max(1,Math.min(max,Math.round(larg*escala)));
hist[i]++;t.total++;
}
// As últimas linhas ficam como contexto da próxima faixa.
if(!fim){
const fica=2*ctx;
tinta.copyWithin(0,(n-fica)*w,n*w);
t.inicio+=n-fica; t.n=fica;
}
}
// O 1º percentil das larguras, em pixels a 300 DPI, e a classe de contração.
// Uma vez só: depois a faixa não existe mais, e a resposta fica guardada,
// também quando é null (uma folha sem tinta).
function tracoFim(t){
if(t.lido!==undefined) return t.lido;
tracoFaixa(t,true);
t.tinta=t.dist=t.rot=t.pai=t.area=t.prox=null; // a faixa não serve mais
if(!t.total) return t.lido=null;
let soma=0, px=1;
for(let i=1;i<t.hist.length;i++){ soma+=t.hist[i]; if(soma>=t.total*0.01){ px=i; break; } }
// largos: a parte da tinta em áreas chapadas, de 20 px ou mais (item 16)
return t.lido={px, classe:px<=4?'C1':px<=19?'C2':'C3', largos:t.tintaPx?t.largosPx/t.tintaPx:0, finos:t.tintaPx?t.finosPx/t.tintaPx:0};
} }
// A linha y da folha: o alfa de cada pixel em alfa[inicio + x*de]. // A linha y da folha: o alfa de cada pixel em alfa[inicio + x*de].
function mapaLinha(m,y,alfa,inicio,de){ function mapaLinha(m,y,alfa,inicio,de){
if(m.traco) tracoLinha(m.traco,alfa,inicio,de);
const base=Math.min(m.ch-1,Math.floor(y/m.pxCel))*m.cw; const base=Math.min(m.ch-1,Math.floor(y/m.pxCel))*m.cw;
const {bits,x0,x1,y0,y1,colDe}=m; const {bits,x0,x1,y0,y1,colDe}=m;
let tinta=0; let tinta=0;
@@ -144,7 +302,8 @@ function analisarMapa(m){
fundoChapado: (total-m.tinta)/total < 0.015, fundoChapado: (total-m.tinta)/total < 0.015,
aproveitamento: Math.max(1,Math.min(100,Math.round(m.tinta/total*100))), aproveitamento: Math.max(1,Math.min(100,Math.round(m.tinta/total*100))),
alturaCm: m.hPx/m.pxPorCm, alturaCm: m.hPx/m.pxPorCm,
grade: +(m.passo*10).toFixed(1) // mm por célula que agrupa grade: +(m.passo*10).toFixed(1), // mm por célula que agrupa
traco: m.traco ? tracoFim(m.traco) : null
}; };
} }

View File

@@ -222,23 +222,53 @@ function medir(a){
if(!/\.png$/i.test(a.f.name)){ a.semPrevia=true; return a; } if(!/\.png$/i.test(a.f.name)){ a.semPrevia=true; return a; }
a.lendo=0; a.leitura={inicio:Date.now(), p:0}; pintaArtes(); a.lendo=0; a.leitura={inicio:Date.now(), p:0}; pintaArtes();
let mostrado=0; let mostrado=0;
const cv=await previaPngGrande(a.f, 1200, p=>{ const lido=await previaPngGrande(a.f, 1200, p=>{
const pct=Math.floor(p*100); const pct=Math.floor(p*100);
a.leitura.p=p; a.leitura.p=p;
if(pct-mostrado>=1){ mostrado=pct; a.lendo=pct; pintaProgressoArte(a); } if(pct-mostrado>=1){ mostrado=pct; a.lendo=pct; pintaProgressoArte(a); }
}).catch(()=>null); }, a.px/300*2.54).catch(()=>null);
const cv=lido&&lido.cv;
if(lido&&lido.mapa) guardaMapaDaArte(a, lido.mapa);
a.lendo=null; a.lendo=null;
if(cv && artes.includes(a)){ a.src=cv.toDataURL('image/webp',0.9); a.miniSrc=miniatura(cv); a.fotoSrc=miniatura(cv,480,720); } if(cv && artes.includes(a)){ a.src=cv.toDataURL('image/webp',0.9); a.miniSrc=miniatura(cv); a.fotoSrc=miniatura(cv,480,720); }
else if(!cv) a.decodeError=true; else if(!cv) a.decodeError=true;
return a; return a;
}).catch(()=>{ a.decodeError=true; return a; }); }).catch(()=>{ a.decodeError=true; return a; });
} }
return carregarImagem(a.f).then(img=>{ return carregarImagem(a.f).then(async img=>{
if(img){ a.prop=img.height/img.width; a.px=img.width; a.py=img.height; a.src=img.src; a.miniSrc=miniatura(img); a.fotoSrc=miniatura(img,480,720); } if(img){ a.prop=img.height/img.width; a.px=img.width; a.py=img.height; a.src=img.src; a.miniSrc=miniatura(img); a.fotoSrc=miniatura(img,480,720);
// Read at its own pixels while the customer sets the width.
a.lendoArte=true;
mapaDaImagem(img, a.px/300*2.54).then(m=>guardaMapaDaArte(a,m)).catch(()=>{})
.finally(()=>{ a.lendoArte=false; if(artes.includes(a)) pintaArtes(); });
}
else a.decodeError=true; else a.decodeError=true;
return a; return a;
}); });
} }
// Item 4 (Dropstar, 30/10/2026): each loose artwork is checked like a sheet,
// at its own pixels: dots under 2 mm, and its thinnest stroke (item 9). Read
// once; the sizes in mm and the stroke at 300 DPI follow the width the
// customer asks for, so they are worked out again when it changes.
function guardaMapaDaArte(a,m){
a.mapa=m; a.anCm=null;
// The stroke in the art's own pixels: the map was read as if at 300 DPI.
a.tracoPx=analisarMapa(m).traco;
}
function analiseDaArte(a){
if(!a.mapa || !(a.cm>0)) return null;
if(a.anCm!==a.cm){
const m=a.mapa; m.larguraCm=a.cm; m.pxPorCm=m.wPx/a.cm;
a.an=analisarMapa(m); a.anCm=a.cm;
}
return a.an;
}
// The art's thinnest stroke at the width asked for, in pixels at 300 DPI.
function tracoDaArte(a){
if(!a.tracoPx || !(a.cm>0)) return null;
const px=Math.max(1,Math.round(a.tracoPx.px*300/dpiDe(a)));
return {px, classe:px<=4?'C1':px<=19?'C2':'C3', largos:a.tracoPx.largos, finos:a.tracoPx.finos};
}
// A metragem sai do arquivo, nunca do peso em bytes. // A metragem sai do arquivo, nunca do peso em bytes.
// imagem → proporção da imagem aplicada à largura do filme // imagem → proporção da imagem aplicada à largura do filme
// PDF → página única lida pelo PDF.js, com boxes, rotação e UserUnit // PDF → página única lida pelo PDF.js, com boxes, rotação e UserUnit

View File

@@ -518,3 +518,17 @@ html:is([data-rota="pagamento"],[data-rota="pix"]) .pagGrid{display:grid;grid-te
.opFn small{font-size:13.5px;color:var(--texto2)} .opFn small{font-size:13.5px;color:var(--texto2)}
.opF i{font-style:normal;font-size:12px;font-weight:700;color:var(--verde-ml);white-space:nowrap} .opF i{font-style:normal;font-size:12px;font-weight:700;color:var(--verde-ml);white-space:nowrap}
.opF em{font-style:normal;font-weight:800;white-space:nowrap} .opF em{font-style:normal;font-weight:800;white-space:nowrap}
/* Item 16: fine lines and solid areas in one file. */
.mistaDlg{width:min(560px,calc(100vw - 32px));margin:auto}
.mistaCorpo{padding:4px 20px 20px;display:flex;flex-direction:column;gap:16px}
.mistaCorpo p{margin:0;line-height:1.5;font-size:15.5px}
.mistaBot{display:flex;gap:10px;flex-wrap:wrap;flex-direction:row-reverse;justify-content:flex-start}
#mistaSegue{margin-left:0}
@media(max-width:520px){.mistaBot button{flex:1 1 100%}}
.mistaBot button{height:42px;padding:0 16px;border-radius:10px;font-weight:700;cursor:pointer}
#mistaSep{background:transparent;border:1px solid currentColor;opacity:.8}
/* Item 17: loose art in two sheets, fine and thick strokes. */
#vArea .folhasTraco{display:flex;flex-direction:column;gap:14px}
#vArea .folhaTraco{margin:0;display:flex;flex-direction:column;gap:6px}
#vArea .folhaTraco figcaption{font-size:14.5px;font-weight:700;color:var(--texto2)}

17
web/theme.js Normal file
View File

@@ -0,0 +1,17 @@
/* Kanban DTF: dark or light, chosen per browser. Loaded in <head>, so the
page draws in its theme from the start and never flashes the other one. */
(() => {
const KEY = 'kanban-theme';
const root = document.documentElement;
let saved = null;
try { saved = localStorage.getItem(KEY); } catch (e) { /* private window: dark */ }
root.dataset.theme = saved === 'light' ? 'light' : 'dark';
window.kanbanTheme = {
get: () => root.dataset.theme,
set(theme) {
root.dataset.theme = theme;
try { localStorage.setItem(KEY, theme); } catch (e) { /* kept for this page only */ }
},
toggle() { this.set(this.get() === 'light' ? 'dark' : 'light'); return this.get(); },
};
})();