Compare commits
32 Commits
ui-v2
...
25e4ac541a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25e4ac541a | ||
|
|
dc87d46801 | ||
|
|
c291f00e96 | ||
|
|
b97b895993 | ||
|
|
f78cb93ba7 | ||
|
|
3d1293a3af | ||
|
|
2bcdb060fd | ||
|
|
6351a094f4 | ||
|
|
945c9e366a | ||
|
|
054a642a61 | ||
|
|
392e7da85b | ||
|
|
d69e326125 | ||
|
|
0fc01315c7 | ||
|
|
94f1bfa733 | ||
|
|
5520081184 | ||
|
|
8b7d9f0bdb | ||
|
|
e3a5ad6fa0 | ||
|
|
353935bed3 | ||
|
|
bd1e1772a7 | ||
|
|
a17f5fc08d | ||
|
|
67fad3a2d7 | ||
|
|
2615163fd3 | ||
|
|
388408d4d6 | ||
|
|
a010b2507e | ||
|
|
df601a7b6e | ||
|
|
67a9cd9533 | ||
|
|
0b8eb143ad | ||
|
|
f5c8bcfb90 | ||
|
|
d2e340032e | ||
|
|
6f294e168b | ||
|
|
c76d2fa7f3 | ||
|
|
05139b71ff |
@@ -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
|
||||||
|
|||||||
@@ -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: |
|
||||||
|
|||||||
@@ -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:
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from uuid import UUID
|
|||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
|
||||||
from ..core import db
|
from ..core import db
|
||||||
|
from .. import proof
|
||||||
from ..artwork import submit_files
|
from ..artwork import submit_files
|
||||||
from ..core.auth import can, operator
|
from ..core.auth import can, operator
|
||||||
from ..core.models import ArtworkSubmission, UploadStart
|
from ..core.models import ArtworkSubmission, UploadStart
|
||||||
@@ -18,9 +19,14 @@ router = APIRouter()
|
|||||||
|
|
||||||
@router.post('/api/operator/orders/{oid}/uploads')
|
@router.post('/api/operator/orders/{oid}/uploads')
|
||||||
def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
|
def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))):
|
||||||
|
if not body.name.lower().endswith('.png'):
|
||||||
|
raise HTTPException(422, 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.')
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
|
row = c.execute('SELECT id,state,parent_id,proof_ok_at FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone()
|
||||||
if not row: raise HTTPException(404, 'Order not found')
|
if not row: raise HTTPException(404, 'Order not found')
|
||||||
|
if row['parent_id']:
|
||||||
|
raise HTTPException(409, 'A prova recebe o PNG final automaticamente.')
|
||||||
|
proof.require_unlocked(c, row)
|
||||||
if row['state'] not in ('rec','cor'): raise HTTPException(409, 'Order is not in artwork review')
|
if row['state'] not in ('rec','cor'): raise HTTPException(409, 'Order is not in artwork review')
|
||||||
return begin_upload(body, session_id=operator_identity(user))
|
return begin_upload(body, session_id=operator_identity(user))
|
||||||
|
|
||||||
@@ -52,4 +58,7 @@ def final_files(oid: UUID, body: ArtworkSubmission, user=Depends(can('produce'))
|
|||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (oid,)).fetchone()
|
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (oid,)).fetchone()
|
||||||
if not order: raise HTTPException(404, 'Order not found')
|
if not order: raise HTTPException(404, 'Order not found')
|
||||||
|
if order['parent_id']:
|
||||||
|
raise HTTPException(409, 'O arquivo final da prova é gerado automaticamente. Use Gerar de novo se falhar.')
|
||||||
|
proof.require_unlocked(c, order)
|
||||||
return submit_files(c,order,body,operator_identity(user),'final',user)
|
return submit_files(c,order,body,operator_identity(user),'final',user)
|
||||||
|
|||||||
@@ -6,21 +6,22 @@ import secrets
|
|||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from datetime import date, datetime, timedelta, timezone
|
from datetime import date, datetime, timedelta, timezone
|
||||||
from typing import Literal
|
from typing import Literal
|
||||||
from uuid import UUID
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
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 CLAIM_TIMEOUT, 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
|
||||||
|
|
||||||
@@ -104,15 +105,17 @@ def backup_now(user=Depends(can('integrations'))):
|
|||||||
@router.get('/api/operator/board')
|
@router.get('/api/operator/board')
|
||||||
def board(user=Depends(operator)):
|
def board(user=Depends(operator)):
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
# Orders that arrived, or lost their machine, get one before the board is read.
|
|
||||||
machines.route(c)
|
|
||||||
# Everything still in progress, however old: an operator must never lose a
|
# Everything still in progress, however old: an operator must never lose a
|
||||||
# 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 (
|
||||||
finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin'").fetchone()['n']
|
SELECT o.*, COALESCE((SELECT max(m.created_at) FROM dtf_local.movements m
|
||||||
|
WHERE m.order_id=o.id AND m.to_state='fin' AND NOT m.back), o.updated_at) AS finished_at
|
||||||
|
FROM dtf_local.orders o WHERE o.state='fin' AND o.parent_id IS NULL
|
||||||
|
) f ORDER BY finished_at DESC,id DESC LIMIT %s''', (BOARD_FINISHED_LIMIT,)).fetchall()
|
||||||
|
finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL").fetchone()['n']
|
||||||
pending = c.execute(f'''SELECT q.* FROM dtf_local.quotes q
|
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}
|
||||||
@@ -127,21 +130,22 @@ def board(user=Depends(operator)):
|
|||||||
approved_total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
|
approved_total = c.execute(f'''SELECT count(*) AS n FROM dtf_local.quotes q
|
||||||
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
LEFT JOIN dtf_local.orders o ON o.quote_id=q.id
|
||||||
WHERE o.id IS NULL AND q.approved IS NOT NULL AND {LIVE_QUOTE}''').fetchone()['n']
|
WHERE o.id IS NULL AND q.approved IS NOT NULL AND {LIVE_QUOTE}''').fetchone()['n']
|
||||||
orders = with_print_files(c, active + list(reversed(finished)))
|
orders = with_print_files(c, active + finished)
|
||||||
# A paid notification that did not become an order is money received
|
# A paid notification that did not become an order is money received
|
||||||
# for nothing the factory will make. The board carries the count; the
|
# for nothing the factory will make. The board carries the count; the
|
||||||
# Pagamentos tab pages through them until someone records a resolution.
|
# Pagamentos tab pages through them until someone records a resolution.
|
||||||
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,23 +186,27 @@ 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')"""
|
||||||
|
|
||||||
|
|
||||||
def assign_machines(c, orders):
|
def assign_machines(c, orders):
|
||||||
"""Each order's machine as stored (app/machines.py gives it): chosen by
|
"""Each machine, its pull attribution, and its printing place."""
|
||||||
someone, or automatic. None while no machine prints its product. In
|
|
||||||
Imprimindo, also which of its machine's two places it holds."""
|
|
||||||
names = {str(m['id']): m['name'] for m in c.execute('SELECT id,name FROM dtf_local.machines').fetchall()}
|
names = {str(m['id']): m['name'] for m in c.execute('SELECT id,name FROM dtf_local.machines').fetchall()}
|
||||||
slots = machines.printing_slots(c)
|
slots = machines.printing_slots(c)
|
||||||
|
ids = [o['id'] for o in orders] + [o['proof_card']['id'] for o in orders if o.get('proof_card')]
|
||||||
|
pulled = {r['order_id']: r for r in c.execute('''SELECT DISTINCT ON (order_id) order_id,operator,created_at
|
||||||
|
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='imp' AND NOT back
|
||||||
|
ORDER BY order_id,id DESC''', (ids,)).fetchall()}
|
||||||
for order in orders:
|
for order in orders:
|
||||||
key = str(order.get('machine_id') or '')
|
key = str(order.get('machine_id') or '')
|
||||||
order['machine'] = ({'id': key, 'name': names[key], 'chosen': bool(order.get('machine_chosen'))}
|
order['machine'] = ({'id': key, 'name': names[key], 'chosen': bool(order.get('machine_chosen'))}
|
||||||
if key in names else None)
|
if key in names else None)
|
||||||
order['printing'] = slots.get(order['id'])
|
order['printing'] = slots.get(order['id'])
|
||||||
|
by = pulled.get(order['id']) or (pulled.get(order['proof_card']['id']) if order.get('proof_card') else None)
|
||||||
|
order['machine_pulled'] = {'by': by['operator'], 'at': by['created_at']} if by else None
|
||||||
return orders
|
return orders
|
||||||
|
|
||||||
|
|
||||||
@@ -206,9 +214,17 @@ def with_print_files(c, orders):
|
|||||||
"""Each order with its generated print files, the items whose final file is
|
"""Each order with its generated print files, the items whose final file is
|
||||||
approved, and the customer's corrections waiting to be approved as finals."""
|
approved, and the customer's corrections waiting to be approved as finals."""
|
||||||
ids = [o['id'] for o in orders]
|
ids = [o['id'] for o in 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,p.claimed_at,p.finished_at,
|
||||||
|
(p.status='rendering' AND p.claimed_at<now()-%s) AS timed_out,
|
||||||
|
p.claimed_at+%s AS timeout_at,u.name
|
||||||
FROM dtf_local.print_files p LEFT JOIN dtf_local.uploads u ON u.id=p.upload_id
|
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''', (CLAIM_TIMEOUT, CLAIM_TIMEOUT, 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 +244,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']]
|
||||||
@@ -255,15 +285,18 @@ def cursor_pair(first, second):
|
|||||||
|
|
||||||
|
|
||||||
@router.get('/api/operator/orders/finished')
|
@router.get('/api/operator/orders/finished')
|
||||||
def finished_page(before_created_at: datetime | None = None, before_id: UUID | None = None,
|
def finished_page(before_finished_at: datetime | None = None, before_id: UUID | None = None,
|
||||||
limit: int = Query(default=50, ge=1, le=100), user=Depends(operator)):
|
limit: int = Query(default=50, ge=1, le=100), user=Depends(operator)):
|
||||||
"""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_finished_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 (
|
||||||
''' + ('AND (created_at,id)<(%s,%s) ' if paged else '') + '''
|
SELECT o.*, COALESCE((SELECT max(m.created_at) FROM dtf_local.movements m
|
||||||
ORDER BY created_at DESC,id DESC LIMIT %s''',
|
WHERE m.order_id=o.id AND m.to_state='fin' AND NOT m.back), o.updated_at) AS finished_at
|
||||||
((before_created_at, before_id) if paged else ()) + (limit + 1,)).fetchall()
|
FROM dtf_local.orders o WHERE o.state='fin' AND o.parent_id IS NULL
|
||||||
|
) f ''' + ('WHERE (finished_at,id)<(%s,%s) ' if paged else '') + '''
|
||||||
|
ORDER BY finished_at DESC,id DESC LIMIT %s''',
|
||||||
|
((before_finished_at, before_id) if paged else ()) + (limit + 1,)).fetchall()
|
||||||
orders = with_print_files(c, rows[:limit])
|
orders = with_print_files(c, rows[:limit])
|
||||||
return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders),
|
return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders),
|
||||||
'names': company_names(c, orders)}
|
'names': company_names(c, orders)}
|
||||||
@@ -282,7 +315,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 +435,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 +458,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 +622,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 +648,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 +674,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()
|
||||||
@@ -628,27 +691,68 @@ class MachineChoice(StrictModel):
|
|||||||
|
|
||||||
@router.post('/api/operator/orders/{uid}/machine')
|
@router.post('/api/operator/orders/{uid}/machine')
|
||||||
def choose_machine(uid: UUID, body: MachineChoice, request: Request, user=Depends(can('print'))):
|
def choose_machine(uid: UUID, body: MachineChoice, request: Request, user=Depends(can('print'))):
|
||||||
"""Send an order to a machine, or back to the automatic choice (None).
|
"""Exceptional manual choice before printing; the operator's pull is final."""
|
||||||
Not the operator: their pull makes an order their machine's (item 12)."""
|
|
||||||
if request.state.operator['role'] == 'operador':
|
if request.state.operator['role'] == 'operador':
|
||||||
raise HTTPException(403, 'A máquina do pedido é a de quem puxa para Imprimindo.')
|
raise HTTPException(403, 'A máquina do pedido é a de quem puxa para Imprimindo.')
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
if body.machine_id and not c.execute('SELECT 1 FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone():
|
current = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||||
raise HTTPException(404, 'Máquina não encontrada.')
|
if not current:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
proof.require_unlocked(c, current)
|
||||||
|
if current['cancelled_at'] or current['state'] not in ('rec', 'tra', 'cor'):
|
||||||
|
raise HTTPException(409, 'A máquina não muda depois que o card entrou em Imprimindo.')
|
||||||
|
if body.machine_id:
|
||||||
|
target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone()
|
||||||
|
if not target or not target['active']:
|
||||||
|
raise HTTPException(404, 'Máquina não encontrada ou desativada.')
|
||||||
|
if machines.product_family(current) not in target['products']:
|
||||||
|
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
|
||||||
|
linked = c.execute('''SELECT id,state,machine_id,proof_result FROM dtf_local.orders
|
||||||
|
WHERE parent_id=%s AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone()
|
||||||
|
if linked and linked['proof_result'] == 'ok' and linked['machine_id'] and body.machine_id != linked['machine_id']:
|
||||||
|
raise HTTPException(409, 'O pedido precisa ficar na mesma máquina que imprimiu a prova.')
|
||||||
row = c.execute('''UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=%s WHERE id=%s
|
row = c.execute('''UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=%s WHERE id=%s
|
||||||
RETURNING number, state, cancelled_at''', (body.machine_id, body.machine_id is not None, uid)).fetchone()
|
RETURNING number, state, cancelled_at''', (body.machine_id, body.machine_id is not None, uid)).fetchone()
|
||||||
if not row:
|
if current['parent_id']:
|
||||||
raise HTTPException(404, 'Pedido não encontrado.')
|
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s',
|
||||||
machines.route(c)
|
(body.machine_id, body.machine_id is not None, current['parent_id']))
|
||||||
# Printing already: the machine it goes to must have a place in Imprimindo.
|
elif linked and linked['proof_result'] is None and linked['state'] in ('rec', 'tra', 'cor'):
|
||||||
if row['state'] == 'imp' and not row['cancelled_at']:
|
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s',
|
||||||
now = c.execute('SELECT machine_id FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
|
(body.machine_id, body.machine_id is not None, linked['id']))
|
||||||
if name := machines.full(c, now['machine_id'], uid):
|
|
||||||
raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.')
|
|
||||||
audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user)
|
audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user)
|
||||||
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 id,parent_id,proof_ok_at,snapshot,state,cancelled_at,contraction FROM dtf_local.orders WHERE id=%s FOR UPDATE',
|
||||||
|
(uid,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
proof.require_unlocked(c, row)
|
||||||
|
if body.item_index >= len(row['snapshot']['items']):
|
||||||
|
raise HTTPException(422, 'Item não encontrado no pedido.')
|
||||||
|
# Printing, the class still changes while the item's files wait to go
|
||||||
|
# into the hot folder: the class is its folder (item 10).
|
||||||
|
written = row['state'] == 'imp' and c.execute('''SELECT 1 FROM dtf_local.hot_parts WHERE order_id=%s
|
||||||
|
AND item_index=%s AND state NOT IN ('queued','gone') LIMIT 1''', (uid, body.item_index)).fetchone()
|
||||||
|
if row['cancelled_at'] or row['state'] not in ('rec', 'tra', 'cor', 'imp') or written:
|
||||||
|
raise HTTPException(409, 'A contração muda até o arquivo ir para a hot folder da máquina.')
|
||||||
|
chosen = dict(row['contraction'] or {})
|
||||||
|
key = str(body.item_index)
|
||||||
|
if body.value is None:
|
||||||
|
chosen.pop(key, None)
|
||||||
|
else:
|
||||||
|
chosen[key] = {'class': body.value, 'by': user, 'at': datetime.now(timezone.utc).isoformat()}
|
||||||
|
c.execute('UPDATE dtf_local.orders SET contraction=%s WHERE id=%s', (Jsonb(chosen), uid))
|
||||||
|
audit('order_contraction_chosen', order=str(uid), item=body.item_index, value=body.value or '', operator=user)
|
||||||
|
return {'ok': True, 'contraction': chosen}
|
||||||
|
|
||||||
|
|
||||||
class ContactWait(StrictModel):
|
class ContactWait(StrictModel):
|
||||||
waiting: bool
|
waiting: bool
|
||||||
note: str = Field(default='', max_length=500)
|
note: str = Field(default='', max_length=500)
|
||||||
@@ -677,10 +781,100 @@ 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':
|
||||||
|
# A prova aprovada é a conferência do pai: os arquivos completos
|
||||||
|
# que o Prumo gerou entram como finais, e o pai segue para a fila.
|
||||||
|
# Itens que ainda dependem de preparo manual continuam em Arte
|
||||||
|
# recebida, com o botão de final disponível.
|
||||||
|
if parent['state'] == 'rec':
|
||||||
|
generated = c.execute('''SELECT p.item_index,p.upload_id FROM dtf_local.print_files p
|
||||||
|
WHERE p.order_id=%s AND p.status='ready' AND p.upload_id IS NOT NULL
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f
|
||||||
|
WHERE f.order_id=p.order_id AND f.item_index=p.item_index
|
||||||
|
AND f.kind='final' AND f.active)
|
||||||
|
ORDER BY p.item_index''', (parent['id'],)).fetchall()
|
||||||
|
for row in generated:
|
||||||
|
c.execute('''INSERT INTO dtf_local.order_files
|
||||||
|
(id,order_id,upload_id,item_index,kind,note,created_by)
|
||||||
|
VALUES(%s,%s,%s,%s,'final',%s,'Prumo')''',
|
||||||
|
(uuid4(), parent['id'], row['upload_id'], row['item_index'],
|
||||||
|
f'Aprovado pela prova do #{card["number"]}'))
|
||||||
|
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,
|
||||||
|
machine_id=NULL,machine_chosen=false,
|
||||||
|
version=version+1, updated_at=now() WHERE id=%s''', (parent['id'],))
|
||||||
|
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
|
||||||
|
VALUES(%s,%s,'rec',%s,%s)''', (parent['id'], parent['state'], user, label))
|
||||||
|
# The proof answer is the contact with the customer: the old
|
||||||
|
# "Aguardando contato" mark has done its job either way (0.1).
|
||||||
|
c.execute('''UPDATE dtf_local.orders SET contact_since=NULL, contact_by=NULL, contact_note=NULL
|
||||||
|
WHERE id=%s''', (parent['id'],))
|
||||||
|
c.execute('UPDATE dtf_local.contact_waits SET ended_at=now() WHERE order_id=%s AND ended_at IS NULL',
|
||||||
|
(parent['id'],))
|
||||||
|
audit('order_proof_answered', order=parent['number'], result=body.result, operator=user)
|
||||||
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post('/api/operator/orders/{uid}/proof-card')
|
||||||
|
def new_proof_card(uid: UUID, user=Depends(can('produce'))):
|
||||||
|
"""A new proof card for an order whose proof was rejected, or that has
|
||||||
|
none yet (an order from before the cards)."""
|
||||||
|
with db.connect() as c:
|
||||||
|
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||||
|
if not row or row.get('parent_id'):
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
if row['cancelled_at'] or row['state'] not in ('rec', 'tra') or row['proof_ok_at'] or proof.open_child(c, uid):
|
||||||
|
raise HTTPException(409, 'Este pedido já tem uma prova em andamento ou aprovada.')
|
||||||
|
child = proof.create_child(c, row)
|
||||||
|
if not child:
|
||||||
|
raise HTTPException(409, 'Este pedido não leva prova.')
|
||||||
|
audit('order_proof_card', order=row['number'], operator=user)
|
||||||
|
return {'ok': True, 'id': child['id'], 'number': child['number']}
|
||||||
|
|
||||||
|
|
||||||
@router.post('/api/operator/orders/{uid}/proof')
|
@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:
|
||||||
@@ -806,9 +1000,10 @@ def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(oper
|
|||||||
if not body.after and not body.before:
|
if not body.after and not body.before:
|
||||||
raise HTTPException(422, 'Informe entre quais pedidos ele fica.')
|
raise HTTPException(422, 'Informe entre quais pedidos ele fica.')
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
row = c.execute('SELECT state, machine_id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
row = c.execute('SELECT id,parent_id,proof_ok_at,state,machine_id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, 'Order not found')
|
raise HTTPException(404, 'Order not found')
|
||||||
|
proof.require_unlocked(c, row)
|
||||||
if not may_reorder(request.state.operator['role'], row['state']):
|
if not may_reorder(request.state.operator['role'], row['state']):
|
||||||
raise HTTPException(403, 'Seu perfil não muda a ordem dos pedidos desta etapa.')
|
raise HTTPException(403, 'Seu perfil não muda a ordem dos pedidos desta etapa.')
|
||||||
mine = request.state.operator['machine']
|
mine = request.state.operator['machine']
|
||||||
@@ -846,6 +1041,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
|||||||
raise HTTPException(409, 'O pedido mudou. Clique em Atualizar.')
|
raise HTTPException(409, 'O pedido mudou. Clique em Atualizar.')
|
||||||
if row.get('cancelled_at'):
|
if row.get('cancelled_at'):
|
||||||
raise HTTPException(409, 'Pedido cancelado.')
|
raise HTTPException(409, 'Pedido cancelado.')
|
||||||
|
proof.require_unlocked(c, row)
|
||||||
if body.state == row['state']:
|
if body.state == row['state']:
|
||||||
return row
|
return row
|
||||||
back = BACK.get(row['state']) == body.state
|
back = BACK.get(row['state']) == body.state
|
||||||
@@ -858,9 +1054,8 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
|||||||
raise HTTPException(422, 'Informe o motivo da correção.')
|
raise HTTPException(422, 'Informe o motivo da correção.')
|
||||||
if back and not body.reason.strip():
|
if back and not body.reason.strip():
|
||||||
raise HTTPException(422, 'Informe por que o pedido está voltando de etapa.')
|
raise HTTPException(422, 'Informe por que o pedido está voltando de etapa.')
|
||||||
# The machine of this session (item 12): pulling a card from the queue
|
# The machine of this session takes a card when it is pulled. A proof
|
||||||
# makes it that machine's ("a máquina real do card é a que puxou"); an
|
# and its parent must keep the same physical machine.
|
||||||
# operator pulls any card but moves only their machine's.
|
|
||||||
account = request.state.operator
|
account = request.state.operator
|
||||||
session_machine = account['machine']
|
session_machine = account['machine']
|
||||||
pulling = row['state'] == 'tra' and body.state == 'imp'
|
pulling = row['state'] == 'tra' and body.state == 'imp'
|
||||||
@@ -869,14 +1064,26 @@ 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']):
|
if pulling:
|
||||||
prints = c.execute('SELECT products FROM dtf_local.machines WHERE id=%s', (session_machine['id'],)).fetchone()
|
chosen = body.machine_id or (UUID(session_machine['id']) if session_machine else row['machine_id'])
|
||||||
if machines.product_family(row) in (prints or {}).get('products', []):
|
if not chosen:
|
||||||
row['machine_id'] = session_machine['id']
|
raise HTTPException(409, 'Escolha a máquina que está puxando este card.')
|
||||||
|
if account['role'] == 'operador' and str(chosen) != session_machine['id']:
|
||||||
|
raise HTTPException(409, f"Você está na {session_machine['name']}: o que você puxa vai para ela.")
|
||||||
|
target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (chosen,)).fetchone()
|
||||||
|
if not target or not target['active']:
|
||||||
|
raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.')
|
||||||
|
if machines.product_family(row) not in target['products']:
|
||||||
|
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
|
||||||
|
linked = c.execute('''SELECT machine_id FROM dtf_local.orders WHERE parent_id=%s
|
||||||
|
AND proof_result='ok' AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone()
|
||||||
|
if linked and linked['machine_id'] and chosen != linked['machine_id']:
|
||||||
|
raise HTTPException(409, 'Puxe o pedido na mesma máquina que imprimiu a prova.')
|
||||||
|
row['machine_id'] = chosen
|
||||||
|
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s', (chosen, uid))
|
||||||
|
if row['parent_id']:
|
||||||
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s',
|
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s',
|
||||||
(session_machine['id'], uid))
|
(chosen, row['parent_id']))
|
||||||
elif account['role'] == 'operador':
|
|
||||||
raise HTTPException(409, f"A {session_machine['name']} não imprime este produto.")
|
|
||||||
# Arte conferida is the queue: what enters it has its final files approved.
|
# Arte conferida is the queue: what enters it has its final files approved.
|
||||||
if body.state in ('tra','imp'):
|
if body.state in ('tra','imp'):
|
||||||
coverage = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
|
coverage = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f
|
||||||
@@ -886,7 +1093,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,11 +1111,18 @@ 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=CASE WHEN %s='tra' AND parent_id IS NOT NULL THEN -extract(epoch FROM now()) ELSE NULL END,
|
||||||
receipt_due_at=CASE WHEN %s THEN COALESCE(receipt_due_at, now()) ELSE receipt_due_at END
|
receipt_due_at=CASE WHEN %s THEN COALESCE(receipt_due_at, now()) ELSE receipt_due_at END
|
||||||
WHERE id=%s RETURNING *''', (body.state, due, uid)).fetchone()
|
WHERE id=%s RETURNING *''', (body.state, body.state, due, uid)).fetchone()
|
||||||
# Entering the queue (Arte conferida) is Tiny's "Preparando envio";
|
# Entering the queue (Arte conferida) is Tiny's "Preparando envio";
|
||||||
# Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23).
|
# Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23).
|
||||||
events = {'tra':'production_started','cor':'correction_needed','fin':'ready'}
|
events = {'tra':'production_started','cor':'correction_needed','fin':'ready'}
|
||||||
@@ -927,9 +1147,10 @@ def regenerate(uid: UUID, user=Depends(can('produce'))):
|
|||||||
"""Queue generation again for items that failed or went to manual preparation,
|
"""Queue generation again for items that failed or went to manual preparation,
|
||||||
and for orders paid before the generator existed."""
|
and for orders paid before the generator existed."""
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
row = c.execute('SELECT id,snapshot,state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
row = c.execute('SELECT id,parent_id,proof_ok_at,snapshot,state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, 'Order not found')
|
raise HTTPException(404, 'Order not found')
|
||||||
|
proof.require_unlocked(c, row)
|
||||||
if row['state'] not in ('rec','tra'):
|
if row['state'] not in ('rec','tra'):
|
||||||
raise HTTPException(409, 'Print files are generated only before the order is queued')
|
raise HTTPException(409, 'Print files are generated only before the order is queued')
|
||||||
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1", (uid,)).fetchone():
|
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1", (uid,)).fetchone():
|
||||||
@@ -1036,7 +1257,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"
|
||||||
@@ -1150,6 +1372,50 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
|||||||
LEFT JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m
|
LEFT JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m
|
||||||
WHERE m.order_id=o.id AND m.to_state='fin') f ON true
|
WHERE m.order_id=o.id AND m.to_state='fin') f ON true
|
||||||
WHERE {REAL_ORDER} AND {within} GROUP BY o.origin''', period).fetchall()}
|
WHERE {REAL_ORDER} AND {within} GROUP BY o.origin''', period).fetchall()}
|
||||||
|
# Speed (item 0.12): the browser's marks on the way to a quote, the
|
||||||
|
# Prumo's print generation and the time from payment event to card.
|
||||||
|
site_speed = c.execute(f'''WITH samples AS (
|
||||||
|
SELECT (o.snapshot->'timings'->>'page_ms')::numeric AS page_ms,
|
||||||
|
(o.snapshot->'timings'->>'upload_ms')::numeric AS upload_ms,
|
||||||
|
(o.snapshot->'timings'->>'upload_bytes')::numeric AS upload_bytes,
|
||||||
|
(o.snapshot->'timings'->>'analysis_ms')::numeric AS analysis_ms,
|
||||||
|
(o.snapshot->'timings'->>'montage_ms')::numeric AS montage_ms
|
||||||
|
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within})
|
||||||
|
SELECT
|
||||||
|
percentile_cont(0.5) WITHIN GROUP (ORDER BY page_ms) AS page_avg,
|
||||||
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY page_ms) AS page_p95, count(page_ms) AS page_n,
|
||||||
|
percentile_cont(0.5) WITHIN GROUP (ORDER BY (upload_bytes/1048576.0)/(upload_ms/1000.0))
|
||||||
|
FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_avg,
|
||||||
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY (upload_bytes/1048576.0)/(upload_ms/1000.0))
|
||||||
|
FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_p95,
|
||||||
|
count(*) FILTER (WHERE upload_ms>0 AND upload_bytes>0) AS upload_n,
|
||||||
|
percentile_cont(0.5) WITHIN GROUP (ORDER BY analysis_ms) AS analysis_avg,
|
||||||
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY analysis_ms) AS analysis_p95, count(analysis_ms) AS analysis_n,
|
||||||
|
percentile_cont(0.5) WITHIN GROUP (ORDER BY montage_ms) AS montage_avg,
|
||||||
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY montage_ms) AS montage_p95, count(montage_ms) AS montage_n
|
||||||
|
FROM samples''', period).fetchone()
|
||||||
|
print_speed = c.execute(f'''WITH samples AS (
|
||||||
|
SELECT extract(epoch FROM (p.finished_at-p.created_at)) AS seconds,
|
||||||
|
COALESCE((o.snapshot->'items'->p.item_index->>'metres')::numeric,
|
||||||
|
(o.snapshot->'items'->p.item_index->>'billed_metres')::numeric, 0) AS metres
|
||||||
|
FROM dtf_local.print_files p JOIN dtf_local.orders o ON o.id=p.order_id
|
||||||
|
WHERE {REAL_ORDER} AND {within} AND p.status='ready' AND p.finished_at IS NOT NULL
|
||||||
|
AND p.item_index < jsonb_array_length(o.snapshot->'items'))
|
||||||
|
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY seconds) AS avg_s,
|
||||||
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n,
|
||||||
|
percentile_cont(0.5) WITHIN GROUP (ORDER BY seconds/NULLIF(metres/10,0))
|
||||||
|
FILTER (WHERE metres>0) AS per10_avg,
|
||||||
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds/NULLIF(metres/10,0))
|
||||||
|
FILTER (WHERE metres>0) AS per10_p95,
|
||||||
|
count(*) FILTER (WHERE metres>0) AS per10_n
|
||||||
|
FROM samples''', period).fetchone()
|
||||||
|
card_speed = c.execute(f'''WITH samples AS (
|
||||||
|
SELECT extract(epoch FROM (o.created_at - min(e.received_at))) AS seconds
|
||||||
|
FROM dtf_local.orders o JOIN dtf_local.payment_events e ON e.reference=o.quote_id::text
|
||||||
|
WHERE {REAL_ORDER} AND {within} GROUP BY o.id)
|
||||||
|
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY seconds) AS avg_s,
|
||||||
|
percentile_cont(0.95) WITHIN GROUP (ORDER BY seconds) AS p95_s, count(*) AS n
|
||||||
|
FROM samples WHERE seconds >= 0''', period).fetchone()
|
||||||
series = []
|
series = []
|
||||||
for offset in range((end - start).days + 1):
|
for offset in range((end - start).days + 1):
|
||||||
day = start + timedelta(days=offset)
|
day = start + timedelta(days=offset)
|
||||||
@@ -1171,9 +1437,32 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
|
|||||||
'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'],
|
'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'],
|
||||||
'median_hours': hours(row['median_hours'])} for row in stages},
|
'median_hours': hours(row['median_hours'])} for row in stages},
|
||||||
'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting},
|
'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting},
|
||||||
|
'speed': speed_figures(site_speed, print_speed, card_speed),
|
||||||
'machines': printed, 'rework': rework_figures(printed, redone, by_printer, undecided)}
|
'machines': printed, 'rework': rework_figures(printed, redone, by_printer, undecided)}
|
||||||
|
|
||||||
|
|
||||||
|
def speed_figures(site, generation, card):
|
||||||
|
"""Números' speed block: average and p95, in seconds except upload (MB/s)."""
|
||||||
|
def pair(avg, p95, n, scale=1):
|
||||||
|
return {'average': round(float(avg)/scale, 2) if avg is not None else None,
|
||||||
|
'p95': round(float(p95)/scale, 2) if p95 is not None else None,
|
||||||
|
'samples': int(n or 0)}
|
||||||
|
return [
|
||||||
|
{'key': 'page', 'label': 'Abrir o montador', 'unit': 's',
|
||||||
|
**pair(site['page_avg'], site['page_p95'], site['page_n'], 1000)},
|
||||||
|
{'key': 'upload', 'label': 'Subir o arquivo', 'unit': 'MB/s',
|
||||||
|
**pair(site['upload_avg'], site['upload_p95'], site['upload_n'])},
|
||||||
|
{'key': 'analysis', 'label': 'Conferência do Prumo', 'unit': 's',
|
||||||
|
**pair(site['analysis_avg'], site['analysis_p95'], site['analysis_n'], 1000)},
|
||||||
|
{'key': 'montage', 'label': 'Montagem das avulsas', 'unit': 's',
|
||||||
|
**pair(site['montage_avg'], site['montage_p95'], site['montage_n'], 1000)},
|
||||||
|
{'key': 'print', 'label': 'Gerar arquivo final (10 m)', 'unit': 's',
|
||||||
|
**pair(generation['per10_avg'], generation['per10_p95'], generation['per10_n'])},
|
||||||
|
{'key': 'card', 'label': 'Card em Arte recebida', 'unit': 's',
|
||||||
|
**pair(card['avg_s'], card['p95_s'], card['n'])},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def rework_figures(printed, redone, by_printer, undecided):
|
def rework_figures(printed, redone, by_printer, undecided):
|
||||||
"""Números' rework: per cause, the metres redone over the film printed,
|
"""Números' rework: per cause, the metres redone over the film printed,
|
||||||
against the goal; the house's total against four times it."""
|
against the goal; the house's total against four times it."""
|
||||||
@@ -1294,21 +1583,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 +1674,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
|
||||||
@@ -1377,7 +1745,7 @@ def queue_folder(body: FolderSync, user=Depends(can('print'))):
|
|||||||
|
|
||||||
|
|
||||||
@router.get('/api/operator/uploads/{uid}/download')
|
@router.get('/api/operator/uploads/{uid}/download')
|
||||||
def download(uid: UUID, user=Depends(operator)):
|
def download(uid: UUID, order_id: UUID | None = None, user=Depends(operator)):
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
row = c.execute('SELECT * FROM dtf_local.uploads WHERE id=%s AND complete', (uid,)).fetchone()
|
row = c.execute('SELECT * FROM dtf_local.uploads WHERE id=%s AND complete', (uid,)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
@@ -1385,4 +1753,15 @@ def download(uid: UUID, user=Depends(operator)):
|
|||||||
if row['expires_at'] <= datetime.now(timezone.utc):
|
if row['expires_at'] <= datetime.now(timezone.utc):
|
||||||
raise HTTPException(410, 'Artwork retention expired')
|
raise HTTPException(410, 'Artwork retention expired')
|
||||||
require_clean(row)
|
require_clean(row)
|
||||||
return {'name':row['name'], 'url':storage.download(row['object_key'],row['name']), 'expires_in':300}
|
name = row['name']
|
||||||
|
if order_id:
|
||||||
|
order = c.execute('SELECT number,snapshot FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone()
|
||||||
|
if not order:
|
||||||
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
originals = [upload for item in order['snapshot']['items'] for upload in item['uploads']]
|
||||||
|
if str(uid) not in originals:
|
||||||
|
raise HTTPException(422, 'Este arquivo não é original do pedido.')
|
||||||
|
index = originals.index(str(uid)) + 1
|
||||||
|
suffix = row['name'].rsplit('.', 1)[-1].lower() if '.' in row['name'] else 'bin'
|
||||||
|
name = f'DTF-{order["number"]}-original-{index}.{suffix}'
|
||||||
|
return {'name':name, 'url':storage.download(row['object_key'],name), 'expires_in':300}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"""Quotes: the customer's cart, approved at once when it can be (app/quote_review.py)."""
|
"""Quotes: the customer's cart, approved at once when it can be (app/quote_review.py)."""
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
|
from datetime import datetime, timezone
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from uuid import UUID, uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
@@ -13,7 +14,7 @@ from ..core.auth import owner
|
|||||||
from ..core.models import QuoteRequest
|
from ..core.models import QuoteRequest
|
||||||
from ..core.pricing import price
|
from ..core.pricing import price
|
||||||
from .. import quote_review
|
from .. import quote_review
|
||||||
from ..grade_check import Files, mismatch
|
from ..grade_check import Files, mismatch, resolution_issue
|
||||||
from ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
|
from ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
|
||||||
from ..scanning import require_clean
|
from ..scanning import require_clean
|
||||||
|
|
||||||
@@ -27,6 +28,12 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
|||||||
require_delivery_available(body.freight.service)
|
require_delivery_available(body.freight.service)
|
||||||
draft = body.model_dump(mode='json', exclude={'request_key'})
|
draft = body.model_dump(mode='json', exclude={'request_key'})
|
||||||
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
|
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
|
||||||
|
accepted_at = datetime.now(timezone.utc).isoformat()
|
||||||
|
for item in draft['items']:
|
||||||
|
if item.get('residue_accepted'):
|
||||||
|
item['residue_accepted_at'] = accepted_at
|
||||||
|
if item.get('stroke_choice'):
|
||||||
|
item['stroke_choice_at'] = accepted_at
|
||||||
reason = quote_review.review_reason(draft)
|
reason = quote_review.review_reason(draft)
|
||||||
if reason is not None:
|
if reason is not None:
|
||||||
# Waits for review: check the delivery now, priced at approval.
|
# Waits for review: check the delivery now, priced at approval.
|
||||||
@@ -51,7 +58,11 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
|||||||
# The grade came from the browser and is shown with the order (it no
|
# The grade came from the browser and is shown with the order (it no
|
||||||
# longer sets the price): before a cart is approved at checkout, the
|
# longer sets the price): before a cart is approved at checkout, the
|
||||||
# server works it out from the files.
|
# server works it out from the files.
|
||||||
note = mismatch(Files(storage), draft['items'], rows) if reason is None else None
|
files = Files(storage)
|
||||||
|
issue = resolution_issue(files, draft['items'], rows)
|
||||||
|
if issue:
|
||||||
|
raise HTTPException(422, issue)
|
||||||
|
note = mismatch(files, draft['items'], rows) if reason is None else None
|
||||||
reason = reason or note
|
reason = reason or note
|
||||||
uid = uuid4()
|
uid = uuid4()
|
||||||
c.execute('INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,review_note) VALUES(%s,%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING',
|
c.execute('INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,review_note) VALUES(%s,%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING',
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -228,7 +231,6 @@ def create_machine(body: MachineIn, user=Depends(can('users'))):
|
|||||||
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
raise HTTPException(409, 'Já existe uma máquina com este nome.')
|
||||||
c.execute('INSERT INTO dtf_local.machines(id,name,products,active,limit_metres) VALUES(%s,%s,%s,%s,%s)',
|
c.execute('INSERT INTO dtf_local.machines(id,name,products,active,limit_metres) VALUES(%s,%s,%s,%s,%s)',
|
||||||
(mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres))
|
(mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres))
|
||||||
machines.route(c)
|
|
||||||
audit('machine_created', operator=user, machine=body.name)
|
audit('machine_created', operator=user, machine=body.name)
|
||||||
return {'id': str(mid)}
|
return {'id': str(mid)}
|
||||||
|
|
||||||
@@ -245,20 +247,21 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))):
|
|||||||
raise HTTPException(404, 'Máquina não encontrada.')
|
raise HTTPException(404, 'Máquina não encontrada.')
|
||||||
if not body.active:
|
if not body.active:
|
||||||
release_sessions(c, mid)
|
release_sessions(c, mid)
|
||||||
machines.route(c)
|
|
||||||
audit('machine_updated', operator=user, machine=body.name)
|
audit('machine_updated', operator=user, machine=body.name)
|
||||||
return {'ok': True}
|
return {'ok': True}
|
||||||
|
|
||||||
|
|
||||||
@router.post('/api/operator/machines/{mid}/delete')
|
@router.post('/api/operator/machines/{mid}/delete')
|
||||||
def delete_machine(mid: UUID, user=Depends(can('users'))):
|
def delete_machine(mid: UUID, user=Depends(can('users'))):
|
||||||
"""Its orders go back to the automatic choice; its operators lose it."""
|
"""Its orders lose that machine; its operators lose the session choice."""
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
|
if c.execute("SELECT 1 FROM dtf_local.orders WHERE machine_id=%s AND state='imp' AND cancelled_at IS NULL LIMIT 1",
|
||||||
|
(mid,)).fetchone():
|
||||||
|
raise HTTPException(409, 'Há pedido imprimindo nesta máquina. Termine ou mova o pedido antes de excluí-la.')
|
||||||
release_sessions(c, mid)
|
release_sessions(c, mid)
|
||||||
row = c.execute('DELETE FROM dtf_local.machines WHERE id=%s RETURNING name', (mid,)).fetchone()
|
row = c.execute('DELETE FROM dtf_local.machines WHERE id=%s RETURNING name', (mid,)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, 'Máquina não encontrada.')
|
raise HTTPException(404, 'Máquina não encontrada.')
|
||||||
machines.route(c)
|
|
||||||
audit('machine_deleted', operator=user, machine=row['name'])
|
audit('machine_deleted', operator=user, machine=row['name'])
|
||||||
return {'ok': True}
|
return {'ok': True}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ from uuid import UUID, uuid4
|
|||||||
|
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
|
|
||||||
from .runtime import upload_row
|
from .runtime import upload_row, storage
|
||||||
|
from .printpng_validate import require_final_png
|
||||||
from .scanning import require_clean
|
from .scanning import require_clean
|
||||||
|
|
||||||
|
|
||||||
@@ -20,8 +21,9 @@ def generated_owner(c, order, ref, kind):
|
|||||||
from, and only while that item still has its original artwork: after a
|
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 +31,6 @@ def generated_owner(c, order, ref, kind):
|
|||||||
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1",
|
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']
|
||||||
|
|
||||||
|
|
||||||
@@ -84,6 +85,8 @@ def submit_files(c, order, body, identity, kind, actor):
|
|||||||
if not upload['complete']:
|
if not upload['complete']:
|
||||||
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar.')
|
raise HTTPException(409, 'Espere o envio de todos os arquivos terminar.')
|
||||||
require_clean(upload)
|
require_clean(upload)
|
||||||
|
if kind == 'final':
|
||||||
|
require_final_png(storage, upload)
|
||||||
# Attached once, except a correction approved as its own final.
|
# Attached once, except a correction approved as its own final.
|
||||||
if c.execute('SELECT id FROM dtf_local.order_files WHERE upload_id=%s'+(" AND kind<>'correction'" if corrected else ''),
|
if c.execute('SELECT id FROM dtf_local.order_files WHERE upload_id=%s'+(" AND kind<>'correction'" if corrected else ''),
|
||||||
(ref.upload_id,)).fetchone():
|
(ref.upload_id,)).fetchone():
|
||||||
|
|||||||
@@ -46,11 +46,8 @@ def main():
|
|||||||
c.execute(sql.SQL('GRANT USAGE ON SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
|
c.execute(sql.SQL('GRANT USAGE ON SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
|
||||||
c.execute(sql.SQL('GRANT SELECT,INSERT,UPDATE,DELETE ON ALL TABLES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
|
c.execute(sql.SQL('GRANT SELECT,INSERT,UPDATE,DELETE ON ALL TABLES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
|
||||||
c.execute(sql.SQL('GRANT USAGE,SELECT ON ALL SEQUENCES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
|
c.execute(sql.SQL('GRANT USAGE,SELECT ON ALL SEQUENCES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role)))
|
||||||
# ops.launch_reset starts the order numbers again at #1 (setval), once
|
# The order identity sequence is never reset: DTF-1…DTF-15 already
|
||||||
# the test orders are gone; nothing else may change a sequence.
|
# exist as Tiny order numbers (Dropstar, 2026-11-05).
|
||||||
numbers = c.execute("SELECT pg_get_serial_sequence('dtf_local.orders','number')").fetchone()[0]
|
|
||||||
c.execute(sql.SQL('GRANT UPDATE ON SEQUENCE {} TO {}').format(
|
|
||||||
sql.Identifier(*numbers.split('.', 1)), sql.Identifier(role)))
|
|
||||||
# Turn the configured credential into a real account so an existing
|
# Turn the configured credential into a real account so an existing
|
||||||
# deployment keeps logging in exactly as before. Inserts only when that
|
# deployment keeps logging in exactly as before. Inserts only when that
|
||||||
# email is absent, so a password changed with local.operators is never
|
# email is absent, so a password changed with local.operators is never
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|||||||
@@ -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,22 @@ 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
|
||||||
|
# Where the thinnest stroke sits in the assembled film, from 0 (top) to 1
|
||||||
|
# (bottom): the proof card crops a 15 cm window around it (Dropstar, 05/11).
|
||||||
|
proof_y_fraction: Decimal | None = Field(default=None, ge=0, le=1)
|
||||||
|
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')
|
||||||
@@ -205,6 +240,19 @@ class Item(StrictModel):
|
|||||||
raise ValueError('Resolution warning must be acknowledged')
|
raise ValueError('Resolution warning must be acknowledged')
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
class ClientTimings(StrictModel):
|
||||||
|
"""What the browser measured on the way to a quote (item 0.12).
|
||||||
|
|
||||||
|
They are only numbers for Números; a cart may send none of them, and the
|
||||||
|
server never uses them to price or accept an order.
|
||||||
|
"""
|
||||||
|
page_ms: int | None = Field(default=None, ge=0, le=600000)
|
||||||
|
upload_ms: int | None = Field(default=None, ge=0, le=3600000)
|
||||||
|
upload_bytes: int | None = Field(default=None, ge=0, le=10**12)
|
||||||
|
analysis_ms: int | None = Field(default=None, ge=0, le=3600000)
|
||||||
|
montage_ms: int | None = Field(default=None, ge=0, le=3600000)
|
||||||
|
|
||||||
|
|
||||||
class QuoteRequest(StrictModel):
|
class QuoteRequest(StrictModel):
|
||||||
request_key: UUID
|
request_key: UUID
|
||||||
customer: Customer
|
customer: Customer
|
||||||
@@ -213,6 +261,13 @@ class QuoteRequest(StrictModel):
|
|||||||
destination: Destination | None = None
|
destination: Destination | None = None
|
||||||
# "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
|
||||||
|
# What the browser measured while the customer built the cart (item 0.12).
|
||||||
|
timings: ClientTimings | None = None
|
||||||
|
|
||||||
|
@model_validator(mode='after')
|
||||||
|
def splits_complete(self):
|
||||||
|
check_splits(self.items)
|
||||||
|
return self
|
||||||
|
|
||||||
@model_validator(mode='after')
|
@model_validator(mode='after')
|
||||||
def destination_matches_freight(self):
|
def destination_matches_freight(self):
|
||||||
@@ -228,6 +283,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 +324,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)
|
||||||
|
|||||||
@@ -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 ''
|
||||||
|
|||||||
@@ -23,7 +23,9 @@ import os
|
|||||||
import struct
|
import struct
|
||||||
import tempfile
|
import tempfile
|
||||||
|
|
||||||
DPI_IDEAL = 300
|
DPI_IDEAL = 200
|
||||||
|
DPI_REFUSE = 96
|
||||||
|
PDF_VECTOR_DPI = 300
|
||||||
# The Site analyses PDFs up to 150 MB (GRANDE_BYTES); above that it does not
|
# The Site analyses PDFs up to 150 MB (GRANDE_BYTES); above that it does not
|
||||||
# grade them, so neither does this.
|
# grade them, so neither does this.
|
||||||
PDF_MAX_BYTES = 150 * 1048576
|
PDF_MAX_BYTES = 150 * 1048576
|
||||||
@@ -123,7 +125,7 @@ def pdf_dpi(path):
|
|||||||
return None
|
return None
|
||||||
found = [(dpi, area) for dpi, area in found if dpi > 0]
|
found = [(dpi, area) for dpi, area in found if dpi > 0]
|
||||||
if not found:
|
if not found:
|
||||||
return DPI_IDEAL
|
return PDF_VECTOR_DPI
|
||||||
total = sum(area for _, area in found) or 1
|
total = sum(area for _, area in found) or 1
|
||||||
return js_round(sum(dpi * area for dpi, area in found) / total)
|
return js_round(sum(dpi * area for dpi, area in found) / total)
|
||||||
|
|
||||||
@@ -178,6 +180,31 @@ def item_grade(files, item, rows):
|
|||||||
return js_round(sum(grade_of(d) for d in dpis) / len(dpis))
|
return js_round(sum(grade_of(d) for d in dpis) / len(dpis))
|
||||||
|
|
||||||
|
|
||||||
|
def resolution_issue(files, items, rows):
|
||||||
|
"""Refuse sub-96 DPI and require recorded consent for measurable 96–199 DPI.
|
||||||
|
|
||||||
|
Unknown formats remain for manual review; they cannot be treated as a
|
||||||
|
measured zero DPI or silently called high-resolution artwork.
|
||||||
|
"""
|
||||||
|
for index, item in enumerate(items, 1):
|
||||||
|
dpis = []
|
||||||
|
for source in item['production']['sources']:
|
||||||
|
row = rows.get(str(source['upload_id']))
|
||||||
|
dpi = source_dpi(files, row, source) if row else None
|
||||||
|
if dpi is None:
|
||||||
|
dpis = []
|
||||||
|
break
|
||||||
|
dpis.append(dpi)
|
||||||
|
if not dpis:
|
||||||
|
continue
|
||||||
|
lowest = min(dpis)
|
||||||
|
if lowest < DPI_REFUSE:
|
||||||
|
return f'Item {index}: resolução de {js_round(lowest)} DPI abaixo do mínimo de {DPI_REFUSE} DPI.'
|
||||||
|
if lowest < DPI_IDEAL and (item['quality_status'] != 'warning' or not item['quality_acknowledged']):
|
||||||
|
return f'Item {index}: confirme a ressalva de resolução entre {DPI_REFUSE} e {DPI_IDEAL - 1} DPI.'
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def mismatch(files, items, rows):
|
def mismatch(files, items, rows):
|
||||||
"""Why a cart's grades cannot be approved at checkout, or None."""
|
"""Why a cart's grades cannot be approved at checkout, or None."""
|
||||||
for item in items:
|
for item in items:
|
||||||
|
|||||||
136
app/hotfolder.py
Normal file
136
app/hotfolder.py
Normal 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}
|
||||||
@@ -1,20 +1,8 @@
|
|||||||
"""The print machines: which one each order goes to, and how loaded each is.
|
"""The print machines, their load and the two printing places on each one."""
|
||||||
|
|
||||||
An order gets its machine once, and keeps it: someone's choice in the order
|
|
||||||
panel, or else the active machine that prints its product with the fewest
|
|
||||||
metres still open, among those below their limit (or, all of them full, the
|
|
||||||
least loaded anyway; the machine then shows it is over its limit). A machine
|
|
||||||
switched off, deleted or no longer printing the product gives its automatic
|
|
||||||
orders back to that choice, unless they are already printing.
|
|
||||||
"""
|
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
|
||||||
# Not finished: the work still ahead of a machine.
|
# Not finished: the work still ahead of a machine.
|
||||||
OPEN = ('rec', 'tra', 'imp', 'cor')
|
OPEN = ('rec', 'tra', 'imp', 'cor')
|
||||||
# Stages an automatic order may still move from: not once it is printing.
|
|
||||||
MOVABLE = ('rec', 'tra', 'cor')
|
|
||||||
# One routing at a time, so two at once cannot both pick the same "least loaded".
|
|
||||||
LOCK = 7_041_901
|
|
||||||
# Two orders at most in Imprimindo per machine (Dropstar, 2026-10-29): one
|
# Two orders at most in Imprimindo per machine (Dropstar, 2026-10-29): one
|
||||||
# printing, the next being ripped by FlexiPRINT meanwhile. A third would
|
# printing, the next being ripped by FlexiPRINT meanwhile. A third would
|
||||||
# make the RIP choke; two mean the next sheet is ready when one ends.
|
# make the RIP choke; two mean the next sheet is ready when one ends.
|
||||||
@@ -44,49 +32,6 @@ def loads(c):
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def pick(machines, load, order):
|
|
||||||
"""The machine for one order, or None when none prints its product."""
|
|
||||||
family, metres = product_family(order), order_metres(order)
|
|
||||||
able = [m for m in machines if m['active'] and family in m['products']]
|
|
||||||
if not able:
|
|
||||||
return None
|
|
||||||
used = lambda m: load.get(str(m['id']), Decimal(0))
|
|
||||||
room = [m for m in able if m['limit_metres'] is None or used(m) + metres <= m['limit_metres']]
|
|
||||||
# min() keeps the first of equals: the machine registered first.
|
|
||||||
return min(room or able, key=used)
|
|
||||||
|
|
||||||
|
|
||||||
def route(c):
|
|
||||||
"""Give every open order without a machine its automatic one."""
|
|
||||||
# A choice whose machine was deleted is no choice any more.
|
|
||||||
c.execute('UPDATE dtf_local.orders SET machine_chosen=false WHERE machine_id IS NULL AND machine_chosen')
|
|
||||||
# Automatic orders on a machine that can no longer take them, before printing.
|
|
||||||
c.execute('''UPDATE dtf_local.orders o SET machine_id=NULL FROM dtf_local.machines m
|
|
||||||
WHERE o.machine_id=m.id AND NOT o.machine_chosen AND o.state=ANY(%s) AND o.cancelled_at IS NULL
|
|
||||||
AND (NOT m.active OR NOT ((CASE WHEN o.snapshot->'items'->0->>'mode' IN ('uv','uvfile')
|
|
||||||
THEN 'uv' ELSE 'textil' END)=ANY(m.products)))''', (list(MOVABLE),))
|
|
||||||
waiting = c.execute('''SELECT id, snapshot FROM dtf_local.orders
|
|
||||||
WHERE machine_id IS NULL AND cancelled_at IS NULL AND state=ANY(%s)
|
|
||||||
ORDER BY created_at, number''', (list(OPEN),)).fetchall()
|
|
||||||
if not waiting:
|
|
||||||
return 0
|
|
||||||
c.execute('SELECT pg_advisory_xact_lock(%s)', (LOCK,))
|
|
||||||
machines = c.execute('''SELECT id, products, active, limit_metres FROM dtf_local.machines
|
|
||||||
ORDER BY created_at, name''').fetchall()
|
|
||||||
load = {k: v['metres'] for k, v in loads(c).items()}
|
|
||||||
routed = 0
|
|
||||||
for order in waiting:
|
|
||||||
machine = pick(machines, load, order)
|
|
||||||
if machine is None:
|
|
||||||
continue
|
|
||||||
if c.execute('''UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=false
|
|
||||||
WHERE id=%s AND machine_id IS NULL RETURNING id''', (machine['id'], order['id'])).fetchone():
|
|
||||||
key = str(machine['id'])
|
|
||||||
load[key] = load.get(key, Decimal(0)) + order_metres(order)
|
|
||||||
routed += 1
|
|
||||||
return routed
|
|
||||||
|
|
||||||
|
|
||||||
def rows(c, with_operators=False):
|
def rows(c, with_operators=False):
|
||||||
"""Every machine with its load, for the Kanban."""
|
"""Every machine with its load, for the Kanban."""
|
||||||
machines = c.execute('''SELECT id, name, products, active, limit_metres FROM dtf_local.machines
|
machines = c.execute('''SELECT id, name, products, active, limit_metres FROM dtf_local.machines
|
||||||
|
|||||||
@@ -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),
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ from uuid import UUID, uuid4
|
|||||||
|
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
from . import machines, mail, proof
|
from . import mail, proof
|
||||||
from .core.auth import audit
|
from .core.auth import audit
|
||||||
from .core.models import PRODUCTION_VERSIONS
|
from .core.models import PRODUCTION_VERSIONS
|
||||||
from .printjobs import queue as queue_print_files
|
from .printjobs import queue as queue_print_files
|
||||||
@@ -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,7 +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'],))
|
||||||
machines.route(c)
|
# An order with a proof gets its proof card (app/proof.py).
|
||||||
|
proof.create_child(c, order)
|
||||||
if is_test(order):
|
if is_test(order):
|
||||||
return order, True
|
return order, True
|
||||||
mail.order_paid(c, order, PUBLIC_ORIGIN)
|
mail.order_paid(c, order, PUBLIC_ORIGIN)
|
||||||
|
|||||||
@@ -380,13 +380,14 @@ def open_source(path, name):
|
|||||||
return SourceImage(path, name)
|
return SourceImage(path, name)
|
||||||
|
|
||||||
|
|
||||||
def check_layout(item, sizes, vector=()):
|
def check_layout(item, sizes, vector=(), proof=False):
|
||||||
"""Refuse a layout the file cannot reproduce faithfully. Returns the lowest
|
"""Refuse a layout the file cannot reproduce faithfully. Returns the lowest
|
||||||
DPI of the raster sources (vector pages have none)."""
|
DPI of the raster sources (vector pages have none). A proof is free of
|
||||||
|
charge, so its zero billed metres must not reject the item's full sheet."""
|
||||||
production = item['production']
|
production = item['production']
|
||||||
height = Decimal(str(production['height_cm']))
|
height = Decimal(str(production['height_cm']))
|
||||||
billed = Decimal(str(item['billed_metres'])) * 100
|
billed = Decimal(str(item['billed_metres'])) * 100
|
||||||
if height > billed + HEIGHT_TOLERANCE_CM:
|
if not proof and height > billed + HEIGHT_TOLERANCE_CM:
|
||||||
raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados')
|
raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados')
|
||||||
lowest = None
|
lowest = None
|
||||||
for placement in production['placements']:
|
for placement in production['placements']:
|
||||||
|
|||||||
209
app/printjobs.py
209
app/printjobs.py
@@ -5,21 +5,24 @@ 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 multiprocessing
|
||||||
import os
|
import os
|
||||||
|
import shutil
|
||||||
import tempfile
|
import tempfile
|
||||||
import time
|
import time
|
||||||
|
from queue import Empty
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from zoneinfo import ZoneInfo
|
from zoneinfo import ZoneInfo
|
||||||
@@ -29,16 +32,20 @@ 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.
|
||||||
|
RENDER_SECONDS = int(os.environ.get('PRINT_RENDER_TIMEOUT_SECONDS', '900'))
|
||||||
|
CLAIM_TIMEOUT = timedelta(minutes=18)
|
||||||
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):
|
||||||
@@ -51,9 +58,10 @@ def queue(c, order_id, items, only_missing=False):
|
|||||||
if only_missing:
|
if only_missing:
|
||||||
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
|
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
|
||||||
ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0,
|
ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0,
|
||||||
claimed_at=NULL, finished_at=NULL, detail='{}'
|
claimed_at=NULL, claim_token=NULL, finished_at=NULL, upload_id=NULL, detail='{}'
|
||||||
WHERE dtf_local.print_files.status IN ('failed','manual')''',
|
WHERE dtf_local.print_files.status IN ('failed','manual') OR
|
||||||
(uuid4(), order_id, index))
|
(dtf_local.print_files.status='rendering' AND dtf_local.print_files.claimed_at<now()-%s)''',
|
||||||
|
(uuid4(), order_id, index, CLAIM_TIMEOUT))
|
||||||
else:
|
else:
|
||||||
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
|
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
|
||||||
ON CONFLICT(order_id,item_index) DO NOTHING''', (uuid4(), order_id, index))
|
ON CONFLICT(order_id,item_index) DO NOTHING''', (uuid4(), order_id, index))
|
||||||
@@ -63,7 +71,43 @@ def claim(c):
|
|||||||
return c.execute('''SELECT p.*, o.snapshot, o.number, o.created_at AS ordered_at FROM dtf_local.print_files p
|
return c.execute('''SELECT p.*, o.snapshot, o.number, o.created_at AS ordered_at FROM dtf_local.print_files p
|
||||||
JOIN dtf_local.orders o ON o.id=p.order_id
|
JOIN dtf_local.orders o ON o.id=p.order_id
|
||||||
WHERE p.status='pending' OR (p.status='rendering' AND p.claimed_at < now()-%s)
|
WHERE p.status='pending' OR (p.status='rendering' AND p.claimed_at < now()-%s)
|
||||||
ORDER BY p.created_at FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
|
ORDER BY CASE WHEN o.parent_id IS NOT NULL THEN 0 ELSE 1 END, p.created_at
|
||||||
|
FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
def _render_child(result_queue, job, item, uploads):
|
||||||
|
"""Render in a killable process: a stuck image decoder cannot hold a card forever."""
|
||||||
|
from .adapters import LocalS3Storage
|
||||||
|
try:
|
||||||
|
result_queue.put(('ready', produce(LocalS3Storage(), job, item, uploads)))
|
||||||
|
except Unsupported as reason:
|
||||||
|
result_queue.put(('manual', str(reason)))
|
||||||
|
except BaseException as exc:
|
||||||
|
logging.exception('Print file generation failed')
|
||||||
|
result_queue.put(('error', type(exc).__name__))
|
||||||
|
|
||||||
|
|
||||||
|
def render_with_timeout(job, item, uploads):
|
||||||
|
ctx = multiprocessing.get_context('spawn')
|
||||||
|
result_queue = ctx.Queue()
|
||||||
|
process = ctx.Process(target=_render_child, args=(result_queue, job, item, uploads))
|
||||||
|
process.start()
|
||||||
|
try:
|
||||||
|
process.join(RENDER_SECONDS)
|
||||||
|
if process.is_alive():
|
||||||
|
process.terminate()
|
||||||
|
process.join(5)
|
||||||
|
if process.is_alive():
|
||||||
|
process.kill()
|
||||||
|
process.join()
|
||||||
|
return 'timeout', None
|
||||||
|
try:
|
||||||
|
return result_queue.get(timeout=5)
|
||||||
|
except Empty:
|
||||||
|
return 'error', f'processo encerrou com código {process.exitcode}'
|
||||||
|
finally:
|
||||||
|
result_queue.close()
|
||||||
|
result_queue.join_thread()
|
||||||
|
|
||||||
|
|
||||||
def render_one(storage):
|
def render_one(storage):
|
||||||
@@ -71,8 +115,10 @@ def render_one(storage):
|
|||||||
job = claim(c)
|
job = claim(c)
|
||||||
if not job:
|
if not job:
|
||||||
return False
|
return False
|
||||||
|
token = uuid4()
|
||||||
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
|
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
|
||||||
attempts=attempts+1 WHERE id=%s''', (job['id'],))
|
attempts=attempts+1,claim_token=%s WHERE id=%s''', (token, job['id']))
|
||||||
|
job['claim_token'] = token
|
||||||
item = job['snapshot']['items'][job['item_index']]
|
item = job['snapshot']['items'][job['item_index']]
|
||||||
uploads = c.execute('''SELECT id,name,size,object_key,scan_state,purged_at,expires_at,
|
uploads = c.execute('''SELECT id,name,size,object_key,scan_state,purged_at,expires_at,
|
||||||
(expires_at<=now()) AS expired FROM dtf_local.uploads WHERE id=ANY(%s)''',
|
(expires_at<=now()) AS expired FROM dtf_local.uploads WHERE id=ANY(%s)''',
|
||||||
@@ -81,65 +127,80 @@ 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
|
||||||
try:
|
outcome, result = render_with_timeout(job, item, by_id)
|
||||||
result = produce(storage, job, item, by_id)
|
if outcome == 'manual':
|
||||||
except Unsupported as reason:
|
finish(job, 'manual', {'reason': result})
|
||||||
finish(job, 'manual', {'reason': str(reason)})
|
|
||||||
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
|
||||||
except Exception as exc:
|
if outcome == 'timeout':
|
||||||
logging.exception('Print file generation failed')
|
finish(job, 'failed', {'reason': f'Tempo limite de {RENDER_SECONDS // 60} min excedido. Gere de novo.'})
|
||||||
final = job['attempts'] + 1 >= MAX_ATTEMPTS
|
audit('print_file_timeout', order=str(job['order_id']), item=job['item_index'])
|
||||||
finish(job, 'failed' if final else 'pending', {'error': type(exc).__name__})
|
|
||||||
return True
|
return True
|
||||||
path, name, size, detail = result
|
if outcome == 'error':
|
||||||
|
final = job['attempts'] + 1 >= MAX_ATTEMPTS
|
||||||
|
finish(job, 'failed' if final else 'pending', {'error': result,
|
||||||
|
'reason': 'A geração falhou. Gere de novo.' if final else ''})
|
||||||
|
return True
|
||||||
|
scratch, parts, detail = result
|
||||||
|
stored = []
|
||||||
try:
|
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:
|
||||||
|
current = c.execute('''SELECT 1 FROM dtf_local.print_files WHERE id=%s AND claim_token=%s
|
||||||
|
AND status='rendering' FOR UPDATE''', (job['id'], job['claim_token'])).fetchone()
|
||||||
|
if not current:
|
||||||
|
return True
|
||||||
|
for uid, name, size, key in stored:
|
||||||
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
|
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(),claim_token=NULL,claimed_at=NULL 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))
|
||||||
|
if job['snapshot'].get('proof_of'):
|
||||||
|
c.execute('''UPDATE dtf_local.order_files SET active=false
|
||||||
|
WHERE order_id=%s AND item_index=%s AND kind='final' ''',
|
||||||
|
(job['order_id'], job['item_index']))
|
||||||
|
c.execute('''INSERT INTO dtf_local.order_files
|
||||||
|
(id,order_id,upload_id,item_index,kind,note,created_by)
|
||||||
|
VALUES(%s,%s,%s,%s,'final','Prova gerada automaticamente pelo Prumo','Prumo')''',
|
||||||
|
(uuid4(), job['order_id'], stored[0][0], job['item_index']))
|
||||||
|
audit('print_file_ready', order=str(job['order_id']), item=job['item_index'], parts=len(stored))
|
||||||
return True
|
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 +217,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 #{proof_of}',
|
||||||
|
f'Classe {item.get("stroke_class") or "C3"}', 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,37 +231,43 @@ 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:
|
# The child owns its final file; the class names its proof.
|
||||||
with os.fdopen(handle, 'wb') as out:
|
prefix = (f'DTF-{job["number"]}-prova-{item.get("stroke_class") or "C3"}' 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,
|
||||||
|
proof_fraction=item.get('proof_y_fraction') 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):
|
||||||
with connect() as c:
|
with connect() as c:
|
||||||
c.execute('''UPDATE dtf_local.print_files SET status=%s, detail=%s,
|
c.execute('''UPDATE dtf_local.print_files SET status=%s, detail=%s,
|
||||||
finished_at=CASE WHEN %s='pending' THEN NULL ELSE now() END,
|
finished_at=CASE WHEN %s='pending' THEN NULL ELSE now() END,
|
||||||
claimed_at=NULL WHERE id=%s''', (status, Jsonb(detail), status, job['id']))
|
claimed_at=NULL,claim_token=NULL WHERE id=%s AND claim_token=%s AND status='rendering' ''',
|
||||||
|
(status, Jsonb(detail), status, job['id'], job['claim_token']))
|
||||||
|
|
||||||
|
|
||||||
def render_loop(storage):
|
def render_loop(storage):
|
||||||
|
|||||||
539
app/printpng.py
Normal file
539
app/printpng.py
Normal file
@@ -0,0 +1,539 @@
|
|||||||
|
"""The print file as a PNG (Dropstar's third round, item 13, 2026-10-29).
|
||||||
|
|
||||||
|
FlexiPRINT's Spot OK 1 preset makes the white underbase from transparency, and
|
||||||
|
it reads that reliably only from a PNG: the montador writes each order item as
|
||||||
|
a 300 DPI PNG with an alpha channel on a transparent background, the same file
|
||||||
|
from payment to Finalizado. The customer may still send PNG or PDF; the output
|
||||||
|
is always PNG, and nothing converts it afterwards.
|
||||||
|
|
||||||
|
A 57 cm x 15 m sheet is 6732 x 177165 px, 4,7 GB as pixels, so nothing here
|
||||||
|
holds a whole sheet: the film is composed and written in bands of rows.
|
||||||
|
|
||||||
|
- Writing: each band is encoded by Pillow without compression, which still
|
||||||
|
chooses each row's PNG filter, and its filtered rows go into one zlib stream
|
||||||
|
for the whole file.
|
||||||
|
- A long PNG sheet is read band by band the same way backwards: the next
|
||||||
|
band's compressed rows, behind the last decoded row unfiltered, are wrapped
|
||||||
|
as a small PNG of their own that Pillow decodes.
|
||||||
|
- A PDF page is rendered band by band at 300 DPI by PDFium, vector all the way.
|
||||||
|
- Loose artwork is small: each file is decoded, turned and scaled to its place
|
||||||
|
once, and copied into every band it crosses.
|
||||||
|
|
||||||
|
A layout longer than 15 m leaves as parts of up to 15 m (Dropstar,
|
||||||
|
2026-10-30), DTF-7-item-1-p3.png, each with its footer saying which part it
|
||||||
|
is. Loose artwork is cut where no piece crosses; a finished sheet is cut
|
||||||
|
between copies when it can be, and through the artwork when not.
|
||||||
|
"""
|
||||||
|
import io
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import struct
|
||||||
|
import zlib
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
||||||
|
|
||||||
|
from .core.models import PRODUCTION_VERSIONS
|
||||||
|
from .printfile import (FOOTER_CM, FOOTER_LOGO, FOOTER_LOGO_CM, MAX_DECODED_PIXELS, SUPPORTED_FORMATS,
|
||||||
|
Unsupported, check_layout)
|
||||||
|
from .printtiles import Pyramid
|
||||||
|
|
||||||
|
DPI = 300
|
||||||
|
PX_PER_CM = DPI / 2.54
|
||||||
|
# Parts of up to 15 m, 6732 x 177165 px (Dropstar, 2026-10-30).
|
||||||
|
PART_CM = Decimal(os.environ.get('PRINT_PART_CM', '1500'))
|
||||||
|
# A cut through artwork only when no gap between pieces is this close to the limit.
|
||||||
|
CUT_SEARCH_CM = Decimal('200')
|
||||||
|
BAND_ROWS = 512
|
||||||
|
# Above this a source is read band by band instead of decoded whole.
|
||||||
|
STREAM_ABOVE_PIXELS = 40_000_000
|
||||||
|
FOOTER_TEXT_CM = 1.1
|
||||||
|
Image.MAX_IMAGE_PIXELS = None
|
||||||
|
|
||||||
|
|
||||||
|
def px(cm):
|
||||||
|
return int(round(float(cm) * PX_PER_CM))
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Writing ----------------------------------------------------------------
|
||||||
|
|
||||||
|
def _chunk(fp, kind, data):
|
||||||
|
fp.write(struct.pack('>I', len(data)) + kind + data)
|
||||||
|
fp.write(struct.pack('>I', zlib.crc32(kind + data) & 0xffffffff))
|
||||||
|
|
||||||
|
|
||||||
|
class PngWriter:
|
||||||
|
"""An RGBA PNG written band by band: only one band is ever in memory."""
|
||||||
|
|
||||||
|
def __init__(self, fp, width, height):
|
||||||
|
self.fp, self.width, self.height = fp, width, height
|
||||||
|
self.rows = 0
|
||||||
|
self.previous = None # the last row written, as an image
|
||||||
|
self.z = zlib.compressobj(6)
|
||||||
|
self.pending = []
|
||||||
|
fp.write(b'\x89PNG\r\n\x1a\n')
|
||||||
|
_chunk(fp, b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 6, 0, 0, 0))
|
||||||
|
per_metre = round(DPI / 0.0254)
|
||||||
|
_chunk(fp, b'pHYs', struct.pack('>IIB', per_metre, per_metre, 1))
|
||||||
|
|
||||||
|
def band(self, image):
|
||||||
|
"""Append `image` (RGBA, the film's width) below what is written."""
|
||||||
|
if image.mode != 'RGBA' or image.width != self.width:
|
||||||
|
raise ValueError('a band must be RGBA and as wide as the film')
|
||||||
|
rows = image.height
|
||||||
|
if self.rows + rows > self.height:
|
||||||
|
raise ValueError('more rows than the file has')
|
||||||
|
# The previous row on top, so each row's filter refers to the real row
|
||||||
|
# above it; that first filtered row is dropped.
|
||||||
|
lead = 1 if self.previous is not None else 0
|
||||||
|
framed = Image.new('RGBA', (self.width, rows + lead))
|
||||||
|
if lead:
|
||||||
|
framed.paste(self.previous, (0, 0))
|
||||||
|
framed.paste(image, (0, lead))
|
||||||
|
encoded = io.BytesIO()
|
||||||
|
framed.save(encoded, 'PNG', compress_level=0)
|
||||||
|
filtered = zlib.decompress(_idat(encoded.getvalue()))
|
||||||
|
self._write(filtered[lead * (1 + 4 * self.width):])
|
||||||
|
self.previous = image.crop((0, rows - 1, self.width, rows))
|
||||||
|
self.rows += rows
|
||||||
|
|
||||||
|
def _write(self, data):
|
||||||
|
out = self.z.compress(data)
|
||||||
|
if out:
|
||||||
|
self.pending.append(out)
|
||||||
|
if sum(map(len, self.pending)) >= 1 << 20:
|
||||||
|
self._flush()
|
||||||
|
|
||||||
|
def _flush(self):
|
||||||
|
if self.pending:
|
||||||
|
_chunk(self.fp, b'IDAT', b''.join(self.pending))
|
||||||
|
self.pending = []
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
if self.rows != self.height:
|
||||||
|
raise ValueError(f'{self.rows} of {self.height} rows written')
|
||||||
|
self.pending.append(self.z.flush())
|
||||||
|
self._flush()
|
||||||
|
_chunk(self.fp, b'IEND', b'')
|
||||||
|
|
||||||
|
|
||||||
|
def _idat(png):
|
||||||
|
"""The concatenated IDAT data of an in-memory PNG."""
|
||||||
|
data, at = [], 8
|
||||||
|
while at < len(png):
|
||||||
|
size, kind = struct.unpack('>I4s', png[at:at + 8])
|
||||||
|
if kind == b'IDAT':
|
||||||
|
data.append(png[at + 8:at + 8 + size])
|
||||||
|
at += 12 + size
|
||||||
|
return b''.join(data)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Reading ----------------------------------------------------------------
|
||||||
|
|
||||||
|
class PngRows:
|
||||||
|
"""A PNG's rows in order, band by band, without decoding the whole image.
|
||||||
|
|
||||||
|
Only 8-bit, non-interlaced files: anything else is decoded whole.
|
||||||
|
"""
|
||||||
|
CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
|
||||||
|
|
||||||
|
def __init__(self, path):
|
||||||
|
self.fp = open(path, 'rb')
|
||||||
|
if self.fp.read(8) != b'\x89PNG\r\n\x1a\n':
|
||||||
|
raise Unsupported('o PNG está corrompido')
|
||||||
|
self.extra = []
|
||||||
|
while True:
|
||||||
|
size, kind = struct.unpack('>I4s', self.fp.read(8))
|
||||||
|
if kind == b'IDAT':
|
||||||
|
self.idat_left = size
|
||||||
|
break
|
||||||
|
data = self.fp.read(size)
|
||||||
|
self.fp.read(4)
|
||||||
|
if kind == b'IHDR':
|
||||||
|
self.width, self.height, depth, color, _, _, interlace = struct.unpack('>IIBBBBB', data)
|
||||||
|
self.ihdr = data
|
||||||
|
if depth != 8 or interlace or color not in self.CHANNELS:
|
||||||
|
raise Unsupported('PNG de 16 bits ou entrelaçado')
|
||||||
|
self.row_bytes = 1 + self.width * self.CHANNELS[color]
|
||||||
|
elif kind in (b'PLTE', b'tRNS'):
|
||||||
|
self.extra.append((kind, data))
|
||||||
|
elif kind == b'IEND':
|
||||||
|
raise Unsupported('o PNG não tem imagem')
|
||||||
|
self.inflate = zlib.decompressobj()
|
||||||
|
self.buffer = b''
|
||||||
|
self.done = 0 # rows decoded so far
|
||||||
|
self.previous = None # the last decoded row, raw
|
||||||
|
|
||||||
|
def _compressed(self, want):
|
||||||
|
"""At least `want` bytes of filtered rows, unless the file ends first."""
|
||||||
|
parts, have = [self.buffer], len(self.buffer)
|
||||||
|
while have < want:
|
||||||
|
if not self.idat_left:
|
||||||
|
self.fp.read(4)
|
||||||
|
size, kind = struct.unpack('>I4s', self.fp.read(8))
|
||||||
|
if kind != b'IDAT':
|
||||||
|
break
|
||||||
|
self.idat_left = size
|
||||||
|
block = self.fp.read(min(self.idat_left, 1 << 20))
|
||||||
|
self.idat_left -= len(block)
|
||||||
|
out = self.inflate.decompress(block)
|
||||||
|
parts.append(out)
|
||||||
|
have += len(out)
|
||||||
|
data = b''.join(parts)
|
||||||
|
self.buffer = data[want:]
|
||||||
|
return data[:want]
|
||||||
|
|
||||||
|
def band(self, rows):
|
||||||
|
"""The next `rows` rows (fewer at the end) as an image in the file's mode."""
|
||||||
|
rows = min(rows, self.height - self.done)
|
||||||
|
if rows <= 0:
|
||||||
|
return None
|
||||||
|
filtered = self._compressed(rows * self.row_bytes)
|
||||||
|
if len(filtered) != rows * self.row_bytes:
|
||||||
|
raise Unsupported('o PNG terminou antes da última linha')
|
||||||
|
lead = 1 if self.previous is not None else 0
|
||||||
|
out = io.BytesIO()
|
||||||
|
out.write(b'\x89PNG\r\n\x1a\n')
|
||||||
|
_chunk(out, b'IHDR', struct.pack('>II', self.width, rows + lead) + self.ihdr[8:])
|
||||||
|
for kind, data in self.extra:
|
||||||
|
_chunk(out, kind, data)
|
||||||
|
body = (b'\x00' + self.previous if lead else b'') + filtered
|
||||||
|
_chunk(out, b'IDAT', zlib.compress(body, 0))
|
||||||
|
_chunk(out, b'IEND', b'')
|
||||||
|
out.seek(0)
|
||||||
|
image = Image.open(out)
|
||||||
|
image.load()
|
||||||
|
if lead:
|
||||||
|
image = image.crop((0, 1, self.width, rows + 1))
|
||||||
|
self.previous = image.crop((0, rows - 1, self.width, rows)).tobytes()
|
||||||
|
self.done += rows
|
||||||
|
return image
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.fp.close()
|
||||||
|
|
||||||
|
|
||||||
|
def rgba(image):
|
||||||
|
if image.mode == 'RGBA':
|
||||||
|
return image
|
||||||
|
if image.mode in ('I;16', 'I;16B', 'I;16L', 'I'):
|
||||||
|
image = image.convert('I').point(lambda value: value * (1 / 257)).convert('L')
|
||||||
|
return image.convert('RGBA')
|
||||||
|
|
||||||
|
|
||||||
|
class Source:
|
||||||
|
"""One customer file: its size as the Site measured it, and its pixels."""
|
||||||
|
|
||||||
|
def __init__(self, path, name):
|
||||||
|
self.path, self.name = path, name
|
||||||
|
with open(path, 'rb') as handle:
|
||||||
|
head = handle.read(1024)
|
||||||
|
self.pdf = b'%PDF-' in head
|
||||||
|
if self.pdf:
|
||||||
|
import pypdfium2
|
||||||
|
try:
|
||||||
|
self.document = pypdfium2.PdfDocument(path)
|
||||||
|
except Exception as exc:
|
||||||
|
raise Unsupported(f'"{name}" não é um PDF que o gerador consiga ler') from exc
|
||||||
|
if len(self.document) != 1:
|
||||||
|
count = len(self.document)
|
||||||
|
self.document.close()
|
||||||
|
raise Unsupported(f'"{name}" tem {count} páginas; só PDFs de uma página são gerados automaticamente')
|
||||||
|
self.page = self.document[0]
|
||||||
|
self.size = self.page.get_size() # as displayed, /Rotate applied
|
||||||
|
self.streamable = True
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
image = Image.open(path)
|
||||||
|
except Exception as exc:
|
||||||
|
raise Unsupported(f'"{name}" não é uma imagem que o gerador consiga ler') from exc
|
||||||
|
if image.format not in SUPPORTED_FORMATS:
|
||||||
|
raise Unsupported(f'"{name}" está em {image.format or "formato desconhecido"}; '
|
||||||
|
'só JPEG, PNG, WebP, TIFF e PDF são gerados automaticamente')
|
||||||
|
# Pillow decodes a whole PNG to look for EXIF after the pixels; only
|
||||||
|
# an orientation ahead of them is read, as is a JPEG's.
|
||||||
|
try:
|
||||||
|
self.orientation = (image.getexif().get(0x0112, 1)
|
||||||
|
if image.format != 'PNG' or 'exif' in image.info else 1)
|
||||||
|
except Exception:
|
||||||
|
self.orientation = 1
|
||||||
|
width, height = image.size
|
||||||
|
self.size = (height, width) if self.orientation in (5, 6, 7, 8) else (width, height)
|
||||||
|
self.streamable = False
|
||||||
|
if image.format == 'PNG' and self.orientation == 1:
|
||||||
|
try:
|
||||||
|
PngRows(path).close()
|
||||||
|
self.streamable = True
|
||||||
|
except Unsupported:
|
||||||
|
pass
|
||||||
|
image.close()
|
||||||
|
|
||||||
|
def decoded(self, width, height):
|
||||||
|
"""The whole file at (width, height) px, upright, RGBA."""
|
||||||
|
if self.pdf:
|
||||||
|
if width * height > MAX_DECODED_PIXELS:
|
||||||
|
raise Unsupported(f'"{self.name}" ficaria grande demais para montar; prepare este item à mão')
|
||||||
|
scale = width / self.size[0]
|
||||||
|
image = self.page.render(scale=scale, fill_color=(0, 0, 0, 0)).to_pil()
|
||||||
|
return rgba(image).resize((width, height), Image.LANCZOS) if image.size != (width, height) else rgba(image)
|
||||||
|
image = Image.open(self.path)
|
||||||
|
if image.width * image.height > MAX_DECODED_PIXELS:
|
||||||
|
raise Unsupported(f'"{self.name}" tem {image.width} × {image.height} px, mais do que o '
|
||||||
|
'gerador processa; prepare este item à mão')
|
||||||
|
image.load()
|
||||||
|
if self.orientation != 1:
|
||||||
|
image = ImageOps.exif_transpose(image)
|
||||||
|
image = rgba(image)
|
||||||
|
return image if image.size == (width, height) else image.resize((width, height), Image.LANCZOS)
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
if self.pdf:
|
||||||
|
self.document.close()
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Pieces -----------------------------------------------------------------
|
||||||
|
|
||||||
|
class Piece:
|
||||||
|
"""One placement on the film, in pixels, able to give the rows of the film
|
||||||
|
it covers, in order."""
|
||||||
|
|
||||||
|
def __init__(self, placement, source):
|
||||||
|
self.source = source
|
||||||
|
self.x, self.y = px(placement['x_cm']), px(placement['y_cm'])
|
||||||
|
self.w = max(1, px(Decimal(str(placement['x_cm'])) + Decimal(str(placement['width_cm']))) - self.x)
|
||||||
|
self.h = max(1, px(Decimal(str(placement['y_cm'])) + Decimal(str(placement['length_cm']))) - self.y)
|
||||||
|
self.rotation = placement['rotation_degrees'] % 360
|
||||||
|
self.mirrored = placement['mirrored']
|
||||||
|
self.reader = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def streamed(self):
|
||||||
|
return (self.source.streamable and not self.rotation and not self.mirrored and
|
||||||
|
self.w * self.h > STREAM_ABOVE_PIXELS)
|
||||||
|
|
||||||
|
def rows(self, top, bottom, cache):
|
||||||
|
"""The piece's rows [top, bottom) in film coordinates, as RGBA."""
|
||||||
|
a, b = top - self.y, bottom - self.y
|
||||||
|
if not self.streamed:
|
||||||
|
return self._placed(cache).crop((0, a, self.w, b))
|
||||||
|
if self.source.pdf:
|
||||||
|
return self._pdf_rows(a, b)
|
||||||
|
return self._png_rows(a, b)
|
||||||
|
|
||||||
|
def _placed(self, cache):
|
||||||
|
"""The whole piece, turned and scaled, shared by every copy."""
|
||||||
|
key = (id(self.source), self.rotation, self.mirrored, self.w, self.h)
|
||||||
|
if key not in cache:
|
||||||
|
upright = (self.h, self.w) if self.rotation in (90, 270) else (self.w, self.h)
|
||||||
|
image = self.source.decoded(*upright)
|
||||||
|
if self.mirrored:
|
||||||
|
image = ImageOps.mirror(image)
|
||||||
|
if self.rotation:
|
||||||
|
# Clockwise, as the Site turns it.
|
||||||
|
image = image.rotate(-self.rotation, expand=True)
|
||||||
|
cache[key] = image if image.size == (self.w, self.h) else image.resize((self.w, self.h), Image.LANCZOS)
|
||||||
|
return cache[key]
|
||||||
|
|
||||||
|
def _pdf_rows(self, a, b):
|
||||||
|
page_w, page_h = self.source.size
|
||||||
|
scale = self.w / page_w
|
||||||
|
top_pt, bottom_pt = a / scale, max(0.0, page_h - b / scale)
|
||||||
|
image = self.source.page.render(scale=scale, crop=(0, bottom_pt, 0, top_pt),
|
||||||
|
fill_color=(0, 0, 0, 0)).to_pil()
|
||||||
|
image = rgba(image)
|
||||||
|
return image if image.size == (self.w, b - a) else image.resize((self.w, b - a), Image.LANCZOS)
|
||||||
|
|
||||||
|
def _png_rows(self, a, b):
|
||||||
|
"""Rows [a, b) of the piece from a PNG read in order, scaled to the piece."""
|
||||||
|
if self.reader is None:
|
||||||
|
self.reader = PngRows(self.source.path)
|
||||||
|
self.buffer, self.buffer_top = None, 0
|
||||||
|
sw, sh = self.reader.width, self.reader.height
|
||||||
|
per_row = sh / self.h
|
||||||
|
# The source rows behind [a, b), with room for the filter on each side.
|
||||||
|
margin = 0 if per_row == 1 and sw == self.w else math.ceil(3 * max(per_row, 1)) + 2
|
||||||
|
want_top, want_bottom = max(0, math.floor(a * per_row) - margin), min(sh, math.ceil(b * per_row) + margin)
|
||||||
|
while self.buffer_top + (self.buffer.height if self.buffer else 0) < want_bottom:
|
||||||
|
band = rgba(self.reader.band(BAND_ROWS))
|
||||||
|
if self.buffer is None:
|
||||||
|
self.buffer = band
|
||||||
|
else:
|
||||||
|
joined = Image.new('RGBA', (sw, self.buffer.height + band.height))
|
||||||
|
joined.paste(self.buffer, (0, 0))
|
||||||
|
joined.paste(band, (0, self.buffer.height))
|
||||||
|
self.buffer = joined
|
||||||
|
if want_top > self.buffer_top: # rows no band will need again
|
||||||
|
self.buffer = self.buffer.crop((0, want_top - self.buffer_top, sw, self.buffer.height))
|
||||||
|
self.buffer_top = want_top
|
||||||
|
if per_row == 1 and sw == self.w:
|
||||||
|
return self.buffer.crop((0, a - self.buffer_top, sw, b - self.buffer_top))
|
||||||
|
box = (0, a * per_row - self.buffer_top, sw, b * per_row - self.buffer_top)
|
||||||
|
return self.buffer.resize((self.w, b - a), Image.LANCZOS, box=box)
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
if self.reader:
|
||||||
|
self.reader.close()
|
||||||
|
self.reader = None
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Parts and footer -------------------------------------------------------
|
||||||
|
|
||||||
|
def part_cuts(production, part_cm=None):
|
||||||
|
"""Where the film is cut into parts, in cm from its top: [0, ..., height]."""
|
||||||
|
limit = Decimal(str(part_cm or PART_CM))
|
||||||
|
height = Decimal(str(production['height_cm']))
|
||||||
|
spans = [(Decimal(str(p['y_cm'])), Decimal(str(p['y_cm'])) + Decimal(str(p['length_cm'])))
|
||||||
|
for p in production['placements']]
|
||||||
|
cuts = [Decimal(0)]
|
||||||
|
while height - cuts[-1] > limit:
|
||||||
|
start = cuts[-1]
|
||||||
|
free = [end for _, end in spans
|
||||||
|
if start + limit - CUT_SEARCH_CM <= end <= start + limit
|
||||||
|
and not any(top < end < bottom for top, bottom in spans)]
|
||||||
|
cuts.append(max(free) if free else start + limit)
|
||||||
|
cuts.append(height)
|
||||||
|
return cuts
|
||||||
|
|
||||||
|
|
||||||
|
def proof_cut(height_cm, limit_cm, fraction=None):
|
||||||
|
"""A proof's window, in cm from the film's top: `limit_cm` centred on the
|
||||||
|
thinnest stroke (fraction 0 at the top, 1 at the bottom), clamped inside
|
||||||
|
the film. Without a measured fraction it starts at the top, as before."""
|
||||||
|
height = Decimal(str(height_cm))
|
||||||
|
if height <= 0:
|
||||||
|
return [Decimal(0), Decimal(0)]
|
||||||
|
span = min(height, Decimal(str(limit_cm)))
|
||||||
|
if fraction is None:
|
||||||
|
return [Decimal(0), span]
|
||||||
|
center = min(Decimal(1), max(Decimal(0), Decimal(str(fraction)))) * height
|
||||||
|
start = min(height - span, max(Decimal(0), center - span / 2))
|
||||||
|
return [start, start + span]
|
||||||
|
|
||||||
|
|
||||||
|
def _font(size):
|
||||||
|
return ImageFont.load_default(size=size)
|
||||||
|
|
||||||
|
|
||||||
|
def footer_band(text, width):
|
||||||
|
"""The footer, 1,5 cm, black on transparent: the logo, then the line."""
|
||||||
|
height = px(FOOTER_CM)
|
||||||
|
band = Image.new('RGBA', (width, height))
|
||||||
|
draw = ImageDraw.Draw(band)
|
||||||
|
x = px(0.5)
|
||||||
|
if os.path.exists(FOOTER_LOGO):
|
||||||
|
logo = rgba(Image.open(FOOTER_LOGO))
|
||||||
|
logo_h = px(FOOTER_LOGO_CM)
|
||||||
|
logo = logo.resize((max(1, round(logo.width * logo_h / logo.height)), logo_h), Image.LANCZOS)
|
||||||
|
band.alpha_composite(logo, (x, (height - logo_h) // 2))
|
||||||
|
x += logo.width + px(0.4)
|
||||||
|
text = text.partition(' · ')[2]
|
||||||
|
room = width - x - px(0.5)
|
||||||
|
size = px(FOOTER_TEXT_CM)
|
||||||
|
while size > 10 and draw.textlength(text, font=_font(size)) > room:
|
||||||
|
size -= 4
|
||||||
|
font = _font(size)
|
||||||
|
top, bottom = font.getbbox(text)[1], font.getbbox(text)[3]
|
||||||
|
draw.text((x, (height - (bottom - top)) // 2 - top), text, font=font, fill=(0, 0, 0, 255),
|
||||||
|
stroke_width=max(1, size // 40), stroke_fill=(0, 0, 0, 255))
|
||||||
|
return band
|
||||||
|
|
||||||
|
|
||||||
|
# ---- The file ---------------------------------------------------------------
|
||||||
|
|
||||||
|
def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False, limit_cm=None,
|
||||||
|
proof_fraction=None):
|
||||||
|
"""Write the PNG part(s) of one approved order item into `out_dir`.
|
||||||
|
|
||||||
|
`files` maps each source index to (local path, original name). With
|
||||||
|
`tiles`, each part's pieces for the Kanban's viewer go in
|
||||||
|
out_dir/tiles/<part name>/<level>/<index>.png (app/printtiles.py).
|
||||||
|
A proof (`limit_cm`) is a free 15 cm window around `proof_fraction`.
|
||||||
|
Returns the parts, [(path, name)], and the evidence the Kanban shows.
|
||||||
|
"""
|
||||||
|
production = item['production']
|
||||||
|
if production.get('version') not in PRODUCTION_VERSIONS:
|
||||||
|
raise Unsupported('o item usa uma montagem antiga')
|
||||||
|
sources = [Source(*files[index]) for index in range(len(production['sources']))]
|
||||||
|
try:
|
||||||
|
vector = {index for index, source in enumerate(sources) if source.pdf}
|
||||||
|
lowest = check_layout(item, [source.size for source in sources], vector, proof=bool(limit_cm))
|
||||||
|
width = px(production['film_width_cm'])
|
||||||
|
pieces = sorted((Piece(placement, sources[placement['source_index']])
|
||||||
|
for placement in production['placements']), key=lambda piece: piece.y)
|
||||||
|
# A proof sheet is a 15 cm window around the finest stroke; a normal
|
||||||
|
# file is cut into parts (app/proof.py, item 0.1).
|
||||||
|
cuts = (proof_cut(production['height_cm'], limit_cm, proof_fraction) if limit_cm
|
||||||
|
else part_cuts(production, part_cm))
|
||||||
|
count = len(cuts) - 1
|
||||||
|
parts, manifests = [], []
|
||||||
|
for number in range(count):
|
||||||
|
name = f'{prefix}.png' if count == 1 else f'{prefix}-p{number + 1}.png'
|
||||||
|
path = os.path.join(out_dir, name)
|
||||||
|
line = footer and (footer + (f' · Parte {number + 1}/{count}' if count > 1 else ''))
|
||||||
|
with open(path, 'wb') as out:
|
||||||
|
manifests.append(write_part(out, pieces, px(cuts[number]), px(cuts[number + 1]), width, line,
|
||||||
|
tiles=os.path.join(out_dir, 'tiles', name) if tiles else None))
|
||||||
|
parts.append((path, name))
|
||||||
|
finally:
|
||||||
|
for source in sources:
|
||||||
|
source.close()
|
||||||
|
return parts, {'format': 'png', 'dpi': DPI,
|
||||||
|
'film_width_cm': str(production['film_width_cm']),
|
||||||
|
'height_cm': str(production['height_cm']),
|
||||||
|
'width_px': width,
|
||||||
|
'parts': [{'name': name, 'from_cm': str(cuts[i]), 'to_cm': str(cuts[i + 1]),
|
||||||
|
**({'tiles': manifests[i]} if manifests[i] else {})}
|
||||||
|
for i, (_, name) in enumerate(parts)],
|
||||||
|
'footer': footer,
|
||||||
|
'billed_metres': str(item['billed_metres']),
|
||||||
|
'placements': len(production['placements']),
|
||||||
|
'sources': len(sources),
|
||||||
|
'vector_sources': len(vector),
|
||||||
|
'min_dpi': round(lowest) if lowest else None}
|
||||||
|
|
||||||
|
|
||||||
|
def write_part(out, pieces, top, bottom, width, footer=None, tiles=None):
|
||||||
|
"""Rows [top, bottom) of the film, then the footer, as one PNG; with
|
||||||
|
`tiles`, a folder, also its pieces for the viewer. Returns their manifest."""
|
||||||
|
foot = footer_band(footer, width) if footer else None
|
||||||
|
height = bottom - top + (foot.height if foot else 0)
|
||||||
|
writer = PngWriter(out, width, height)
|
||||||
|
pyramid = None
|
||||||
|
if tiles:
|
||||||
|
def emit(level, index, data):
|
||||||
|
folder = os.path.join(tiles, str(level))
|
||||||
|
os.makedirs(folder, exist_ok=True)
|
||||||
|
with open(os.path.join(folder, f'{index}.png'), 'wb') as strip:
|
||||||
|
strip.write(data)
|
||||||
|
pyramid = Pyramid(width, height, emit)
|
||||||
|
cache = {}
|
||||||
|
for band_top in range(top, bottom, BAND_ROWS):
|
||||||
|
band_bottom = min(bottom, band_top + BAND_ROWS)
|
||||||
|
band = Image.new('RGBA', (width, band_bottom - band_top))
|
||||||
|
for piece in pieces:
|
||||||
|
if piece.y >= band_bottom:
|
||||||
|
break
|
||||||
|
if piece.y + piece.h <= band_top:
|
||||||
|
continue
|
||||||
|
a, b = max(band_top, piece.y), min(band_bottom, piece.y + piece.h)
|
||||||
|
rows = piece.rows(a, b, cache)
|
||||||
|
left = max(0, -piece.x)
|
||||||
|
if left or piece.x + rows.width > width:
|
||||||
|
rows = rows.crop((left, 0, min(rows.width, width - piece.x), rows.height))
|
||||||
|
band.alpha_composite(rows, (max(0, piece.x), a - band_top))
|
||||||
|
writer.band(band)
|
||||||
|
if pyramid:
|
||||||
|
pyramid.band(band)
|
||||||
|
# A piece the film has passed is done with: its pixels can go.
|
||||||
|
for piece in pieces:
|
||||||
|
if piece.y + piece.h <= band_bottom:
|
||||||
|
piece.close()
|
||||||
|
live = {(id(p.source), p.rotation, p.mirrored, p.w, p.h) for p in pieces if p.y + p.h > band_bottom}
|
||||||
|
for key in [key for key in cache if key not in live]:
|
||||||
|
del cache[key]
|
||||||
|
if foot:
|
||||||
|
writer.band(foot)
|
||||||
|
if pyramid:
|
||||||
|
pyramid.band(foot)
|
||||||
|
writer.close()
|
||||||
|
return pyramid.close() if pyramid else None
|
||||||
58
app/printpng_validate.py
Normal file
58
app/printpng_validate.py
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
"""Small, bounded header check for the final file FlexiPRINT receives.
|
||||||
|
|
||||||
|
The original upload may be PNG or PDF. A *final* file is a transparent,
|
||||||
|
8-bit RGBA PNG tagged 300 DPI. Read only header chunks before IDAT, so even
|
||||||
|
a multi-gigabyte sheet is checked without decoding or downloading the film.
|
||||||
|
"""
|
||||||
|
import struct
|
||||||
|
|
||||||
|
PNG = b'\x89PNG\r\n\x1a\n'
|
||||||
|
HEADER_BYTES = 1 << 20
|
||||||
|
|
||||||
|
|
||||||
|
def final_png_issue(data):
|
||||||
|
if not data.startswith(PNG):
|
||||||
|
return 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.'
|
||||||
|
at = len(PNG)
|
||||||
|
rgba = False
|
||||||
|
dpi = None
|
||||||
|
image_data = False
|
||||||
|
while at + 12 <= len(data):
|
||||||
|
size = struct.unpack('>I', data[at:at + 4])[0]
|
||||||
|
kind = data[at + 4:at + 8]
|
||||||
|
end = at + 12 + size
|
||||||
|
if kind == b'IDAT':
|
||||||
|
image_data = True
|
||||||
|
break
|
||||||
|
if end > len(data):
|
||||||
|
return 'O cabeçalho do PNG final está incompleto ou inválido.'
|
||||||
|
body = data[at + 8:at + 8 + size]
|
||||||
|
if kind == b'IHDR':
|
||||||
|
if at != 8 or size != 13:
|
||||||
|
return 'O cabeçalho do PNG final está inválido.'
|
||||||
|
width, height, depth, color, compression, filtering, interlace = struct.unpack('>IIBBBBB', body)
|
||||||
|
rgba = bool(width and height and depth == 8 and color == 6 and
|
||||||
|
compression == 0 and filtering == 0 and interlace == 0)
|
||||||
|
elif kind == b'pHYs' and size == 9:
|
||||||
|
x, y, unit = struct.unpack('>IIB', body)
|
||||||
|
if unit == 1 and x and y:
|
||||||
|
dpi = (x * .0254, y * .0254)
|
||||||
|
at = end
|
||||||
|
if not rgba:
|
||||||
|
return 'O PNG final precisa ter transparência (canal alfa RGBA de 8 bits).'
|
||||||
|
if not dpi or any(abs(axis - 300) > 1 for axis in dpi):
|
||||||
|
return 'O PNG final precisa estar marcado como 300 DPI nos dois eixos.'
|
||||||
|
if not image_data:
|
||||||
|
return 'O PNG final está incompleto: faltam os dados da imagem.'
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def require_final_png(storage, upload):
|
||||||
|
from fastapi import HTTPException
|
||||||
|
if not upload['name'].lower().endswith('.png'):
|
||||||
|
raise HTTPException(422, 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.')
|
||||||
|
response = storage.client.get_object(Bucket=storage.bucket, Key=upload['object_key'],
|
||||||
|
Range=f'bytes=0-{HEADER_BYTES - 1}')
|
||||||
|
issue = final_png_issue(response['Body'].read())
|
||||||
|
if issue:
|
||||||
|
raise HTTPException(422, issue)
|
||||||
102
app/printtiles.py
Normal file
102
app/printtiles.py
Normal 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)]}
|
||||||
70
app/proof.py
70
app/proof.py
@@ -11,6 +11,10 @@ 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
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
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 +28,69 @@ 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 15 cm per contraction class, and follows the normal flow up
|
||||||
|
# to Revisão. The parent waits outside the queue, "Aguardando prova". On the
|
||||||
|
# child, the Vendedor (Gestão and the Administrador too) marks Prova OK, and
|
||||||
|
# the parent enters the queue; or Prova reprovada, with its reason, and the
|
||||||
|
# parent goes back to Arte recebida and the child closes. The child is no
|
||||||
|
# sale: it is not in Tiny, Números, the customer's account or their e-mails.
|
||||||
|
PROOF_SHEET_CM = Decimal('15')
|
||||||
|
# Three proofs at most per order, one per item (Dropstar, 2026-10-23).
|
||||||
|
MAX_PROOFS = 3
|
||||||
|
PROVIDER = 'prova'
|
||||||
|
|
||||||
|
|
||||||
|
def proof_identity(order_id):
|
||||||
|
return uuid5(NAMESPACE_URL, f'dtf-proof:{order_id}')
|
||||||
|
|
||||||
|
|
||||||
|
def create_child(c, parent):
|
||||||
|
"""The parent's proof card, in Arte recebida, its proof sheets queued to be
|
||||||
|
generated. Returns it, or None when the order needs no proof."""
|
||||||
|
if parent.get('parent_id') or not needs_proof(parent['snapshot']):
|
||||||
|
return None
|
||||||
|
from .printjobs import queue
|
||||||
|
# A class has one proof. When several items share it, use the one with the
|
||||||
|
# finest measured line; no metre or product value is sold on this card.
|
||||||
|
classes = {}
|
||||||
|
for index, item in enumerate(parent['snapshot']['items']):
|
||||||
|
kind = item.get('stroke_class') or 'C3'
|
||||||
|
width = item.get('stroke_px') or 10000
|
||||||
|
if kind not in classes or width < classes[kind][0]:
|
||||||
|
classes[kind] = (width, index, item)
|
||||||
|
selected = [classes[kind] for kind in ('C1', 'C2', 'C3') if kind in classes][:MAX_PROOFS]
|
||||||
|
proof_items = [{**item, 'billed_metres': '0', 'total_cents': 0, 'unit_cents': 0,
|
||||||
|
'proof_parent_item_index': index} for _, index, item in selected]
|
||||||
|
freight = {**parent['snapshot'].get('freight', {}), 'total_cents': 0}
|
||||||
|
snapshot = {**parent['snapshot'], 'items': proof_items, 'total_cents': 0,
|
||||||
|
'freight': freight, 'proof_of': parent['number']}
|
||||||
|
child = c.execute('''INSERT INTO dtf_local.orders(id,owner,snapshot,payment,origin,parent_id,machine_id,machine_chosen)
|
||||||
|
VALUES(%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
|
||||||
|
(uuid4(), proof_identity(parent['id']), Jsonb(snapshot), Jsonb({'provider': PROVIDER}),
|
||||||
|
parent['origin'], parent['id'], parent.get('machine_id'), parent.get('machine_chosen', False))).fetchone()
|
||||||
|
queue(c, child['id'], len(snapshot['items']))
|
||||||
|
return child
|
||||||
|
|
||||||
|
|
||||||
|
def open_child(c, parent_id):
|
||||||
|
"""The parent's proof card still waiting for its answer, if any."""
|
||||||
|
return c.execute('''SELECT * FROM dtf_local.orders WHERE parent_id=%s AND proof_result IS NULL
|
||||||
|
AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (parent_id,)).fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
def waiting(c, order):
|
||||||
|
"""Whether the order waits for its proof: it has a proof card without an OK."""
|
||||||
|
return not order.get('parent_id') and not order.get('proof_ok_at') and bool(open_child(c, order['id']))
|
||||||
|
|
||||||
|
|
||||||
|
def require_unlocked(c, order):
|
||||||
|
"""A parent cannot enter production or have its final changed before the proof answer."""
|
||||||
|
if waiting(c, order):
|
||||||
|
child = open_child(c, order['id'])
|
||||||
|
raise HTTPException(409, f'Aguardando prova do #{child["number"]}: responda no card da prova.')
|
||||||
|
|||||||
@@ -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,23 @@ 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),
|
||||||
|
**({'residue_accepted_at': original['residue_accepted_at']}
|
||||||
|
if original.get('residue_accepted_at') else {}),
|
||||||
|
**({'stroke_px': original['stroke_px'], 'stroke_class': original['stroke_class']}
|
||||||
|
if original.get('stroke_class') else {}),
|
||||||
|
**({'stroke_choice': original['stroke_choice']} if original.get('stroke_choice') else {}),
|
||||||
|
**({'stroke_choice_at': original['stroke_choice_at']}
|
||||||
|
if original.get('stroke_choice_at') else {}),
|
||||||
|
**({'proof_y_fraction': original['proof_y_fraction']}
|
||||||
|
if original.get('proof_y_fraction') is not None else {}),
|
||||||
|
**({'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', ''),
|
||||||
@@ -87,6 +99,8 @@ def approve(c, row, items, reviewer):
|
|||||||
'destination': draft.get('destination'),
|
'destination': draft.get('destination'),
|
||||||
# The customer's proof only above 10 m (Dropstar, 2026-10-28).
|
# The customer's proof only above 10 m (Dropstar, 2026-10-28).
|
||||||
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
|
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
|
||||||
|
# Browser timings are kept for Números, never for the price (0.12).
|
||||||
|
**({'timings': draft['timings']} if draft.get('timings') else {}),
|
||||||
'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents']}
|
'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents']}
|
||||||
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
|
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
|
||||||
(Jsonb(approved), reviewer, row['id']))
|
(Jsonb(approved), reviewer, row['id']))
|
||||||
|
|||||||
@@ -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),
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|||||||
@@ -136,6 +136,7 @@ CREATE TABLE IF NOT EXISTS dtf_local.print_files (
|
|||||||
created_at timestamptz NOT NULL DEFAULT now(), finished_at timestamptz,
|
created_at timestamptz NOT NULL DEFAULT now(), finished_at timestamptz,
|
||||||
UNIQUE(order_id,item_index)
|
UNIQUE(order_id,item_index)
|
||||||
);
|
);
|
||||||
|
ALTER TABLE dtf_local.print_files ADD COLUMN IF NOT EXISTS claim_token uuid;
|
||||||
|
|
||||||
-- Each run of the off-server database backup (ops/db_backup.py), which the
|
-- Each run of the off-server database backup (ops/db_backup.py), which the
|
||||||
-- Kanban shows so a backup that stopped working does not go unnoticed.
|
-- Kanban shows so a backup that stopped working does not go unnoticed.
|
||||||
@@ -203,8 +204,40 @@ CREATE INDEX IF NOT EXISTS payment_events_unprocessed ON dtf_local.payment_event
|
|||||||
CREATE INDEX IF NOT EXISTS print_files_open ON dtf_local.print_files(created_at)
|
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;
|
||||||
|
CREATE INDEX IF NOT EXISTS movements_finished_latest ON dtf_local.movements(order_id, created_at DESC)
|
||||||
|
WHERE to_state='fin' AND NOT back;
|
||||||
|
|
||||||
-- The Kanban lists payment events a person must act on (money without an
|
-- The Kanban lists payment events a person must act on (money without an
|
||||||
-- order, or a reversed payment on an existing order) until resolved.
|
-- order, or a reversed payment on an existing order) until resolved.
|
||||||
@@ -254,11 +287,9 @@ ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFA
|
|||||||
ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
|
ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
|
||||||
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
|
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
|
||||||
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro'));
|
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro'));
|
||||||
-- The print machines, and which products each prints. An order keeps the
|
-- Print machines and which products each prints. An order gets its machine
|
||||||
-- machine someone chose (machine_chosen) or the one given automatically: the
|
-- when someone pulls it into Imprimindo; no machine is assigned at payment.
|
||||||
-- active machine of its product with the fewest metres open (app/machines.py).
|
-- limit_metres remains the load shown for a machine.
|
||||||
-- limit_metres: the metres open a machine takes before the next order goes to
|
|
||||||
-- another one; NULL is no limit.
|
|
||||||
CREATE TABLE IF NOT EXISTS dtf_local.machines (
|
CREATE TABLE IF NOT EXISTS dtf_local.machines (
|
||||||
id uuid PRIMARY KEY, name text UNIQUE NOT NULL, products text[] NOT NULL DEFAULT '{}',
|
id uuid PRIMARY KEY, name text UNIQUE NOT NULL, products text[] NOT NULL DEFAULT '{}',
|
||||||
active boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now()
|
active boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now()
|
||||||
@@ -273,6 +304,15 @@ DO $$ BEGIN
|
|||||||
INSERT INTO dtf_local.migrations VALUES('machine-chosen-v1');
|
INSERT INTO dtf_local.migrations VALUES('machine-chosen-v1');
|
||||||
END IF;
|
END IF;
|
||||||
END $$;
|
END $$;
|
||||||
|
-- Remove the old automatic suggestions before printing. Keep real choices
|
||||||
|
-- and machines already printing, whose hot-folder files may be in flight.
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='machine-pull-only-v1') THEN
|
||||||
|
UPDATE dtf_local.orders SET machine_id=NULL, machine_chosen=false
|
||||||
|
WHERE NOT machine_chosen AND state IN ('rec','tra','cor');
|
||||||
|
INSERT INTO dtf_local.migrations VALUES('machine-pull-only-v1');
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
-- The machines an operator works on; none means every machine.
|
-- The machines an operator works on; none means every machine.
|
||||||
CREATE TABLE IF NOT EXISTS dtf_local.operator_machines (
|
CREATE TABLE IF NOT EXISTS dtf_local.operator_machines (
|
||||||
operator_id uuid NOT NULL REFERENCES dtf_local.operators(id) ON DELETE CASCADE,
|
operator_id uuid NOT NULL REFERENCES dtf_local.operators(id) ON DELETE CASCADE,
|
||||||
@@ -423,6 +463,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;
|
||||||
|
|||||||
@@ -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()')
|
||||||
|
|||||||
90
docs/ROADMAP-FASE-2-2026-11-06.md
Normal file
90
docs/ROADMAP-FASE-2-2026-11-06.md
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
# Roadmap da 3ª rodada e Fase 2 — Kanban turbinado
|
||||||
|
|
||||||
|
Base: PDF de Marcus Fernandes, 05/11/2026, versão 2; leitura do repositório em 06/11/2026. Este plano ordena **entregas por esforço crescente**, preservando duas travas do documento: a correção **0.1 começa imediatamente e bloqueia a divulgação do site**, e **nenhuma frente da Fase 2 entra em produção antes da bateria de testes da seção 0**. Horas são faixas preliminares de engenharia, incluindo implementação e validação local; não são prazo corrido nem promessa de implantação. Uma pessoa pode tocar itens rápidos enquanto a correção 0.1 avança.
|
||||||
|
|
||||||
|
**Execução em 06/11:** a Etapa 0 está implementada no código e validada localmente. A prova 0.1 passou a recortar os 15 cm no trecho de traço mais fino de cada classe, gera o PNG final do filho, limpa o contato ao responder a prova e mantém pai e filho na mesma máquina. A 0.11 foi ensaiada no reset local com o `ops.launch_reset` (sem reiniciar a numeração) e a 0.12 passou a registrar tempos do site/Prumo em Números. A bateria local passou: unitários (o de preços no host, porque o container da API não tem Node), smoke, workflow, pagamento, impressão/prova, usuários, Kanban, cotações, segurança, retenção, backup e os dois testes de navegador. Nada foi implantado em produção; a 0.11 em dados reais continua dependendo de autorização, backup e janela.
|
||||||
|
|
||||||
|
## O que o código já comprova
|
||||||
|
|
||||||
|
- O pagamento cria o pedido e dispara a geração do arquivo e o card de prova; há caminhos separados para pedido de teste e pagamento registrado pelo balcão ([`app/payments.py`](../app/payments.py), [`app/api/operator.py`](../app/api/operator.py)). A correção 0.10 exige teste de ponta a ponta em ambiente controlado para confirmar que **pedido real do site** não usa esses caminhos.
|
||||||
|
- O pagamento cria o pedido e o card de prova. O card filho gera seu próprio PNG final, o pai fica bloqueado até a resposta e os dois compartilham a máquina; a prova usa uma janela de 15 cm em volta do traço mais fino de cada classe ([`app/proof.py`](../app/proof.py), [`app/printjobs.py`](../app/printjobs.py), [`app/printpng.py`](../app/printpng.py)).
|
||||||
|
- A máquina não é mais atribuída ao pagamento: quem puxa o card escolhe a máquina da sessão, e o histórico guarda operador e hora ([`app/machines.py`](../app/machines.py), [`app/api/operator.py`](../app/api/operator.py)).
|
||||||
|
- A folha pronta aceita resíduo e traço fino com o mesmo aceite das avulsas; a régua é 96/200 DPI e 287–293 DPI passam como 300 ([`web/site-quality.js`](../web/site-quality.js), [`web/site-config.js`](../web/site-config.js), [`app/grade_check.py`](../app/grade_check.py)).
|
||||||
|
- A geração tem timeout de 15 minutos, aviso de falha com hora no card e “Gerar de novo” ([`app/printjobs.py`](../app/printjobs.py), [`app/api/operator.py`](../app/api/operator.py)).
|
||||||
|
- O download do original agora usa `DTF-<n>-original-<i>`, e o arquivo final só entra como PNG RGBA 8 bits a 300 DPI ([`app/api/operator.py`](../app/api/operator.py), [`app/printpng_validate.py`](../app/printpng_validate.py)).
|
||||||
|
- A 0.12 passou a registrar em Números a página, o upload (MB/s), a conferência do Prumo, a montagem, a geração por 10 m e o tempo do evento de pagamento até o card, com média e p95 ([`app/api/operator.py`](../app/api/operator.py), [`web/checkout.js`](../web/checkout.js), [`web/kanban.js`](../web/kanban.js)).
|
||||||
|
|
||||||
|
Esses achados são **verificação estática do repositório**, não prova de que a versão implantada tem exatamente o mesmo comportamento. O PDF traz evidências visuais dos pedidos #14 e #15; a confirmação de correção precisa repetir cenários equivalentes em homologação.
|
||||||
|
|
||||||
|
## Etapa 0 — correções antes da Fase 2
|
||||||
|
|
||||||
|
**Começar 0.1 no primeiro dia**, em paralelo aos primeiros itens abaixo. Os itens estão na ordem aproximada de menor esforço para entregar. A sequência de publicação deve preservar as dependências indicadas.
|
||||||
|
|
||||||
|
| Ordem de entrega | PDF | Trabalho e critério de aceite | Estimativa | Dependência |
|
||||||
|
|---|---|---|---:|---|
|
||||||
|
| 1 | 0.7 | Finalizados do mais novo ao mais antigo; colunas de trabalho continuam FIFO. | 2–4 h | Nenhuma. |
|
||||||
|
| 2 | 0.6 | “Abrir arquivo” na frente do card em todas as colunas, sem expandir. | 3–6 h | Nenhuma. |
|
||||||
|
| 3 | 0.10 | Provar que pedido real do site só nasce com pagamento confirmado; manter exceções explícitas de teste e balcão. Corrigir apenas se o teste achar furo. | 3–8 h | Acesso a homologação e um fluxo de pagamento de teste. |
|
||||||
|
| 4 | 0.8 | Nova régua: `<96` recusa; `96–199` exige ciência; `>=200` passa sem ressalva. Aplicar no navegador e na aprovação do servidor; conferir 287–293 DPI. | 6–12 h | Arquivos de amostra. |
|
||||||
|
| 5 | 0.9 | Arquivo final exclusivamente PNG 300 DPI transparente. Validar no servidor, no upload e na aprovação; mensagem clara para PDF/TIFF ou conversão definida. | 8–16 h | Decidir **rejeitar** PDF/TIFF ou convertê-los; sugerido rejeitar e orientar o designer, por ser a via menor e mais segura. |
|
||||||
|
| 6 | 0.5 + limpeza da máquina | Eliminar máquina automática na criação; atribuir a máquina da sessão que puxa; gravar operador/hora; contar o limite e mandar à pasta certa. Pai e filho não podem divergir. | 10–20 h | Regra de prova 0.1 para a vinculação pai/filho. |
|
||||||
|
| 7 | 0.4 | Timeout visível, horário da falha, recuperação de job preso e “Gerar de novo” funcional para falha/timeout. | 10–18 h | Definir timeout inicial por tamanho; medir com 0.12. |
|
||||||
|
| 8 | 0.3 | PNG alto: medir dimensões no servidor ou rejeitar com limite explícito **antes de cobrar**; `0 DPI` nunca passa como medida. Testar 57 × 1600 cm. | 12–24 h | Definir limite aceito para arquivo alto caso a análise no servidor não seja viável. |
|
||||||
|
| 9 | 0.2 | Aceite explícito e persistido de resíduo e traço fino na folha pronta **e** nas avulsas; sem aceite, trava; fundo chapado e `<96 DPI` continuam sem exceção. | 14–28 h | Texto final de aceite já está no PDF. |
|
||||||
|
| 10 | 0.1 **urgente** | Prova criada no pagamento: até 15 cm por classe do trecho de menor traço, PNG final aprovado no filho, custo/metragem zero, topo da fila, uma máquina para pai/filho, travas do pai até resposta do vendedor, motivo na reprovação. | 36–72 h | 0.5 integra a parte de máquina; usar amostras #14/#15. **Bloqueia divulgação.** |
|
||||||
|
| 11 | “O que tirar” | Remover “Contato feito”, agrupar Originais, mover Manifesto para Arquivos e ocultar nota do cliente. A remoção da máquina automática está em 0.5. | 6–12 h | “Contato feito” depende de 0.1; demais independentes. |
|
||||||
|
| 12 | 0.12 | Medir média e p95 das seis etapas no Números; ETA de upload e andamento legível das etapas no site; converter violações dos limites do PDF em correções com número. | 24–40 h | Instrumentar antes da bateria final para medir casos reais. |
|
||||||
|
| 13 | 0.11 | **Só depois de 0.1–0.10:** backup verificável, limpeza de pedidos/cards/histórico/pastas e recibos, preservar cadastros/integrações e sequência de números Tiny; repetir toda a bateria. | 8–16 h de operação | Autorização expressa do dono dos dados, janela, backup/restauração, lista de números já usados no Tiny; cliente cancela testes no Tiny. |
|
||||||
|
|
||||||
|
**Gate de saída da Etapa 0:** repetir no site e no Kanban os cenários do PDF, inclusive #14/#15 equivalentes, PNG alto, 96/199/200/293 DPI, resíduo/traço fino nos dois caminhos, timeout e retomada, máquina puxada, saída em PNG, pedido não pago, e medição de tempos. Divulgar o site somente após a prova 0.1 e os demais bloqueios comerciais estarem validados. O “zerar” é destrutivo: preparar e ensaiar restauração antes de executar em qualquer ambiente com dados reais.
|
||||||
|
|
||||||
|
## Fase 2 — entregas menores primeiro, respeitando dependências
|
||||||
|
|
||||||
|
O PDF numera as frentes pela prioridade do cliente; esta tabela muda **apenas a ordem de implementação sugerida por tempo**. A documentação da frente 12 acompanha cada entrega e fecha a rodada.
|
||||||
|
|
||||||
|
| Sequência | Frente | Entrega | Estimativa | Entrada necessária / dependência |
|
||||||
|
|---|---|---|---:|---|
|
||||||
|
| 1 | 6 | Nome Prumo e relatório ordenado das ações no card e no resumo antes do pagamento. | 12–24 h | Itens prévios 9/13/16 citados no PDF; persistir eventos reais, não inferir do resultado final. |
|
||||||
|
| 2 | 4 | Área de vídeos, player flutuante e vínculo por produto. | 12–24 h | Estrutura independe da gravação; **Dropstar fornece seis vídeos** para publicar. A edição pelo Kanban entra na frente 8. |
|
||||||
|
| 3 | 5 | Tratamento pelo designer como opcional, item pago, etiqueta e prazo adicional de 24 h. | 12–24 h | **Dropstar define R$ X** e confirma capacidade/SLA; reutilizar fluxo existente de envio do final. |
|
||||||
|
| 4 | 9 | Evoluir cotações/tentativas para aba “Aguardando pagamento”, idade, contato, expiração e abandono. | 16–32 h | Decisões de expiração, aviso, cancelamento e arquivo; vide quadro abaixo. Não tratar cotação pendente de revisão como pedido criado. |
|
||||||
|
| 5 | 11 | Limites editáveis por etapa, cores, lista Atrasados e comparação no Números. | 18–32 h | Limites iniciais no PDF: 2 h, 6 h, 4 h, 2 h, 3 dias; confirmar dono de cada etapa. |
|
||||||
|
| 6 | 3 | Premium: produto, preço, classe/pasta PREMIUM, SKU Tiny e comparação no site. | 28–52 h | **Bloqueado para publicação** até preset Spot OK Premium no Flexi, hot folder, contração e três folhas de teste aprovadas pela Dropstar; SKU Tiny. |
|
||||||
|
| 7 | 2 | Foto/vídeo da revisão, câmera/upload, pasta `Revisões/`, bloqueio de Finalizado acima de 1 m e foto no aviso. | 36–64 h | Dropstar instala pedestal/celular e aprova exemplo de foto; integrar ao fluxo de avisos do n8n/Tiny já usado pelo cliente. |
|
||||||
|
| 8 | 1 | Ficha de máquinas, insumos/peças/eventos, contadores, alertas e custo/ROI no Números. | 64–112 h | Hot folders existentes; **Dropstar fornece** preço/data de instalação, custos/lotes, mínimos e registro operacional. Confirmar como detectar “entre um arquivo e outro” sem sinal de impressão do Flexi. |
|
||||||
|
| 9 | 7a | Montador no Kanban com `Estampas/`, tabela de tamanhos, lista, montagem e card faturado. | 72–128 h | Prumo 6; **Dropstar fornece** PNGs/códigos, tabela de tamanhos e regra de faturamento/Tiny; criar perfil Expedição. |
|
||||||
|
| 10 | 7b | QR no impresso e preenchimento automático do lote. | 72–128 h | 7a em uso; **Dropstar fornece** origem e formato dos pedidos do lote e validação física do QR. |
|
||||||
|
| 11 | 8 | Aba Site administrável: produtos, preços/faixas, cupons, vídeos e nota da arte, com vigência e auditoria. | 96–160 h | Modelo comercial e permissões aprovados pela Gestão; frente 4 para vídeos; migrar preço autoritativo do código para banco sem alterar pedidos pagos. |
|
||||||
|
| 12 | 10 | Vetorizar/ampliar separado, lote, prévia, créditos/packs, cupom e chamada ao motor. | 120–220 h | Frente 8; **Wagner mede custo/qualidade por imagem e escolhe motor**, Dropstar aprova pack e política grátis. Fazer piloto antes de fixar preço. |
|
||||||
|
| Transversal | 12 | Documentação macro, por perfil e implantação; atualizar ao concluir cada rodada. | 16–32 h | Acesso aos fluxos reais de Flexi, Tiny, pagamento e n8n; revisão operacional da Dropstar. |
|
||||||
|
|
||||||
|
## Dependências que precisam vir deles
|
||||||
|
|
||||||
|
**Dropstar/Marcus (decisões e material):**
|
||||||
|
|
||||||
|
1. Autorizar e agendar o reset 0.11 **somente quando a correção estiver validada**; confirmar backup, dados a preservar, sequência dos números e cancelamento manual dos testes no Tiny.
|
||||||
|
2. Fornecer massa de homologação equivalente aos pedidos #14/#15 e aos arquivos de DPI, resíduo, traço e PNG alto; confirmar os tempos aceitáveis já propostos no PDF após a medição 0.12.
|
||||||
|
3. Informar preço do tratamento; preços de compra e datas das máquinas; lançamentos históricos, custos, mínimos e responsáveis por alimentar insumos/eventos.
|
||||||
|
4. Gravar/entregar seis vídeos; fornecer pedestal/celular para revisão e aprovar se foto pode seguir pelo fluxo de aviso existente.
|
||||||
|
5. Configurar e testar o Premium no Flexi (8 passadas, branco máximo, contração, hot folder), imprimir três folhas, dar o “ok, testado” e cadastrar/confirmar SKU no Tiny.
|
||||||
|
6. Entregar biblioteca `Estampas/` (PNG transparente 300 DPI por código), tabela de larguras, exceções por tamanho, regra de faturamento e origem dos lotes/QR.
|
||||||
|
7. Definir preços iniciais, faixas, cupons, responsáveis e vigência da aba Site; validar se a nota da arte deve sair da tela até ter ação definida.
|
||||||
|
8. Com Wagner, comparar motor próprio e API para vetorizar: custo real, fotos/degradês, volume esperado e política dos packs/grátis antes de ativar cobrança.
|
||||||
|
|
||||||
|
**Respostas operacionais necessárias, mas parcialmente verificadas no código:**
|
||||||
|
|
||||||
|
| Pergunta do PDF | Achado no repositório | Confirmação externa |
|
||||||
|
|---|---|---|
|
||||||
|
| Onde fica pedido criado e não pago? | Cotações sem pedido aparecem na aba Cotações; tentativas têm registros separados. O card de produção surge ao confirmar pagamento, teste ou pagamento de balcão. | Definir se a futura aba une cotação aprovada e tentativa pendente; manter cotações aguardando revisão separadas. |
|
||||||
|
| Quanto duram Pix/cartão e o arquivo? | Pix: 30 min configurados. Cotação aprovada: 24 h; arquivos têm retenção própria. Não há uma regra única de 24 h de pedido não pago. | Confirmar política de cartão pendente/3DS, contato, expiração de 24 h, mensagem e exclusão do arquivo em conformidade com pagamento tardio. |
|
||||||
|
| “Original 1” baixa com qual nome? | Hoje o download individual usa o nome do upload. | O PDF já decide: renomear para nome do pedido; não precisa de nova decisão. |
|
||||||
|
| Menor traço é medido quando? | Nas avulsas, a medida é recalculada para a largura escolhida em 300 DPI. | Validar a folha pronta com arquivo de teste; a regra final deve ser a dimensão impressa, não o original. |
|
||||||
|
| Tiny avisa a cada etapa? | O código envia eventos de pagamento, entrada na fila e Finalizado; atualização de status Tiny depende de configuração. | **Dropstar verifica n8n/Tiny real:** quais estados disparam WhatsApp e texto aprovado. |
|
||||||
|
| “Pedir novamente” reutiliza final? | Não foi localizada implementação dessa ação no site/portal do repositório. | Se existe fora deste código, demonstrar; se entrar no escopo, decidir reaproveitamento de PNG válido, retenção e nova conferência. |
|
||||||
|
|
||||||
|
## Decisões de interpretação do PDF
|
||||||
|
|
||||||
|
- Em 0.5, o texto diz que a máquina automática é sugestão; em “O que tirar”, Marcus manda retirar a atribuição automática e deixar toda a fila sem máquina até alguém puxar. **Adotar a segunda regra**, que é explícita e resolve a separação pai/filho. Se uma sugestão visual ainda for desejada, ela não pode gravar `machine_id` nem dividir a prova.
|
||||||
|
- O quadro “Ordem e dependências” chama a frente 9 de “Aba Cotações”; o texto da frente 9 pede **aba Aguardando pagamento**. Tratar como evolução da aba existente e mostrar apenas oportunidades realmente pagáveis, sem misturar revisão de orçamento.
|
||||||
|
- Na frente 5, “item 8 no ar” se refere ao envio de arquivo final da rodada anterior, não necessariamente à frente 8 da Fase 2. O fluxo já existe no código; o preço do serviço é o bloqueio principal.
|
||||||
|
- A proposta de 24 h para pedido não pago não substitui os 30 min do Pix. O sistema precisa distinguir vencimento da tentativa de pagamento, prazo de recuperação comercial e retenção do arquivo, para não apagar uma compra paga tardiamente.
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -1,28 +1,38 @@
|
|||||||
"""Clear the test orders before the Site opens to customers, once, by hand.
|
"""Clear the test board before the Site opens to customers, once, by hand.
|
||||||
|
|
||||||
Run from the worker's console (Portainer > Containers > worker > Console):
|
Run from the worker's console (Portainer > Containers > worker > Console):
|
||||||
|
|
||||||
python -m ops.launch_reset shows what would be removed
|
python -m ops.launch_reset shows what would be removed
|
||||||
python -m ops.launch_reset --confirmar APAGAR removes it
|
python -m ops.launch_reset --confirmar APAGAR removes it
|
||||||
python -m ops.launch_reset --confirmar APAGAR --contas also customer accounts
|
python -m ops.launch_reset --confirmar APAGAR --contas also customer accounts
|
||||||
|
python -m ops.launch_reset --root /srv/Kanban --confirmar APAGAR
|
||||||
|
also empties the flow folders
|
||||||
|
|
||||||
Removes every order with its moves, files and notices, every quote, payment
|
Removes every order with its moves, files, notices and history, every quote,
|
||||||
attempt and payment notification, and the artwork pictures. The artwork
|
payment attempt and payment notification, and the artwork pictures. The
|
||||||
files are marked expired, so the worker deletes them from storage within a
|
artwork files are marked expired, so the worker deletes them from storage
|
||||||
minute. Operators, the Tiny connection and the backups are kept.
|
within a minute. Operators, machines, prices, the Tiny connection and the
|
||||||
|
backups are kept.
|
||||||
|
|
||||||
It refuses if any payment was made with real money (Mercado Pago's
|
It refuses if any payment was made with real money (Mercado Pago's
|
||||||
live_mode): those are customers' orders, not tests.
|
live_mode): those are customers' orders, not tests.
|
||||||
|
|
||||||
Order numbers start again at #1. A database set up before the worker could
|
The order numbering is **not** reset (Dropstar, 2026-11-05): DTF-1…DTF-15
|
||||||
do that prints the one command to run in the database container's console.
|
already exist as Tiny order numbers. DELETE keeps the identity sequence, so
|
||||||
|
the next card continues from where it stopped.
|
||||||
"""
|
"""
|
||||||
import argparse
|
import argparse
|
||||||
|
import shutil
|
||||||
import sys
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from app.core import db
|
from app.core import db
|
||||||
|
|
||||||
TABLES = [ # in an order the foreign keys allow
|
TABLES = [ # in an order the foreign keys allow
|
||||||
|
('hot_parts', 'peças nas pastas das máquinas'),
|
||||||
|
('print_parts', 'partes dos arquivos de impressão'),
|
||||||
|
('reworks', 'retrabalhos'),
|
||||||
|
('contact_waits', 'esperas de contato'),
|
||||||
('movements', 'movimentos de etapa'),
|
('movements', 'movimentos de etapa'),
|
||||||
('order_files', 'arquivos finais e correções'),
|
('order_files', 'arquivos finais e correções'),
|
||||||
('print_files', 'arquivos de impressão gerados'),
|
('print_files', 'arquivos de impressão gerados'),
|
||||||
@@ -34,20 +44,38 @@ TABLES = [ # in an order the foreign keys allow
|
|||||||
('upload_thumbnails', 'miniaturas das artes'),
|
('upload_thumbnails', 'miniaturas das artes'),
|
||||||
]
|
]
|
||||||
ACCOUNTS = [('sessions', 'sessões de clientes'), ('accounts', 'contas de clientes')]
|
ACCOUNTS = [('sessions', 'sessões de clientes'), ('accounts', 'contas de clientes')]
|
||||||
|
FLOW_FOLDERS = ('1. Arte recebida', '2. Arte conferida', '3. Imprimindo',
|
||||||
|
'4. Revisão', '5. Finalizado', 'Recibos', 'Revisões')
|
||||||
CONFIRM = 'APAGAR'
|
CONFIRM = 'APAGAR'
|
||||||
RESTART = 'ALTER TABLE dtf_local.orders ALTER COLUMN number RESTART WITH 1;'
|
|
||||||
# What the worker's role may do itself (app/bootstrap.py grants it).
|
|
||||||
RENUMBER = "SELECT setval(pg_get_serial_sequence('dtf_local.orders','number'), 1, false)"
|
|
||||||
|
|
||||||
|
|
||||||
def counts(c, tables):
|
def counts(c, tables):
|
||||||
return {table: c.execute(f'SELECT count(*) AS n FROM dtf_local.{table}').fetchone()['n'] for table, _ in tables}
|
return {table: c.execute(f'SELECT count(*) AS n FROM dtf_local.{table}').fetchone()['n'] for table, _ in tables}
|
||||||
|
|
||||||
|
|
||||||
|
def clean_folders(root, dry_run=True):
|
||||||
|
"""Empty the flow folders under `root`, recreating them; keep Estampas/."""
|
||||||
|
root = Path(root)
|
||||||
|
if not any((root / name).exists() for name in FLOW_FOLDERS):
|
||||||
|
raise SystemExit(f'{root} does not look like the Kanban root: no flow folders found.')
|
||||||
|
if dry_run:
|
||||||
|
return [str(root / name) for name in FLOW_FOLDERS if (root / name).exists()]
|
||||||
|
cleaned = []
|
||||||
|
for name in FLOW_FOLDERS:
|
||||||
|
path = root / name
|
||||||
|
if path.is_dir():
|
||||||
|
shutil.rmtree(path)
|
||||||
|
path.mkdir(parents=True, exist_ok=True)
|
||||||
|
cleaned.append(str(path))
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
def main(argv=None, out=print, connect=db.connect):
|
def main(argv=None, out=print, connect=db.connect):
|
||||||
parser = argparse.ArgumentParser(prog='python -m ops.launch_reset')
|
parser = argparse.ArgumentParser(prog='python -m ops.launch_reset')
|
||||||
parser.add_argument('--confirmar', default='', help=f'escreva {CONFIRM} para apagar')
|
parser.add_argument('--confirmar', default='', help=f'escreva {CONFIRM} para apagar')
|
||||||
parser.add_argument('--contas', action='store_true', help='apagar também as contas de clientes')
|
parser.add_argument('--contas', action='store_true', help='apagar também as contas de clientes')
|
||||||
|
parser.add_argument('--root', type=Path, help='raiz Kanban, a pasta com "1. Arte recebida"')
|
||||||
|
parser.add_argument('--keep-files', action='store_true', help='não mexer nas pastas do Kanban')
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
tables = TABLES + (ACCOUNTS if args.contas else [])
|
tables = TABLES + (ACCOUNTS if args.contas else [])
|
||||||
with connect() as c:
|
with connect() as c:
|
||||||
@@ -61,22 +89,20 @@ def main(argv=None, out=print, connect=db.connect):
|
|||||||
for table, label in tables:
|
for table, label in tables:
|
||||||
out(f'{before[table]:>7} {label}')
|
out(f'{before[table]:>7} {label}')
|
||||||
out(f'{files:>7} arquivos de arte (o worker apaga do armazenamento)')
|
out(f'{files:>7} arquivos de arte (o worker apaga do armazenamento)')
|
||||||
|
if args.root and not args.keep_files:
|
||||||
|
out('Pastas que serão esvaziadas:')
|
||||||
|
for folder in clean_folders(args.root, dry_run=True):
|
||||||
|
out(f' {folder}')
|
||||||
if args.confirmar != CONFIRM:
|
if args.confirmar != CONFIRM:
|
||||||
out(f'Nada foi apagado. Repita com --confirmar {CONFIRM} para apagar.')
|
out(f'Nada foi apagado. Repita com --confirmar {CONFIRM} para apagar.')
|
||||||
return 0
|
return 0
|
||||||
for table, _ in tables:
|
for table, _ in tables:
|
||||||
c.execute(f'DELETE FROM dtf_local.{table}')
|
c.execute(f'DELETE FROM dtf_local.{table}')
|
||||||
c.execute('UPDATE dtf_local.uploads SET expires_at=now() WHERE purged_at IS NULL')
|
c.execute('UPDATE dtf_local.uploads SET expires_at=now() WHERE purged_at IS NULL')
|
||||||
out('Apagado.')
|
if args.root and not args.keep_files:
|
||||||
try:
|
for folder in clean_folders(args.root, dry_run=False):
|
||||||
with connect() as c:
|
out(f'esvaziada {folder}')
|
||||||
c.execute(RENUMBER)
|
out('Apagado. A numeração dos pedidos continua de onde parou.')
|
||||||
out('A numeração dos pedidos recomeça em #1.')
|
|
||||||
except Exception as exc: # the application's role cannot alter the table
|
|
||||||
if 'permission' not in str(exc).lower() and 'owner' not in str(exc).lower():
|
|
||||||
raise
|
|
||||||
out('Para a numeração recomeçar em #1, rode no console do container do banco (db):')
|
|
||||||
out(f' psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "{RESTART}"')
|
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -170,14 +180,13 @@ try{
|
|||||||
await evaluate(`(()=>{const f=new File(['x'],'oversize.cdr');Object.defineProperty(f,'size',{value:4294967296+1});return sel([f]);})()`);
|
await evaluate(`(()=>{const f=new File(['x'],'oversize.cdr');Object.defineProperty(f,'size',{value:4294967296+1});return sel([f]);})()`);
|
||||||
assert.equal(await evaluate(`folhas.length===0 && $('recusa').textContent.includes('4 GB')`),true,
|
assert.equal(await evaluate(`folhas.length===0 && $('recusa').textContent.includes('4 GB')`),true,
|
||||||
'files beyond the 4 GB upload limit are rejected before browser analysis');
|
'files beyond the 4 GB upload limit are rejected before browser analysis');
|
||||||
// A large sheet (here 900 MB) is the normal order: graded from the pixel size in its
|
// A PNG above the browser's ~32k-pixel height limit cannot be checked here:
|
||||||
// header, never decoded. 6732 x 35433 px across 57 cm is 3 m at 300 DPI.
|
// it is refused with a clear message instead of being accepted as 0 DPI.
|
||||||
await evaluate(`(()=>{const h=new Uint8Array(33);h.set([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0,0,0,13,0x49,0x48,0x44,0x52]);
|
await evaluate(`(()=>{const h=new Uint8Array(33);h.set([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0,0,0,13,0x49,0x48,0x44,0x52]);
|
||||||
const v=new DataView(h.buffer);v.setUint32(16,6732);v.setUint32(20,35433);h.set([8,6,0,0,0],24);
|
const v=new DataView(h.buffer);v.setUint32(16,6732);v.setUint32(20,35433);h.set([8,6,0,0,0],24);
|
||||||
const f=new File([h],'folha-grande.png');Object.defineProperty(f,'size',{value:900*1048576});return sel([f]);})()`);
|
const f=new File([h],'folha-grande.png');Object.defineProperty(f,'size',{value:900*1048576});return sel([f]);})()`);
|
||||||
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].an`),'large sheet graded from its header');
|
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].measurementError`),'tall sheet refused');
|
||||||
assert.deepEqual(await evaluate(`({grande:folhas[0].an.grande,dpi:folhas[0].an.dpi,alt:folhas[0].med.alt,preview:!!folhas[0].previewSrc})`),
|
assert.equal(await evaluate(`folhas[0].measurementError.includes('PNG alto')`),true);
|
||||||
{grande:true,dpi:300,alt:300,preview:false});
|
|
||||||
await evaluate(`folhas=[];pintaFolha()`);
|
await evaluate(`folhas=[];pintaFolha()`);
|
||||||
await evaluate(`pickTipo('avulsa')`);
|
await evaluate(`pickTipo('avulsa')`);
|
||||||
assert.equal(await evaluate('modo'),'avulsa');
|
assert.equal(await evaluate('modo'),'avulsa');
|
||||||
@@ -295,13 +304,13 @@ try{
|
|||||||
await waitFor(()=>evaluate(`$('envios').textContent.includes('Não foi possível enviar folha-montada.png') &&
|
await waitFor(()=>evaluate(`$('envios').textContent.includes('Não foi possível enviar folha-montada.png') &&
|
||||||
!!$('envios').querySelector('[data-envio]')`),'a failed upload says so under the uploader');
|
!!$('envios').querySelector('[data-envio]')`),'a failed upload says so under the uploader');
|
||||||
assert.deepEqual(await evaluate(`({mode:modo,art:artes.length,title:$('montcabTit').textContent,rate:precoMetro()})`),{mode:'file',art:0,title:'Sua folha',rate:19.9});
|
assert.deepEqual(await evaluate(`({mode:modo,art:artes.length,title:$('montcabTit').textContent,rate:precoMetro()})`),{mode:'file',art:0,title:'Sua folha',rate:19.9});
|
||||||
// One price per product (Dropstar, 2026-10-23): the sheet is graded, and the
|
// One price per product (Dropstar, 2026-10-23): the sheet is still graded
|
||||||
// grade is shown, but the metre costs the same as for any other grade.
|
// internally, but the customer's screen no longer shows the /100 score.
|
||||||
await waitFor(()=>evaluate('itemAtual?.nota>0'),'graded ready sheet');
|
await waitFor(()=>evaluate('itemAtual?.nota>0'),'graded ready sheet');
|
||||||
assert.deepEqual(await evaluate(`({unit:itemAtual.unit,total:itemAtual.total,shown:$('cNota').textContent===itemAtual.nota+'/100',
|
assert.deepEqual(await evaluate(`({unit:itemAtual.unit,total:itemAtual.total,hidden:!document.getElementById('cNota'),
|
||||||
metre:$('cMetro').textContent,ladder:!!document.getElementById('cEscada'),
|
metre:$('cMetro').textContent,ladder:!!document.getElementById('cEscada'),
|
||||||
discount:/desconto/i.test($('carrLin').textContent+$('resLin').textContent+$('compra').textContent)})`),
|
discount:/desconto/i.test($('carrLin').textContent+$('resLin').textContent+$('compra').textContent)})`),
|
||||||
{unit:19.9,total:19.9,shown:true,metre:'R$ 19,90',ladder:false,discount:false});
|
{unit:19.9,total:19.9,hidden:true,metre:'R$ 19,90',ladder:false,discount:false});
|
||||||
assert.deepEqual(await evaluate(`({folha:$('tipoFolhaPreco').textContent,avulsa:$('tipoAvulsaPreco').textContent})`),
|
assert.deepEqual(await evaluate(`({folha:$('tipoFolhaPreco').textContent,avulsa:$('tipoAvulsaPreco').textContent})`),
|
||||||
{folha:'R$ 19,90 /m',avulsa:'R$ 21,90 /m'});
|
{folha:'R$ 19,90 /m',avulsa:'R$ 21,90 /m'});
|
||||||
assert.equal(await evaluate(`document.querySelectorAll('[data-cm]').length`),0);
|
assert.equal(await evaluate(`document.querySelectorAll('[data-cm]').length`),0);
|
||||||
@@ -340,13 +349,13 @@ 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 now offers the same acceptance as loose art (Dropstar,
|
||||||
// the sheet goes on and the item says how many dots were accepted.
|
// 2026-11-05): the dots may be part of the art; the customer can take them.
|
||||||
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('Li e concordo'),stopped:itemAtual===null})`),{box:true,text:true,stopped:true});
|
||||||
await waitFor(()=>evaluate(`itemAtual?.residueAccepted===1 && !$('lista').textContent.includes('Sobrou 1 ponto')`),'accepted residue lets the sheet go on');
|
await evaluate(`(()=>{const el=document.querySelector('[data-residuo]');el.checked=true;
|
||||||
await click('[data-residuo="0"]');
|
el.dispatchEvent(new Event('change',{bubbles:true}));})()`);
|
||||||
await waitFor(()=>evaluate(`itemAtual===null && $('aoVivo').textContent.includes('ponto de recorte')`),'unticked, the residue stops it again');
|
await waitFor(()=>evaluate('itemAtual!==null'),'accepted residue lets the sheet through');
|
||||||
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');
|
||||||
|
|||||||
@@ -205,8 +205,15 @@ try{
|
|||||||
// Open the order's panel from its card, then click the real transition
|
// Open the order's panel from its card, then click the real transition
|
||||||
// buttons there, including the rerender after each move.
|
// buttons there, including the rerender after each move.
|
||||||
await kanban.click('[data-tab="board"]');
|
await kanban.click('[data-tab="board"]');
|
||||||
|
assert.equal(await kanban.eval(`!!document.querySelector('[data-card="${oid}"] .card-open')`),true);
|
||||||
await kanban.click(`[data-card="${oid}"]`);
|
await kanban.click(`[data-card="${oid}"]`);
|
||||||
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel');
|
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel');
|
||||||
|
// No machine at payment (Dropstar, 2026-11-05): the pull chooses one.
|
||||||
|
await waitFor(()=>kanban.eval(`board.machines.some(m=>m.active&&m.products.includes('textil'))`),'a textile machine');
|
||||||
|
const machineId=await kanban.eval(`board.machines.find(m=>m.active&&m.products.includes('textil')).id`);
|
||||||
|
await kanban.eval(`(()=>{const s=document.querySelector('[data-order="${oid}"] select[aria-label="Máquina do pedido"]');
|
||||||
|
s.value=${JSON.stringify(machineId)};s.dispatchEvent(new Event('change',{bubbles:true}));})()`);
|
||||||
|
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').machine?.id===${JSON.stringify(machineId)}`),'machine chosen');
|
||||||
// Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão before Finalizado.
|
// Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão before Finalizado.
|
||||||
for(const [title,state] of [['Arte conferida','tra'],['Imprimindo','imp'],['Revisão','rev'],['Finalizado','fin']]){
|
for(const [title,state] of [['Arte conferida','tra'],['Imprimindo','imp'],['Revisão','rev'],['Finalizado','fin']]){
|
||||||
if(state==='tra'){
|
if(state==='tra'){
|
||||||
@@ -219,7 +226,7 @@ try{
|
|||||||
await waitFor(()=>kanban.eval(`(()=>{const input=document.querySelector('[data-order="${oid}"] [data-final-item]');return !!input&&!input.closest('form').hidden;})()`),'final upload controls');
|
await waitFor(()=>kanban.eval(`(()=>{const input=document.querySelector('[data-order="${oid}"] [data-final-item]');return !!input&&!input.closest('form').hidden;})()`),'final upload controls');
|
||||||
const doc=await kanban.call('DOM.getDocument');
|
const doc=await kanban.call('DOM.getDocument');
|
||||||
const input=await kanban.call('DOM.querySelector',{nodeId:doc.root.nodeId,selector:`[data-order="${oid}"] [data-final-item]`});
|
const input=await kanban.call('DOM.querySelector',{nodeId:doc.root.nodeId,selector:`[data-order="${oid}"] [data-final-item]`});
|
||||||
await kanban.call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve('tests/fixtures/local-test.cdr')]});
|
await kanban.call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve('tests/fixtures/final-300.png')]});
|
||||||
await kanban.fill(`[data-order="${oid}"] input[placeholder="Nota da revisão"]`,'Browser test final file');
|
await kanban.fill(`[data-order="${oid}"] input[placeholder="Nota da revisão"]`,'Browser test final file');
|
||||||
await kanban.eval(`(()=>{const check=document.querySelector('[data-order="${oid}"] [data-confirm]');check.click();check.closest('form').requestSubmit();})()`);
|
await kanban.eval(`(()=>{const check=document.querySelector('[data-order="${oid}"] [data-confirm]');check.click();check.closest('form').requestSubmit();})()`);
|
||||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').version===1`),'final file approval');
|
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').version===1`),'final file approval');
|
||||||
@@ -233,6 +240,13 @@ try{
|
|||||||
await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`);
|
await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`);
|
||||||
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state);
|
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state);
|
||||||
if(state==='tra'){
|
if(state==='tra'){
|
||||||
|
// The file opens from the card itself, without first expanding the order.
|
||||||
|
await kanban.eval('closePanel()');
|
||||||
|
await kanban.click(`[data-card="${oid}"] .card-open`);
|
||||||
|
await waitFor(()=>kanban.eval(`!!document.querySelector('.viewer[open]')`),'file viewer from the card');
|
||||||
|
assert.equal(await kanban.eval(`$('drawer').hidden`),true);
|
||||||
|
await kanban.click('.viewer .vbtn.pri');
|
||||||
|
await kanban.click(`[data-card="${oid}"]`);
|
||||||
// Entering the queue moves its file to Arte conferida, whole and named after the order.
|
// Entering the queue moves its file to Arte conferida, whole and named after the order.
|
||||||
const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
|
||||||
await waitFor(async()=>(await savedFiles('2. Arte conferida')).some(n=>n.startsWith(prefix)&&!n.endsWith('.baixando')),'final file in Arte conferida',45000);
|
await waitFor(async()=>(await savedFiles('2. Arte conferida')).some(n=>n.startsWith(prefix)&&!n.endsWith('.baixando')),'final file in Arte conferida',45000);
|
||||||
|
|||||||
54
tests/finished_order_test.py
Normal file
54
tests/finished_order_test.py
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
"""Finalizado sorts by completion, including when an older order finishes last.
|
||||||
|
|
||||||
|
Run against the local stack: python3 -m tests.finished_order_test
|
||||||
|
"""
|
||||||
|
from urllib.parse import urlencode
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
|
from app.core import db
|
||||||
|
from tests.smoke_test import Client
|
||||||
|
|
||||||
|
|
||||||
|
def run():
|
||||||
|
client = Client()
|
||||||
|
owner = uuid4()
|
||||||
|
older_quote, newer_quote = uuid4(), uuid4()
|
||||||
|
older_order, newer_order = uuid4(), uuid4()
|
||||||
|
snapshot = {'customer': {'mail': 'finished-order@example.test', 'cnpj': '11222333000181'},
|
||||||
|
'items': [{'mode': 'file', 'billed_metres': '1.00'}]}
|
||||||
|
try:
|
||||||
|
with db.connect() as c:
|
||||||
|
for quote_id in (older_quote, newer_quote):
|
||||||
|
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft)
|
||||||
|
VALUES(%s,%s,%s,'finished-order-test',%s)''',
|
||||||
|
(quote_id, owner, uuid4(), Jsonb(snapshot)))
|
||||||
|
for order_id, quote_id, age in ((older_order, older_quote, 2), (newer_order, newer_quote, 1)):
|
||||||
|
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin,state,created_at)
|
||||||
|
VALUES(%s,%s,%s,%s,%s,'site','fin',now()-%s*interval '1 day')''',
|
||||||
|
(order_id, quote_id, owner, Jsonb(snapshot), Jsonb({'provider': 'teste'}), age))
|
||||||
|
# The older purchase finishes later; it must be first in Finalizado.
|
||||||
|
for order_id, minutes in ((older_order, 2), (newer_order, 1)):
|
||||||
|
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
|
||||||
|
VALUES(%s,'rev','fin','finished-order-test','',false,now()+%s*interval '1 minute')''',
|
||||||
|
(order_id, minutes))
|
||||||
|
board = client.call('/operator/board', operator=True)['orders']
|
||||||
|
finished = [o for o in board if o['state'] == 'fin']
|
||||||
|
ids = [o['id'] for o in finished]
|
||||||
|
assert ids.index(str(older_order)) < ids.index(str(newer_order)), ids
|
||||||
|
page = client.call('/operator/orders/finished?limit=2', operator=True)['orders']
|
||||||
|
assert [o['id'] for o in page] == [str(older_order), str(newer_order)], page
|
||||||
|
cursor = urlencode({'before_finished_at': page[0]['finished_at'], 'before_id': page[0]['id']})
|
||||||
|
next_page = client.call('/operator/orders/finished?' + cursor + '&limit=1', operator=True)['orders']
|
||||||
|
assert [o['id'] for o in next_page] == [str(newer_order)], next_page
|
||||||
|
print('PASS: Finalizado and its cursor use completion time, not order creation time')
|
||||||
|
finally:
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute('DELETE FROM dtf_local.movements WHERE order_id=ANY(%s)', ([older_order, newer_order],))
|
||||||
|
c.execute('DELETE FROM dtf_local.orders WHERE id=ANY(%s)', ([older_order, newer_order],))
|
||||||
|
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([older_quote, newer_quote],))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
run()
|
||||||
BIN
tests/fixtures/final-300.png
vendored
Normal file
BIN
tests/fixtures/final-300.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 147 B |
@@ -47,7 +47,8 @@ def session_upload(client, name):
|
|||||||
def run():
|
def run():
|
||||||
tag = secrets.token_hex(4)
|
tag = secrets.token_hex(4)
|
||||||
mail = f'kanban-{tag}@example.test'
|
mail = f'kanban-{tag}@example.test'
|
||||||
cnpj = '11.222.333/0001-81'
|
cnpj_digits = '11222333' + f'{int(tag, 16) % 1000000:06d}'
|
||||||
|
cnpj = f'{cnpj_digits[:2]}.{cnpj_digits[2:5]}.{cnpj_digits[5:8]}/{cnpj_digits[8:12]}-{cnpj_digits[12:]}'
|
||||||
customer = {'mail': mail, 'cnpj': cnpj, 'zap': '(16) 98765-' + str(4000 + int(tag[:3], 16) % 1000)}
|
customer = {'mail': mail, 'cnpj': cnpj, 'zap': '(16) 98765-' + str(4000 + int(tag[:3], 16) % 1000)}
|
||||||
client = Client()
|
client = Client()
|
||||||
client.call('/session')
|
client.call('/session')
|
||||||
@@ -183,20 +184,20 @@ def run():
|
|||||||
# The company's name from the registry: on the board, and found by the search.
|
# The company's name from the registry: on the board, and found by the search.
|
||||||
from app import cnpj as registry
|
from app import cnpj as registry
|
||||||
# Even after a failed try (the worker may have had no internet), a lookup stores the names.
|
# Even after a failed try (the worker may have had no internet), a lookup stores the names.
|
||||||
registry.company('11222333000181', db.connect, transport=httpx.MockTransport(lambda request: httpx.Response(
|
registry.company(cnpj_digits, db.connect, transport=httpx.MockTransport(lambda request: httpx.Response(
|
||||||
200, json={'razao_social': f'KANBAN {tag} COMERCIO LTDA', 'nome_fantasia': f'Loja {tag}'})))
|
200, json={'razao_social': f'KANBAN {tag} COMERCIO LTDA', 'nome_fantasia': f'Loja {tag}'})))
|
||||||
board = client.call('/operator/board', operator=True)
|
board = client.call('/operator/board', operator=True)
|
||||||
assert board['names']['11222333000181'] == {'legal': f'KANBAN {tag} COMERCIO LTDA', 'trade': f'Loja {tag}'}
|
assert board['names'][cnpj_digits] == {'legal': f'KANBAN {tag} COMERCIO LTDA', 'trade': f'Loja {tag}'}
|
||||||
found = client.call('/operator/search?' + urlencode({'q': f'loja {tag}'}), operator=True)
|
found = client.call('/operator/search?' + urlencode({'q': f'loja {tag}'}), operator=True)
|
||||||
assert str(order_id) in {o['id'] for o in found['orders']}, found
|
assert str(order_id) in {o['id'] for o in found['orders']}, found
|
||||||
# A failed lookup is kept and not repeated within the day.
|
# A failed lookup is kept and not repeated within the day.
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
c.execute("DELETE FROM dtf_local.cnpj_names WHERE cnpj='11222333000181'")
|
c.execute('DELETE FROM dtf_local.cnpj_names WHERE cnpj=%s', (cnpj_digits,))
|
||||||
registry.resolve(db.connect, limit=200, transport=httpx.MockTransport(lambda request: httpx.Response(503)))
|
registry.resolve(db.connect, limit=200, transport=httpx.MockTransport(lambda request: httpx.Response(503)))
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
row = c.execute("SELECT fetched_at,failed_at FROM dtf_local.cnpj_names WHERE cnpj='11222333000181'").fetchone()
|
row = c.execute('SELECT fetched_at,failed_at FROM dtf_local.cnpj_names WHERE cnpj=%s', (cnpj_digits,)).fetchone()
|
||||||
assert row['fetched_at'] is None and row['failed_at'] is not None
|
assert row['fetched_at'] is None and row['failed_at'] is not None
|
||||||
assert '11222333000181' not in registry.pending(c, 500)
|
assert cnpj_digits not in registry.pending(c, 500)
|
||||||
Client().call('/operator/stats', expected=401)
|
Client().call('/operator/stats', expected=401)
|
||||||
# "Fazer backup agora": recorded for the backup service, shown as asked.
|
# "Fazer backup agora": recorded for the backup service, shown as asked.
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
@@ -216,7 +217,7 @@ def run():
|
|||||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([pending, approved, paid],))
|
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([pending, approved, paid],))
|
||||||
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (uid,))
|
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (uid,))
|
||||||
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s', (uid,))
|
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s', (uid,))
|
||||||
c.execute("DELETE FROM dtf_local.cnpj_names WHERE cnpj='11222333000181'")
|
c.execute('DELETE FROM dtf_local.cnpj_names WHERE cnpj=%s', (cnpj_digits,))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
It empties the order tables, so it runs last. Run inside the API container:
|
It empties the order tables, so it runs last. Run inside the API container:
|
||||||
python -m tests.launch_reset_test
|
python -m tests.launch_reset_test
|
||||||
"""
|
"""
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
@@ -37,6 +39,8 @@ def run():
|
|||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
assert c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (order,)).fetchone()
|
assert c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (order,)).fetchone()
|
||||||
|
|
||||||
|
with db.connect() as c:
|
||||||
|
before_number = c.execute('SELECT COALESCE(max(number),0) AS n FROM dtf_local.orders').fetchone()['n']
|
||||||
lines.clear()
|
lines.clear()
|
||||||
assert launch_reset.main(['--confirmar', 'APAGAR'], out=lines.append) == 0, lines
|
assert launch_reset.main(['--confirmar', 'APAGAR'], out=lines.append) == 0, lines
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
@@ -45,8 +49,8 @@ def run():
|
|||||||
assert not c.execute('''SELECT 1 FROM dtf_local.uploads WHERE purged_at IS NULL
|
assert not c.execute('''SELECT 1 FROM dtf_local.uploads WHERE purged_at IS NULL
|
||||||
AND expires_at>now()''').fetchone()
|
AND expires_at>now()''').fetchone()
|
||||||
assert c.execute('SELECT count(*) AS n FROM dtf_local.operators').fetchone()['n'] >= 1
|
assert c.execute('SELECT count(*) AS n FROM dtf_local.operators').fetchone()['n'] >= 1
|
||||||
assert 'Apagado.' in lines and 'A numeração dos pedidos recomeça em #1.' in lines, lines
|
assert any('Apagado.' in line for line in lines) and 'continua de onde parou' in lines[-1], lines
|
||||||
# The worker's own role restarts the numbers: the next order is #1.
|
# The numbering is not reset: DTF-1…DTF-15 already exist in Tiny.
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
quote = uuid4()
|
quote = uuid4()
|
||||||
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
|
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
|
||||||
@@ -55,10 +59,25 @@ def run():
|
|||||||
first = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
|
first = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
|
||||||
VALUES(%s,%s,%s,%s,%s,'site') RETURNING number''', (uuid4(), quote, owner, Jsonb({'items': []}),
|
VALUES(%s,%s,%s,%s,%s,'site') RETURNING number''', (uuid4(), quote, owner, Jsonb({'items': []}),
|
||||||
Jsonb({'provider': 'teste'}))).fetchone()['number']
|
Jsonb({'provider': 'teste'}))).fetchone()['number']
|
||||||
assert first == 1, first
|
assert first > before_number, (first, before_number)
|
||||||
c.execute('DELETE FROM dtf_local.orders WHERE quote_id=%s', (quote,))
|
c.execute('DELETE FROM dtf_local.orders WHERE quote_id=%s', (quote,))
|
||||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
|
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
|
||||||
print('PASS: launch cleanup refuses real payments, counts first, then removes test orders and quotes')
|
# The Kanban folders: only the flow folders are emptied; Estampas stays.
|
||||||
|
with tempfile.TemporaryDirectory() as temp:
|
||||||
|
root = Path(temp)
|
||||||
|
for name in ('1. Arte recebida', '2. Arte conferida', '3. Imprimindo',
|
||||||
|
'4. Revisão', '5. Finalizado', 'Recibos', 'Revisões'):
|
||||||
|
(root / name).mkdir()
|
||||||
|
(root / name / 'card.txt').write_text('x')
|
||||||
|
(root / 'Estampas').mkdir()
|
||||||
|
(root / 'Estampas' / '1001.png').write_bytes(b'art')
|
||||||
|
lines.clear()
|
||||||
|
assert launch_reset.main(['--root', temp, '--confirmar', 'APAGAR'], out=lines.append) == 0, lines
|
||||||
|
for name in ('1. Arte recebida', '2. Arte conferida', '3. Imprimindo',
|
||||||
|
'4. Revisão', '5. Finalizado', 'Recibos', 'Revisões'):
|
||||||
|
assert list((root / name).iterdir()) == [], name
|
||||||
|
assert (root / 'Estampas' / '1001.png').read_bytes() == b'art'
|
||||||
|
print('PASS: launch cleanup refuses real payments, counts first, then removes test orders and quotes, keeping the numbering and the art library')
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
64
tests/machine_pull_test.py
Normal file
64
tests/machine_pull_test.py
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
"""A card has no machine until pull, and a proof gives its machine to its parent."""
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
|
from app.core import db
|
||||||
|
from tests.smoke_test import Client
|
||||||
|
from tests.users_test import order_fixture
|
||||||
|
|
||||||
|
|
||||||
|
def final_stub(c, oid, owner):
|
||||||
|
uid = uuid4()
|
||||||
|
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
|
||||||
|
expires_at,scan_state) VALUES(%s,%s,'machine-test.png',1,%s,'',true,now()+interval '1 day','clean')''',
|
||||||
|
(uid, owner, f'machine-test/{uid}'))
|
||||||
|
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
|
||||||
|
VALUES(%s,%s,%s,0,'final','machine test','test')''', (uuid4(), oid, uid))
|
||||||
|
|
||||||
|
|
||||||
|
def run():
|
||||||
|
client = Client()
|
||||||
|
client.call('/session')
|
||||||
|
tag = uuid4().hex[:6]
|
||||||
|
machine = client.call('/operator/machines', {'name': f'Pull {tag}', 'products': ['textil']}, operator=True)['id']
|
||||||
|
other = client.call('/operator/machines', {'name': f'Other {tag}', 'products': ['textil']}, operator=True)['id']
|
||||||
|
owner = uuid4()
|
||||||
|
with db.connect() as c:
|
||||||
|
_, oid = order_fixture(c, owner, 'file')
|
||||||
|
final_stub(c, oid, owner)
|
||||||
|
c.execute("UPDATE dtf_local.orders SET state='tra' WHERE id=%s", (oid,))
|
||||||
|
board = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == str(oid))
|
||||||
|
assert board['machine'] is None, board['machine']
|
||||||
|
moved = client.call(f'/operator/orders/{oid}/move', {'state': 'imp', 'version': 0,
|
||||||
|
'machine_id': machine}, operator=True)
|
||||||
|
assert str(moved['machine_id']) == machine
|
||||||
|
shown = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == str(oid))
|
||||||
|
assert shown['machine_pulled']['by'] and shown['machine_pulled']['at'], shown
|
||||||
|
assert client.call(f'/operator/orders/{oid}/history', operator=True)[-1]['machine'] == f'Pull {tag}'
|
||||||
|
|
||||||
|
with db.connect() as c:
|
||||||
|
_, parent = order_fixture(c, owner, 'file')
|
||||||
|
parent_row = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (parent,)).fetchone()
|
||||||
|
child = uuid4()
|
||||||
|
c.execute('''INSERT INTO dtf_local.orders(id,owner,snapshot,payment,origin,parent_id,state)
|
||||||
|
VALUES(%s,%s,%s,%s,'site',%s,'tra')''',
|
||||||
|
(child, owner, Jsonb({**parent_row['snapshot'], 'proof_of': 1}),
|
||||||
|
Jsonb({'provider': 'prova'}), parent))
|
||||||
|
final_stub(c, child, owner)
|
||||||
|
shown = {o['id']: o for o in client.call('/operator/board', operator=True)['orders']}
|
||||||
|
assert shown[str(parent)]['machine'] is None and shown[str(child)]['machine'] is None
|
||||||
|
client.call(f'/operator/orders/{child}/move', {'state': 'imp', 'version': 0,
|
||||||
|
'machine_id': machine}, operator=True)
|
||||||
|
shown = {o['id']: o for o in client.call('/operator/board', operator=True)['orders']}
|
||||||
|
assert shown[str(parent)]['machine']['id'] == machine == shown[str(child)]['machine']['id']
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (child,))
|
||||||
|
client.call(f'/operator/orders/{child}/proof-answer', {'result': 'ok'}, operator=True)
|
||||||
|
locked = client.call(f'/operator/orders/{parent}/machine', {'machine_id': other}, operator=True, expected=409)
|
||||||
|
assert 'mesma máquina' in locked['detail'], locked
|
||||||
|
print('PASS: no machine at creation; pull records operator and time; proof and parent share one machine')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
run()
|
||||||
@@ -153,7 +153,8 @@ def run():
|
|||||||
assert tester.call('/operator/quotes/' + test_quote + '/test-order', {}, operator=True)['id'] == order['id']
|
assert tester.call('/operator/quotes/' + test_quote + '/test-order', {}, operator=True)['id'] == order['id']
|
||||||
version = order['version']
|
version = order['version']
|
||||||
# Arte conferida, the print queue, takes the order once its final is approved.
|
# Arte conferida, the print queue, takes the order once its final is approved.
|
||||||
final = upload_bytes(tester, b'TEST ORDER FINAL', order_id=order['id'])
|
from tests.smoke_test import final_png_bytes
|
||||||
|
final = upload_bytes(tester, final_png_bytes('test order'), name='TEST-ORDER-FINAL.png', order_id=order['id'])
|
||||||
version = tester.call('/operator/orders/' + order['id'] + '/final-files',
|
version = tester.call('/operator/orders/' + order['id'] + '/final-files',
|
||||||
{'version': version, 'files': [{'item_index': 0, 'upload_id': final}], 'note': 'Teste'},
|
{'version': version, 'files': [{'item_index': 0, 'upload_id': final}], 'note': 'Teste'},
|
||||||
operator=True)['version']
|
operator=True)['version']
|
||||||
|
|||||||
@@ -9,30 +9,42 @@ Kanban until someone records what was done.
|
|||||||
Run inside the API container (it needs Pillow): python -m tests.print_file_test
|
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'}
|
||||||
|
|
||||||
|
|
||||||
def artwork(kind='PNG'):
|
def artwork(kind='PNG'):
|
||||||
image = Image.new('RGBA', (600, 300), (0, 0, 0, 0))
|
image = Image.new('RGBA', (1600, 800), (0, 0, 0, 0))
|
||||||
for x in range(40, 560):
|
for x in range(40, 1560):
|
||||||
for y in range(40, 260):
|
for y in range(40, 760):
|
||||||
image.putpixel((x, y), (220, 30, 60, 255))
|
image.putpixel((x, y), (220, 30, 60, 255))
|
||||||
out = io.BytesIO()
|
out = io.BytesIO()
|
||||||
if kind == 'PDF':
|
if kind == 'PDF':
|
||||||
image.convert('RGB').save(out, 'PDF', resolution=72)
|
image.convert('RGB').save(out, 'PDF', resolution=72)
|
||||||
else:
|
else:
|
||||||
image.save(out, kind)
|
image.save(out, kind, dpi=(300, 300))
|
||||||
return out.getvalue()
|
return out.getvalue()
|
||||||
|
|
||||||
|
|
||||||
@@ -81,16 +93,28 @@ def run():
|
|||||||
uid = upload_bytes(client, artwork(), name='LOCAL-PRINT-TEST.png')
|
uid = upload_bytes(client, artwork(), name='LOCAL-PRINT-TEST.png')
|
||||||
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(1600 / (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.
|
||||||
@@ -117,8 +141,12 @@ def run():
|
|||||||
client.call('/operator/orders/' + oid + '/move', {'state': 'tra', 'version': version}, operator=True)
|
client.call('/operator/orders/' + oid + '/move', {'state': 'tra', 'version': version}, operator=True)
|
||||||
version += 1
|
version += 1
|
||||||
# Printing, the folders still get the file of an order they hold (to take
|
# Printing, the folders still get the file of an order they hold (to take
|
||||||
# it to Finalizado later), and no one else's.
|
# it to Finalizado later), and no one else's. The pull chooses the machine.
|
||||||
client.call('/operator/orders/' + oid + '/move', {'state': 'imp', 'version': version}, operator=True)
|
tag = uuid4().hex[:6]
|
||||||
|
machine = client.call('/operator/machines', {'name': f'Hot {tag}', 'products': ['textil']},
|
||||||
|
operator=True)['id']
|
||||||
|
client.call('/operator/orders/' + oid + '/move', {'state': 'imp', 'version': version,
|
||||||
|
'machine_id': machine}, operator=True)
|
||||||
version += 1
|
version += 1
|
||||||
held = client.call('/operator/queue/folder', {'early': True, 'held': [oid]}, operator=True)
|
held = client.call('/operator/queue/folder', {'early': True, 'held': [oid]}, operator=True)
|
||||||
assert [(f['state'], f['upload_id']) for f in held['files'] if f['order'] == oid] == [('imp', str(row['upload_id']))], held
|
assert [(f['state'], f['upload_id']) for f in held['files'] if f['order'] == oid] == [('imp', str(row['upload_id']))], held
|
||||||
@@ -140,16 +168,140 @@ 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.
|
||||||
|
try:
|
||||||
|
# No class measured or chosen: the part waits for one.
|
||||||
|
assert not [p for p in client.call('/operator/queue/hot', {}, operator=True)['write'] if p['order'] == oid]
|
||||||
|
client.call('/operator/orders/' + oid + '/contraction', {'item_index': 0, 'value': 'C2'}, operator=True)
|
||||||
|
hot = client.call('/operator/queue/hot', {}, operator=True)
|
||||||
|
due = [p for p in hot['write'] if p['order'] == oid]
|
||||||
|
assert hot['folder'] == '3. Imprimindo' and [(p['folder'], p['name']) for p in due] == \
|
||||||
|
[(f'Hot {tag}/C2', 'DTF-%d-item-1.png' % order['number'])], hot
|
||||||
|
# Claimed by this computer only: asked again, nobody else gets it.
|
||||||
|
assert not [p for p in client.call('/operator/queue/hot', {}, operator=True)['write'] if p['order'] == oid]
|
||||||
|
part = due[0]['id']
|
||||||
|
assert client.call(f'/operator/queue/hot/{part}', {'state': 'written'}, operator=True)['ok']
|
||||||
|
client.call('/operator/orders/' + oid + '/contraction', {'item_index': 0, 'value': 'C1'}, operator=True,
|
||||||
|
expected=409)
|
||||||
|
watch = client.call('/operator/queue/hot', {}, operator=True)['watch']
|
||||||
|
assert [p['id'] for p in watch if p['order'] == oid] == [part], watch
|
||||||
|
assert client.call(f'/operator/queue/hot/{part}', {'state': 'consumed'}, operator=True)['ok']
|
||||||
|
assert not client.call(f'/operator/queue/hot/{part}', {'state': 'consumed'}, operator=True)['ok']
|
||||||
|
board = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == oid)
|
||||||
|
assert board['hot'] == {'parts': 1, 'taken': 1, 'waiting': 0}, board['hot']
|
||||||
|
print('PASS: the printing file goes once into its machine\'s hot folder for its class')
|
||||||
|
finally:
|
||||||
|
client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False},
|
||||||
|
operator=True)
|
||||||
|
|
||||||
|
# A single-page PDF is drawn from its vectors at 300 DPI.
|
||||||
pdf_upload = upload_bytes(client, artwork('PDF'), name='LOCAL-PRINT-TEST.pdf')
|
pdf_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['proof_y_fraction'] = '0.8'
|
||||||
|
long['production'] = {**long['production'], 'height_cm': 1050,
|
||||||
|
'placements': [{**long['production']['placements'][0], 'y_cm': 1040}]}
|
||||||
|
parent = paid_order(client, long)
|
||||||
|
board = client.call('/operator/board', operator=True)['orders']
|
||||||
|
mine = next(o for o in board if o['id'] == parent['id'])
|
||||||
|
card = next(o for o in board if o['id'] == mine['proof_card']['id'])
|
||||||
|
assert card['proof_parent']['number'] == parent['number'] and card['state'] == 'rec', card
|
||||||
|
assert card['snapshot']['proof_of'] == parent['number'] and card['payment'] == {'provider': 'prova'}
|
||||||
|
assert float(card['snapshot']['items'][0]['proof_y_fraction']) == 0.8, card['snapshot']['items'][0]
|
||||||
|
# The proof answer is the customer contact: the old "Aguardando contato"
|
||||||
|
# mark must not survive it (item 0.1).
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("""UPDATE dtf_local.orders SET contact_since=now(), contact_by='Site',
|
||||||
|
contact_note='Prova pedida no site' WHERE id=%s""", (parent['id'],))
|
||||||
|
c.execute('INSERT INTO dtf_local.contact_waits(order_id,started_at) VALUES(%s,now())', (parent['id'],))
|
||||||
|
with db.connect() as c:
|
||||||
|
assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key LIKE %s', (card['id'] + '%',)).fetchone()
|
||||||
|
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (card['id'],))
|
||||||
|
final = str(uuid4())
|
||||||
|
held = client.call('/operator/orders/' + parent['id'] + '/final-files',
|
||||||
|
{'version': parent['version'], 'files': [{'item_index': 0, 'upload_id': final}],
|
||||||
|
'note': 'Local proof test final'}, operator=True, expected=409)
|
||||||
|
assert 'Aguardando prova' in held['detail'], held
|
||||||
|
for path, body in [('/move', {'state': 'tra', 'version': parent['version']}),
|
||||||
|
('/contraction', {'item_index': 0, 'value': 'C1'}),
|
||||||
|
('/machine', {'machine_id': None}),
|
||||||
|
('/queue', {'after': card['id']})]:
|
||||||
|
held = client.call('/operator/orders/' + parent['id'] + path, body, operator=True, expected=409)
|
||||||
|
assert 'Aguardando prova' in held['detail'], (path, held)
|
||||||
|
client.call('/operator/orders/' + card['id'] + '/move', {'state': 'fin', 'version': card['version']},
|
||||||
|
operator=True, expected=409)
|
||||||
|
# Reprovada needs its reason; the order goes back to Arte recebida.
|
||||||
|
client.call('/operator/orders/' + card['id'] + '/proof-answer', {'result': 'rejected', 'reason': 'x'},
|
||||||
|
operator=True, expected=422)
|
||||||
|
client.call('/operator/orders/' + card['id'] + '/proof-answer',
|
||||||
|
{'result': 'rejected', 'reason': 'Cor do fundo errada'}, operator=True)
|
||||||
|
client.call('/operator/orders/' + card['id'] + '/proof-answer', {'result': 'ok'}, operator=True, expected=409)
|
||||||
|
board = client.call('/operator/board', operator=True)['orders']
|
||||||
|
mine = next(o for o in board if o['id'] == parent['id'])
|
||||||
|
assert mine['state'] == 'rec' and mine['proof_card']['proof_result'] == 'rejected', mine['proof_card']
|
||||||
|
assert mine['proof_card']['proof_reason'] == 'Cor do fundo errada'
|
||||||
|
assert not mine.get('contact_since'), mine
|
||||||
|
with db.connect() as c:
|
||||||
|
assert c.execute('SELECT ended_at FROM dtf_local.contact_waits WHERE order_id=%s',
|
||||||
|
(parent['id'],)).fetchone()['ended_at']
|
||||||
|
assert not [o for o in board if o['id'] == card['id']], 'an answered proof card leaves the board'
|
||||||
|
# Rejection releases the parent for corrected artwork, until a new proof card is opened.
|
||||||
|
final = upload_bytes(client, artwork(), name='LOCAL-PROOF-FINAL.png', order_id=parent['id'])
|
||||||
|
version = client.call('/operator/orders/' + parent['id'] + '/final-files',
|
||||||
|
{'version': mine['version'], 'files': [{'item_index': 0, 'upload_id': final}],
|
||||||
|
'note': 'Local proof test final'}, operator=True)['version']
|
||||||
|
# A new card, and Prova OK lets the order into the queue.
|
||||||
|
again = client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True)
|
||||||
|
client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True, expected=409)
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (again['id'],))
|
||||||
|
client.call('/operator/orders/' + again['id'] + '/proof-answer', {'result': 'ok'}, operator=True)
|
||||||
|
mine = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == parent['id'])
|
||||||
|
assert mine['proof_ok_at'] and mine['proof_card']['proof_result'] == 'ok' and mine['state'] == 'tra', mine
|
||||||
|
print('PASS: an order with a proof waits for its proof card, which is answered OK or rejected in Revisão')
|
||||||
|
|
||||||
|
# Prova OK is the parent's check: the full print file Prumo already made
|
||||||
|
# becomes the parent final and the parent enters Arte conferida (0.1).
|
||||||
|
readable = upload_bytes(client, artwork(), name='LOCAL-PROOF-REAL.png')
|
||||||
|
long = loose_item(readable, copies=1)
|
||||||
|
parent = paid_order(client, long)
|
||||||
|
# A proof card for a small order, as the panel can open one; the parent
|
||||||
|
# file is only 10 cm tall, so this test does not draw a 10 m film.
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{proof}','true') WHERE id=%s",
|
||||||
|
(parent['id'],))
|
||||||
|
client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True)
|
||||||
|
board = client.call('/operator/board', operator=True)['orders']
|
||||||
|
mine = next(o for o in board if o['id'] == parent['id'])
|
||||||
|
card = next(o for o in board if o['id'] == mine['proof_card']['id'])
|
||||||
|
wait_print(client, parent['id'], 'ready')
|
||||||
|
wait_print(client, card['id'], 'ready')
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (card['id'],))
|
||||||
|
client.call('/operator/orders/' + card['id'] + '/proof-answer', {'result': 'ok'}, operator=True)
|
||||||
|
mine = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == parent['id'])
|
||||||
|
assert mine['state'] == 'tra' and mine['final_items'] == [0], mine
|
||||||
|
assert mine['proof_ok_at'] and mine['proof_card']['proof_result'] == 'ok', mine
|
||||||
|
with db.connect() as c:
|
||||||
|
final = c.execute('''SELECT note,created_by FROM dtf_local.order_files
|
||||||
|
WHERE order_id=%s AND kind='final' AND active''', (parent['id'],)).fetchone()
|
||||||
|
assert final['created_by'] == 'Prumo' and 'prova' in final['note'].lower(), final
|
||||||
|
print('PASS: Prova OK turns Prumo\'s full file into the parent final and queues it')
|
||||||
|
|
||||||
# A 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()
|
||||||
@@ -209,7 +361,7 @@ def run():
|
|||||||
finished = client.call('/operator/orders/finished?limit=1', operator=True)
|
finished = client.call('/operator/orders/finished?limit=1', operator=True)
|
||||||
if finished['orders']:
|
if finished['orders']:
|
||||||
last = finished['orders'][-1]
|
last = finished['orders'][-1]
|
||||||
client.call('/operator/orders/finished?before_created_at=' + last['created_at'].replace('+', '%2B')
|
client.call('/operator/orders/finished?before_finished_at=' + last['finished_at'].replace('+', '%2B')
|
||||||
+ '&before_id=' + last['id'], operator=True)
|
+ '&before_id=' + last['id'], operator=True)
|
||||||
print('PASS: send log, payment history and finished orders page and filter')
|
print('PASS: send log, payment history and finished orders page and filter')
|
||||||
|
|
||||||
|
|||||||
@@ -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']
|
||||||
|
|||||||
@@ -7,12 +7,25 @@ import hashlib
|
|||||||
import http.cookiejar
|
import http.cookiejar
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import struct
|
||||||
|
import zlib
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import time
|
import time
|
||||||
from urllib.error import HTTPError
|
from urllib.error import HTTPError
|
||||||
from urllib.request import build_opener, HTTPCookieProcessor, Request, urlopen
|
from urllib.request import build_opener, HTTPCookieProcessor, Request, urlopen
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
|
|
||||||
|
def final_png_bytes(label='final'):
|
||||||
|
"""A tiny real RGBA PNG tagged 300 DPI for operator final-file tests."""
|
||||||
|
def chunk(kind, body):
|
||||||
|
return struct.pack('>I', len(body)) + kind + body + struct.pack('>I', zlib.crc32(kind + body) & 0xffffffff)
|
||||||
|
red = hashlib.sha256(label.encode()).digest()[0]
|
||||||
|
row = b'\x00' + bytes((red, 30, 60, 255, 0, 0, 0, 0))
|
||||||
|
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 2, 1, 8, 6, 0, 0, 0)) +
|
||||||
|
chunk(b'pHYs', struct.pack('>IIB', 11811, 11811, 1)) +
|
||||||
|
chunk(b'IDAT', zlib.compress(row)) + chunk(b'IEND', b''))
|
||||||
|
|
||||||
if Path('.env').exists():
|
if Path('.env').exists():
|
||||||
for line in Path('.env').read_text().splitlines():
|
for line in Path('.env').read_text().splitlines():
|
||||||
if line.strip() and not line.startswith('#') and '=' in line:
|
if line.strip() and not line.startswith('#') and '=' in line:
|
||||||
@@ -197,9 +210,11 @@ def run():
|
|||||||
# A cart the Site priced is approved at once and can be paid straight away,
|
# A cart the Site priced is approved at once and can be paid straight away,
|
||||||
# at the server's own prices; no operator can then change it.
|
# at the server's own prices; no operator can then change it.
|
||||||
# The server works the grade out from the file: this PNG is 6059 px across
|
# The server works the grade out from the file: this PNG is 6059 px across
|
||||||
# 57 cm, 270 DPI, which is grade 90.
|
# 57 cm, 270 DPI, which is grade 100 under the 200 DPI clean threshold.
|
||||||
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
||||||
graded=upload_bytes(client,png,name='arte-270dpi.png')
|
graded=upload_bytes(client,png,name='arte-270dpi.png')
|
||||||
|
low_png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(3366).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
||||||
|
low=upload_bytes(client,low_png,name='arte-150dpi.png')
|
||||||
small={**draft,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,graded)]}
|
small={**draft,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,graded)]}
|
||||||
auto=client.call('/quotes',small)
|
auto=client.call('/quotes',small)
|
||||||
assert auto['status']=='approved'
|
assert auto['status']=='approved'
|
||||||
@@ -214,6 +229,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}
|
||||||
@@ -222,9 +260,10 @@ def run():
|
|||||||
assert client.call('/quotes/'+held['id'])['review_reason']=='Nota não conferida no servidor'
|
assert client.call('/quotes/'+held['id'])['review_reason']=='Nota não conferida no servidor'
|
||||||
# A better grade than the file supports, or one the server cannot check, waits too:
|
# A better grade than the file supports, or one the server cannot check, waits too:
|
||||||
# the price ignores the grade, but the order shows it.
|
# the price ignores the grade, but the order shows it.
|
||||||
inflated=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',100,graded)]})
|
low_item={**item_spec('avulsa','2.75',100,low),'quality_status':'warning','quality_acknowledged':True}
|
||||||
|
inflated=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[low_item]})
|
||||||
assert inflated['status']=='pending_review'
|
assert inflated['status']=='pending_review'
|
||||||
assert client.call('/quotes/'+inflated['id'])['review_reason']=='Nota 100 maior que a do arquivo (90)'
|
assert client.call('/quotes/'+inflated['id'])['review_reason']=='Nota 100 maior que a do arquivo (75)'
|
||||||
unchecked=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,uid)]})
|
unchecked=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,uid)]})
|
||||||
assert client.call('/quotes/'+unchecked['id'])['review_reason']=='Nota não conferida no servidor'
|
assert client.call('/quotes/'+unchecked['id'])['review_reason']=='Nota não conferida no servidor'
|
||||||
print('PASS: priced carts are approved at checkout; large or inconsistent ones wait for review')
|
print('PASS: priced carts are approved at checkout; large or inconsistent ones wait for review')
|
||||||
@@ -239,21 +278,32 @@ def run():
|
|||||||
board=client.call('/operator/board',operator=True)
|
board=client.call('/operator/board',operator=True)
|
||||||
assert len([o for o in board['orders'] if o['quote_id']==qid])==1
|
assert len([o for o in board['orders'] if o['quote_id']==qid])==1
|
||||||
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':0},operator=True,expected=409)
|
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':0},operator=True,expected=409)
|
||||||
client.call('/operator/orders/'+oid+'/move',{'state':'cor','version':0},operator=True,expected=422)
|
# Above 10 m the proof comes first: the parent cannot move at all until
|
||||||
version=0
|
# Prova OK on its proof card in Revisão (item 0.1).
|
||||||
|
held=client.call('/operator/orders/'+oid+'/move',{'state':'cor','version':0},operator=True,expected=409)
|
||||||
|
assert 'Aguardando prova' in held['detail'], held
|
||||||
|
card=next(o for o in board['orders'] if o['id']==oid)['proof_card']
|
||||||
|
from app.core import db
|
||||||
|
with db.connect() as c:
|
||||||
|
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s",(card['id'],))
|
||||||
|
client.call('/operator/orders/'+card['id']+'/proof-answer',{'result':'ok'},operator=True)
|
||||||
|
version=next(o for o in client.call('/operator/board',operator=True)['orders'] if o['id']==oid)['version']
|
||||||
|
client.call('/operator/orders/'+oid+'/move',{'state':'cor','version':version},operator=True,expected=422)
|
||||||
# Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão comes before Finalizado.
|
# Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão comes before Finalizado.
|
||||||
|
machine=None
|
||||||
for state in ('cor','rec','tra','imp','rev','fin'):
|
for state in ('cor','rec','tra','imp','rev','fin'):
|
||||||
if state=='tra':
|
if state=='tra':
|
||||||
# The queue takes approved final files only.
|
# The queue takes approved final files only.
|
||||||
client.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
client.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
||||||
files=[{'item_index':i,'upload_id':upload_bytes(client,b'LOCAL FINAL FIXTURE '+str(i).encode(),order_id=oid)} for i in range(4)]
|
files=[{'item_index':i,'upload_id':upload_bytes(client,final_png_bytes(str(i)),name=f'LOCAL-FINAL-{i}.png',order_id=oid)} for i in range(4)]
|
||||||
result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True)
|
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':
|
body={'state':state,'version':version,'reason':'Local test correction' if state=='cor' else ''}
|
||||||
# Above 10 m the proof comes first: no Finalizado before Prova OK (app/proof.py).
|
if state=='imp':
|
||||||
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':version},operator=True,expected=409)
|
if machine is None:
|
||||||
version=client.call('/operator/orders/'+oid+'/proof',{},operator=True)['version']
|
machine=client.call('/operator/machines',{'name':'Smoke '+uuid4().hex[:6],'products':['textil']},operator=True)['id']
|
||||||
moved=client.call('/operator/orders/'+oid+'/move',{'state':state,'version':version,'reason':'Local test correction' if state=='cor' else ''},operator=True)
|
body['machine_id']=machine
|
||||||
|
moved=client.call('/operator/orders/'+oid+'/move',body,operator=True)
|
||||||
version+=1;assert moved['version']==version
|
version+=1;assert moved['version']==version
|
||||||
client.call('/operator/orders/'+oid+'/move',{'state':'rec','version':0},operator=True,expected=409)
|
client.call('/operator/orders/'+oid+'/move',{'state':'rec','version':0},operator=True,expected=409)
|
||||||
assert len(client.call('/operator/orders/'+oid+'/history',operator=True))==6
|
assert len(client.call('/operator/orders/'+oid+'/history',operator=True))==6
|
||||||
|
|||||||
@@ -62,25 +62,43 @@ class GradeCheckTests(unittest.TestCase):
|
|||||||
self.assertEqual(grade_check.pdf_dpi(handle.name), 300)
|
self.assertEqual(grade_check.pdf_dpi(handle.name), 300)
|
||||||
|
|
||||||
def test_grades_follow_the_site(self):
|
def test_grades_follow_the_site(self):
|
||||||
# 57 cm is 22.44 in: 6059 px is 270 DPI, grade 90; 3366 px is 150 DPI, grade 50.
|
# 57 cm is 22.44 in: the new clean threshold is 200 DPI.
|
||||||
files = FakeFiles({'a.png': encoded('PNG', (6059, 100)), 'b.jpg': encoded('JPEG', (3366, 100)),
|
files = FakeFiles({'a.png': encoded('PNG', (6059, 100)), 'b.jpg': encoded('JPEG', (3366, 100)),
|
||||||
'tall.png': encoded('PNG', (100, 2362)), 'x.cdr': b'CDR'})
|
'tall.png': encoded('PNG', (100, 2362)), 'x.cdr': b'CDR'})
|
||||||
rows = {n: {'name': n, 'size': 1} for n in files.blobs}
|
rows = {n: {'name': n, 'size': 1} for n in files.blobs}
|
||||||
# A sheet takes the worst sheet's grade.
|
# A sheet takes the worst sheet's grade.
|
||||||
self.assertEqual(grade_check.item_grade(files, item('sheet', 0, [('a.png', 57, 0)]), rows), 90)
|
self.assertEqual(grade_check.item_grade(files, item('sheet', 0, [('a.png', 57, 0)]), rows), 100)
|
||||||
self.assertEqual(grade_check.item_grade(files, item('sheet', 0, [('a.png', 57, 0), ('b.jpg', 57, 0)]), rows), 50)
|
self.assertEqual(grade_check.item_grade(files, item('sheet', 0, [('a.png', 57, 0), ('b.jpg', 57, 0)]), rows), 75)
|
||||||
# Artworks average; a rotated one is measured along its height.
|
# Artworks average; a rotated one is measured along its height.
|
||||||
self.assertEqual(grade_check.item_grade(files, item('artwork', 0, [('a.png', 57, 0), ('b.jpg', 57, 0)]), rows), 70)
|
self.assertEqual(grade_check.item_grade(files, item('artwork', 0, [('a.png', 57, 0), ('b.jpg', 57, 0)]), rows), 88)
|
||||||
self.assertEqual(grade_check.item_grade(files, item('artwork', 0, [('tall.png', 20, 90)]), rows), 100)
|
self.assertEqual(grade_check.item_grade(files, item('artwork', 0, [('tall.png', 20, 90)]), rows), 100)
|
||||||
self.assertIsNone(grade_check.item_grade(files, item('sheet', 0, [('x.cdr', 57, 0)]), rows))
|
self.assertIsNone(grade_check.item_grade(files, item('sheet', 0, [('x.cdr', 57, 0)]), rows))
|
||||||
# What the cart claims is checked, with a point or two of rounding.
|
# What the cart claims is checked, with a point or two of rounding.
|
||||||
claim = lambda g, src: grade_check.mismatch(files, [item('sheet', g, src)], rows)
|
claim = lambda g, src: grade_check.mismatch(files, [item('sheet', g, src)], rows)
|
||||||
self.assertIsNone(claim(90, [('a.png', 57, 0)]))
|
self.assertIsNone(claim(100, [('a.png', 57, 0)]))
|
||||||
self.assertIsNone(claim(92, [('a.png', 57, 0)]))
|
self.assertIsNone(claim(77, [('b.jpg', 57, 0)]))
|
||||||
self.assertEqual(claim(100, [('a.png', 57, 0)]), 'Nota 100 maior que a do arquivo (90)')
|
self.assertEqual(claim(100, [('b.jpg', 57, 0)]), 'Nota 100 maior que a do arquivo (75)')
|
||||||
self.assertEqual(claim(40, [('x.cdr', 57, 0)]), 'Nota não conferida no servidor')
|
self.assertEqual(claim(40, [('x.cdr', 57, 0)]), 'Nota não conferida no servidor')
|
||||||
self.assertIsNone(claim(0, [('x.cdr', 57, 0)]))
|
self.assertIsNone(claim(0, [('x.cdr', 57, 0)]))
|
||||||
|
|
||||||
|
def test_resolution_boundaries_and_consent(self):
|
||||||
|
width = lambda dpi: int(dpi * 57 / 2.54) + 1
|
||||||
|
files = FakeFiles({f'{dpi}.png': encoded('PNG', (width(dpi), 20))
|
||||||
|
for dpi in (95, 96, 199, 200, 287, 293)})
|
||||||
|
rows = {name: {'name': name, 'size': 1} for name in files.blobs}
|
||||||
|
def issue(dpi, status='ok', acknowledged=False):
|
||||||
|
spec = item('sheet', 0, [(f'{dpi}.png', 57, 0)])
|
||||||
|
spec.update(quality_status=status, quality_acknowledged=acknowledged)
|
||||||
|
return grade_check.resolution_issue(files, [spec], rows)
|
||||||
|
self.assertIn('abaixo do mínimo', issue(95))
|
||||||
|
self.assertIn('confirme a ressalva', issue(96))
|
||||||
|
self.assertIn('confirme a ressalva', issue(199))
|
||||||
|
self.assertIsNone(issue(96, 'warning', True))
|
||||||
|
self.assertIsNone(issue(199, 'warning', True))
|
||||||
|
for dpi in (200, 287, 293):
|
||||||
|
self.assertIsNone(issue(dpi), dpi)
|
||||||
|
self.assertEqual(grade_check.grade_of(dpi), 100)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -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
176
tests/test_printpng.py
Normal 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()
|
||||||
27
tests/test_printpng_validate.py
Normal file
27
tests/test_printpng_validate.py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
"""Final artwork acceptance is based on PNG bytes, alpha and 300 DPI metadata."""
|
||||||
|
import io
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from app.printpng_validate import final_png_issue
|
||||||
|
|
||||||
|
|
||||||
|
def png(mode='RGBA', dpi=(300, 300)):
|
||||||
|
out = io.BytesIO()
|
||||||
|
Image.new(mode, (3, 3), (0, 0, 0, 0) if mode == 'RGBA' else (0, 0, 0)).save(out, 'PNG', dpi=dpi)
|
||||||
|
return out.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
class FinalPngTests(unittest.TestCase):
|
||||||
|
def test_accepts_only_rgba_300dpi_png(self):
|
||||||
|
self.assertIsNone(final_png_issue(png()))
|
||||||
|
self.assertIn('precisa ser PNG', final_png_issue(b'%PDF-1.7'))
|
||||||
|
self.assertIn('transparência', final_png_issue(png('RGB')))
|
||||||
|
self.assertIn('300 DPI', final_png_issue(png(dpi=(72, 72))))
|
||||||
|
self.assertIn('300 DPI', final_png_issue(png(dpi=(300, 150))))
|
||||||
|
self.assertIn('incompleto', final_png_issue(png()[:50]))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
26
tests/test_proof_cut.py
Normal file
26
tests/test_proof_cut.py
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
"""The proof window: 15 cm around the finest stroke, never outside the film."""
|
||||||
|
import unittest
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from app.printpng import proof_cut
|
||||||
|
|
||||||
|
|
||||||
|
class ProofCutTests(unittest.TestCase):
|
||||||
|
def test_centres_the_window_on_the_finest_stroke(self):
|
||||||
|
self.assertEqual(proof_cut(100, 15, 0.5), [Decimal('42.5'), Decimal('57.5')])
|
||||||
|
self.assertEqual(proof_cut(100, 15, 0.8), [Decimal('72.5'), Decimal('87.5')])
|
||||||
|
|
||||||
|
def test_clamps_at_both_ends(self):
|
||||||
|
self.assertEqual(proof_cut(100, 15, 0), [Decimal(0), Decimal(15)])
|
||||||
|
self.assertEqual(proof_cut(100, 15, 1), [Decimal(85), Decimal(100)])
|
||||||
|
|
||||||
|
def test_a_short_film_is_the_whole_proof(self):
|
||||||
|
self.assertEqual(proof_cut(10, 15, 0.5), [Decimal(0), Decimal(10)])
|
||||||
|
self.assertEqual(proof_cut(10, 15, None), [Decimal(0), Decimal(10)])
|
||||||
|
|
||||||
|
def test_without_a_measure_the_old_top_window_remains(self):
|
||||||
|
self.assertEqual(proof_cut(100, 15, None), [Decimal(0), Decimal(15)])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
66
tests/test_proof_render.py
Normal file
66
tests/test_proof_render.py
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
"""A free proof is a 15 cm window around the measured fine stroke, not the top."""
|
||||||
|
import io
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
from app.printpng import render
|
||||||
|
|
||||||
|
PX_CM = 300 / 2.54
|
||||||
|
|
||||||
|
|
||||||
|
def item(height_cm=30, fraction='0.75'):
|
||||||
|
return {
|
||||||
|
'mode': 'file', 'metres': '10.5', 'billed_metres': '0',
|
||||||
|
'production': {
|
||||||
|
'version': 3, 'film_width_cm': 20, 'height_cm': height_cm,
|
||||||
|
'sources': [{'upload_id': '00000000-0000-0000-0000-000000000001',
|
||||||
|
'kind': 'sheet', 'width_cm': 20, 'length_cm': height_cm,
|
||||||
|
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
|
||||||
|
'measurement': 'file'}],
|
||||||
|
'placements': [{'source_index': 0, 'copy_index': 0, 'x_cm': 0, 'y_cm': 0,
|
||||||
|
'width_cm': 20, 'length_cm': height_cm,
|
||||||
|
'rotation_degrees': 0, 'mirrored': False}],
|
||||||
|
},
|
||||||
|
'proof_parent_item_index': 0, 'proof_y_fraction': fraction,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ProofRenderTests(unittest.TestCase):
|
||||||
|
def _sheet(self, folder):
|
||||||
|
height = round(30 * PX_CM)
|
||||||
|
width = round(20 * PX_CM)
|
||||||
|
image = Image.new('RGBA', (width, height), (220, 30, 60, 255))
|
||||||
|
ImageDraw.Draw(image).rectangle((0, height // 2, width - 1, height - 1),
|
||||||
|
fill=(30, 60, 220, 255))
|
||||||
|
path = Path(folder) / 'sheet.png'
|
||||||
|
image.save(path, 'PNG', dpi=(300, 300))
|
||||||
|
return str(path)
|
||||||
|
|
||||||
|
def test_the_window_follows_the_finest_stroke(self):
|
||||||
|
with tempfile.TemporaryDirectory() as source, tempfile.TemporaryDirectory() as out:
|
||||||
|
sheet = self._sheet(source)
|
||||||
|
parts, detail = render(item(), {0: (sheet, 'sheet.png')}, out, 'proof',
|
||||||
|
limit_cm=15, proof_fraction='0.75')
|
||||||
|
self.assertEqual(len(parts), 1)
|
||||||
|
self.assertEqual(detail['parts'][0]['from_cm'], '15')
|
||||||
|
with Image.open(parts[0][0]) as proof:
|
||||||
|
self.assertEqual(proof.width, round(20 * PX_CM))
|
||||||
|
self.assertLessEqual(abs(proof.height - round(15 * PX_CM)), 1)
|
||||||
|
# The bottom half is blue: the window covered 15 to 30 cm.
|
||||||
|
self.assertEqual(proof.getpixel((proof.width // 2, round(5 * PX_CM))), (30, 60, 220, 255))
|
||||||
|
|
||||||
|
def test_the_top_is_still_the_default_without_a_measure(self):
|
||||||
|
with tempfile.TemporaryDirectory() as source, tempfile.TemporaryDirectory() as out:
|
||||||
|
sheet = self._sheet(source)
|
||||||
|
parts, detail = render(item(fraction=None), {0: (sheet, 'sheet.png')}, out, 'proof',
|
||||||
|
limit_cm=15)
|
||||||
|
self.assertEqual(detail['parts'][0]['from_cm'], '0')
|
||||||
|
with Image.open(parts[0][0]) as proof:
|
||||||
|
self.assertEqual(proof.getpixel((proof.width // 2, round(5 * PX_CM))), (220, 30, 60, 255))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
35
tests/test_speed.py
Normal file
35
tests/test_speed.py
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
"""Números' speed block: average and p95, in the units the PDF asks for."""
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from app.api.operator import speed_figures
|
||||||
|
|
||||||
|
|
||||||
|
class SpeedFiguresTests(unittest.TestCase):
|
||||||
|
def test_formats_seconds_and_upload_speed(self):
|
||||||
|
site = {'page_avg': 1500, 'page_p95': 3000, 'page_n': 4,
|
||||||
|
'upload_avg': 2.5, 'upload_p95': 1.5, 'upload_n': 4,
|
||||||
|
'analysis_avg': 12000, 'analysis_p95': 20000, 'analysis_n': 3,
|
||||||
|
'montage_avg': 8000, 'montage_p95': 9000, 'montage_n': 2}
|
||||||
|
generation = {'per10_avg': 90, 'per10_p95': 120, 'per10_n': 5}
|
||||||
|
card = {'avg_s': 0.4, 'p95_s': 0.9, 'n': 2}
|
||||||
|
rows = {row['key']: row for row in speed_figures(site, generation, card)}
|
||||||
|
self.assertEqual(rows['page']['average'], 1.5)
|
||||||
|
self.assertEqual(rows['page']['p95'], 3.0)
|
||||||
|
self.assertEqual(rows['upload']['unit'], 'MB/s')
|
||||||
|
self.assertEqual(rows['analysis']['average'], 12.0)
|
||||||
|
self.assertEqual(rows['montage']['p95'], 9.0)
|
||||||
|
self.assertEqual(rows['print']['average'], 90)
|
||||||
|
self.assertEqual(rows['card']['samples'], 2)
|
||||||
|
|
||||||
|
def test_missing_samples_stay_empty(self):
|
||||||
|
empty = {key: None for key in ('page_avg', 'page_p95', 'page_n', 'upload_avg', 'upload_p95',
|
||||||
|
'upload_n', 'analysis_avg', 'analysis_p95', 'analysis_n',
|
||||||
|
'montage_avg', 'montage_p95', 'montage_n')}
|
||||||
|
generation = {'per10_avg': None, 'per10_p95': None, 'per10_n': 0}
|
||||||
|
card = {'avg_s': None, 'p95_s': None, 'n': 0}
|
||||||
|
rows = speed_figures(empty, generation, card)
|
||||||
|
self.assertTrue(all(row['average'] is None and row['samples'] == 0 for row in rows))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -4,13 +4,11 @@ Run inside the API container: python -m tests.users_test
|
|||||||
"""
|
"""
|
||||||
import secrets
|
import secrets
|
||||||
import time
|
import time
|
||||||
from decimal import Decimal
|
|
||||||
from urllib.request import Request, urlopen
|
from urllib.request import Request, urlopen
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
from app import machines as routing
|
|
||||||
from app import payments, proof
|
from app import payments, proof
|
||||||
from app.core import db
|
from app.core import db
|
||||||
from tests.smoke_test import BASE, Client, with_host
|
from tests.smoke_test import BASE, Client, with_host
|
||||||
@@ -61,34 +59,7 @@ def pickup_photo(client, oid, content):
|
|||||||
return uid
|
return uid
|
||||||
|
|
||||||
|
|
||||||
def expected_machine(su, product, metres=1.0):
|
|
||||||
"""What app/machines.py should pick now: the active machine of the product
|
|
||||||
with the fewest metres open, among those with room, else among all."""
|
|
||||||
# Listed in the order they were registered: min() keeps the first of equals, as the routing does.
|
|
||||||
rows = [m for m in su.call('/operator/machines', operator=True)['machines'] if m['active'] and product in m['products']]
|
|
||||||
room = [m for m in rows if m['limit_metres'] is None or m['open_metres'] + metres <= m['limit_metres']]
|
|
||||||
return min(room or rows, key=lambda m: m['open_metres'])['id']
|
|
||||||
|
|
||||||
|
|
||||||
def picking():
|
|
||||||
"""The choice itself: room first, then the fewest metres, then the first registered."""
|
|
||||||
textil = {'snapshot': {'items': [{'mode': 'file', 'billed_metres': '1'}]}}
|
|
||||||
uv = {'snapshot': {'items': [{'mode': 'uvfile', 'billed_metres': '1'}]}}
|
|
||||||
a = {'id': 'a', 'products': ['textil'], 'active': True, 'limit_metres': Decimal('2')}
|
|
||||||
b = {'id': 'b', 'products': ['textil'], 'active': True, 'limit_metres': None}
|
|
||||||
off = {'id': 'off', 'products': ['textil'], 'active': False, 'limit_metres': None}
|
|
||||||
assert routing.pick([a, b], {}, textil)['id'] == 'a'
|
|
||||||
assert routing.pick([off, a, b], {'a': Decimal('0.5')}, textil)['id'] == 'b'
|
|
||||||
# Full: the one with room takes it, even with more metres open.
|
|
||||||
assert routing.pick([a, b], {'a': Decimal('1.5'), 'b': Decimal('9')}, textil)['id'] == 'b'
|
|
||||||
# All full: the least loaded anyway.
|
|
||||||
b_full = {**b, 'limit_metres': Decimal('3')}
|
|
||||||
assert routing.pick([a, b_full], {'a': Decimal('5'), 'b': Decimal('4')}, textil)['id'] == 'b'
|
|
||||||
assert routing.pick([a, b], {}, uv) is None
|
|
||||||
|
|
||||||
|
|
||||||
def run():
|
def run():
|
||||||
picking()
|
|
||||||
tag = secrets.token_hex(3)
|
tag = secrets.token_hex(3)
|
||||||
su = Client()
|
su = Client()
|
||||||
su.call('/session')
|
su.call('/session')
|
||||||
@@ -131,19 +102,22 @@ def run():
|
|||||||
expected=409)
|
expected=409)
|
||||||
admin.call(f"/operator/users/{mine['id']}/delete", {}, expected=409)
|
admin.call(f"/operator/users/{mine['id']}/delete", {}, expected=409)
|
||||||
|
|
||||||
# Orders other suites left open get their machines first; then each paid
|
# No machine at payment: a card waits for a person to choose one or to
|
||||||
# order goes to the machine of its product with the fewest metres open.
|
# pull it into Imprimindo (Dropstar, 2026-11-05).
|
||||||
su.call('/operator/board', operator=True)
|
su.call('/operator/board', operator=True)
|
||||||
want = {'textil': expected_machine(su, 'textil'), 'uv': expected_machine(su, 'uv')}
|
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
textil_q, textil_o = order_fixture(c, owner, 'file')
|
textil_q, textil_o = order_fixture(c, owner, 'file')
|
||||||
uv_q, uv_o = order_fixture(c, owner, 'uvfile')
|
uv_q, uv_o = order_fixture(c, owner, 'uvfile')
|
||||||
made += [(textil_q, textil_o), (uv_q, uv_o)]
|
made += [(textil_q, textil_o), (uv_q, uv_o)]
|
||||||
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
||||||
assert board[str(textil_o)]['machine']['id'] == want['textil'] and not board[str(textil_o)]['machine']['chosen']
|
assert board[str(uv_o)]['machine'] is None and not board[str(textil_o)]['machine_chosen']
|
||||||
assert board[str(uv_o)]['machine']['id'] == want['uv'] and not board[str(uv_o)]['machine']['chosen']
|
assert board[str(uv_o)]['machine'] is None and not board[str(uv_o)]['machine_chosen']
|
||||||
# On the UV machine of this test, whatever the others carry.
|
# Chosen before printing, each one stays there.
|
||||||
|
su.call(f'/operator/orders/{textil_o}/machine', {'machine_id': textil}, operator=True)
|
||||||
su.call(f'/operator/orders/{uv_o}/machine', {'machine_id': uv}, operator=True)
|
su.call(f'/operator/orders/{uv_o}/machine', {'machine_id': uv}, operator=True)
|
||||||
|
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
||||||
|
assert board[str(textil_o)]['machine']['id'] == textil and board[str(textil_o)]['machine']['chosen']
|
||||||
|
assert board[str(uv_o)]['machine']['id'] == uv and board[str(uv_o)]['machine']['chosen']
|
||||||
|
|
||||||
# The operator prints: Arte conferida to Imprimindo to Revisão, nothing
|
# The operator prints: Arte conferida to Imprimindo to Revisão, nothing
|
||||||
# else (Dropstar, 2026-10-23). After signing in they say which machine
|
# else (Dropstar, 2026-10-23). After signing in they say which machine
|
||||||
@@ -153,6 +127,11 @@ def run():
|
|||||||
assert (me['machine_question'], me['machine_answered'], me['machine']) == ('required', False, None), me
|
assert (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 +173,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.
|
||||||
@@ -332,36 +312,36 @@ def run():
|
|||||||
listed = {m['id']: m for m in admin.call('/operator/machines')['machines']}
|
listed = {m['id']: m for m in admin.call('/operator/machines')['machines']}
|
||||||
assert listed[textil2]['operators'] == [] and [o['id'] for o in listed[uv]['operators']] == [op_id], listed[uv]
|
assert listed[textil2]['operators'] == [] and [o['id'] for o in listed[uv]['operators']] == [op_id], listed[uv]
|
||||||
assert next(u for u in admin.call('/operator/users')['users'] if u['id'] == op_id)['machines'] == [uv]
|
assert next(u for u in admin.call('/operator/users')['users'] if u['id'] == op_id)['machines'] == [uv]
|
||||||
# The next order goes to the one with fewer metres open.
|
# A paid order starts with no machine; choosing one by hand is the
|
||||||
target = expected_machine(su, 'textil')
|
# only way it gets one before a pull (Dropstar, 2026-11-05).
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
made.append(order_fixture(c, owner, 'file'))
|
made.append(order_fixture(c, owner, 'file'))
|
||||||
second = str(made[-1][1])
|
second = str(made[-1][1])
|
||||||
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
||||||
assert board[second]['machine']['id'] == target
|
assert board[second]['machine'] is None and not board[second]['machine_chosen']
|
||||||
# Chosen by hand, the order stays there; back to automatic, it is routed again.
|
|
||||||
su.call(f'/operator/orders/{second}/machine', {'machine_id': textil2}, operator=True)
|
su.call(f'/operator/orders/{second}/machine', {'machine_id': textil2}, operator=True)
|
||||||
|
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
||||||
|
assert board[second]['machine']['id'] == textil2 and board[second]['machine']['chosen']
|
||||||
listed = {m['id']: m for m in su.call('/operator/machines', operator=True)['machines']}
|
listed = {m['id']: m for m in su.call('/operator/machines', operator=True)['machines']}
|
||||||
assert listed[textil2]['open_orders'] >= 1 and listed[textil2]['states'].get('rec', 0) >= 1
|
assert listed[textil2]['open_orders'] >= 1 and listed[textil2]['states'].get('rec', 0) >= 1
|
||||||
|
|
||||||
# A limit: once full, the next order goes to a machine with room.
|
# The limit is shown on the machine; it no longer routes new orders.
|
||||||
open_now = listed[textil2]['open_metres']
|
open_now = listed[textil2]['open_metres']
|
||||||
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'],
|
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'],
|
||||||
'limit_metres': round(open_now + 0.5, 1)})
|
'limit_metres': round(open_now + 0.5, 1)})
|
||||||
listed = {m['id']: m for m in su.call('/operator/machines', operator=True)['machines']}
|
listed = {m['id']: m for m in su.call('/operator/machines', operator=True)['machines']}
|
||||||
assert listed[textil2]['limit_metres'] == round(open_now + 0.5, 1)
|
assert listed[textil2]['limit_metres'] == round(open_now + 0.5, 1)
|
||||||
target = expected_machine(su, 'textil')
|
|
||||||
assert target != textil2
|
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
made.append(order_fixture(c, owner, 'file'))
|
made.append(order_fixture(c, owner, 'file'))
|
||||||
third = str(made[-1][1])
|
third = str(made[-1][1])
|
||||||
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
||||||
assert board[third]['machine']['id'] == target
|
assert board[third]['machine'] is None and not board[third]['machine_chosen']
|
||||||
|
su.call(f'/operator/orders/{third}/machine', {'machine_id': textil}, operator=True)
|
||||||
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'],
|
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'],
|
||||||
'limit_metres': 0}, expected=422)
|
'limit_metres': 0}, expected=422)
|
||||||
su.call(f'/operator/orders/{second}/machine', {'machine_id': None}, operator=True)
|
su.call(f'/operator/orders/{second}/machine', {'machine_id': None}, operator=True)
|
||||||
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
||||||
assert not board[second]['machine']['chosen']
|
assert not board[second]['machine_chosen']
|
||||||
|
|
||||||
# Números per machine: an order printed for half an hour on its machine, then
|
# Números per machine: an order printed for half an hour on its machine, then
|
||||||
# finished. It counts the film printed (0,40 m), not the metre billed.
|
# finished. It counts the film printed (0,40 m), not the metre billed.
|
||||||
@@ -375,10 +355,10 @@ def run():
|
|||||||
c.execute(f'''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
|
c.execute(f'''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
|
||||||
VALUES(%s,%s,%s,'users-test','',false,{at})''', (third, frm, to))
|
VALUES(%s,%s,%s,'users-test','',false,{at})''', (third, frm, to))
|
||||||
after = {m['id']: m for m in su.call('/operator/stats?days=7', operator=True)['machines']}
|
after = {m['id']: m for m in su.call('/operator/stats?days=7', operator=True)['machines']}
|
||||||
assert after[target]['orders'] == before[target]['orders'] + 1
|
assert after[textil]['orders'] == before[textil]['orders'] + 1
|
||||||
assert round(after[target]['metres'] - before[target]['metres'], 2) == 0.4, (before[target], after[target])
|
assert round(after[textil]['metres'] - before[textil]['metres'], 2) == 0.4, (before[textil], after[textil])
|
||||||
assert after[target]['last_finished'] and after[target]['metres_per_hour'] is not None
|
assert after[textil]['last_finished'] and after[textil]['metres_per_hour'] is not None
|
||||||
assert after[target]['printing_hours'] >= before[target]['printing_hours'] + 0.49
|
assert after[textil]['printing_hours'] >= before[textil]['printing_hours'] + 0.49
|
||||||
# Two orders printing at once on one machine: the half hour they share counts
|
# Two orders printing at once on one machine: the half hour they share counts
|
||||||
# once, so the machine did 1,50 m in 0,5 h, not in 1 h.
|
# once, so the machine did 1,50 m in 0,5 h, not in 1 h.
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
@@ -399,7 +379,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 +390,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 +398,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']) == \
|
||||||
@@ -469,12 +468,13 @@ def run():
|
|||||||
assert {o['name'] for o in on_free} == {'Op', 'Marcus'}, on_free
|
assert {o['name'] for o in on_free} == {'Op', 'Marcus'}, on_free
|
||||||
designer.call('/operator/me/machine', {'machine_id': free}, expected=403)
|
designer.call('/operator/me/machine', {'machine_id': free}, expected=403)
|
||||||
|
|
||||||
# Switched off, a machine gives its automatic orders to another one.
|
# Switching a machine off no longer re-routes the cards: a person
|
||||||
|
# chooses another machine (Dropstar, 2026-11-05).
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=false WHERE id=%s', (textil2, second))
|
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=false WHERE id=%s', (textil2, second))
|
||||||
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'], 'active': False})
|
admin.call(f'/operator/machines/{textil2}', {'name': f'Têxtil B {tag}', 'products': ['textil'], 'active': False})
|
||||||
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
||||||
assert board[second]['machine']['id'] not in (None, textil2)
|
assert board[second]['machine']['id'] == textil2
|
||||||
|
|
||||||
# Disabled, the operator is out at once; deleted, the account is gone.
|
# Disabled, the operator is out at once; deleted, the account is gone.
|
||||||
op_row = users[emails['operador']]
|
op_row = users[emails['operador']]
|
||||||
@@ -483,12 +483,11 @@ def run():
|
|||||||
op.call('/operator/board', expected=401)
|
op.call('/operator/board', expected=401)
|
||||||
admin.call(f"/operator/users/{op_row['id']}/delete", {})
|
admin.call(f"/operator/users/{op_row['id']}/delete", {})
|
||||||
assert emails['operador'] not in {u['email'] for u in admin.call('/operator/users')['users']}
|
assert emails['operador'] not in {u['email'] for u in admin.call('/operator/users')['users']}
|
||||||
# A deleted machine sends its orders back to the automatic choice.
|
# A deleted machine leaves its cards without a machine; a person picks one.
|
||||||
su.call(f'/operator/machines/{uv}/delete', {}, operator=True)
|
su.call(f'/operator/machines/{uv}/delete', {}, operator=True)
|
||||||
machines.remove(uv)
|
machines.remove(uv)
|
||||||
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']}
|
||||||
back = board[str(textil_o)]['machine']
|
assert board[str(uv_o)]['machine'] is None
|
||||||
assert back and back['id'] != uv and not back['chosen']
|
|
||||||
# Rework (D-02 to D-04): Gestão opens it with its cause, an Administrador
|
# Rework (D-02 to D-04): Gestão opens it with its cause, an Administrador
|
||||||
# authorizes it, never their own, and only then it counts in Números.
|
# authorizes it, never their own, and only then it counts in Números.
|
||||||
emails['gestao'] = f'gestao-{tag}@example.test'
|
emails['gestao'] = f'gestao-{tag}@example.test'
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import os
|
import os
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
from urllib.request import urlopen
|
from urllib.request import urlopen
|
||||||
from tests.smoke_test import Client, approved_quote, upload_bytes, item_spec, register
|
from tests.smoke_test import Client, approved_quote, upload_bytes, item_spec, register, final_png_bytes
|
||||||
|
|
||||||
def run():
|
def run():
|
||||||
customer=Client();other=Client();customer.call('/session');other.call('/session')
|
customer=Client();other=Client();customer.call('/session');other.call('/session')
|
||||||
@@ -50,12 +50,21 @@ def run():
|
|||||||
assert other.call('/customer/orders/'+oid)['id']==oid
|
assert other.call('/customer/orders/'+oid)['id']==oid
|
||||||
print('PASS: registration claims only current guest records, cross-session account login, revoked sessions, owner UUID is not a credential')
|
print('PASS: registration claims only current guest records, cross-session account login, revoked sessions, owner UUID is not a credential')
|
||||||
|
|
||||||
|
machine = None
|
||||||
def move(state,version):
|
def move(state,version):
|
||||||
return customer.call('/operator/orders/'+oid+'/move',{'state':state,'version':version,'reason':'Please replace the artwork' if state=='cor' else ''},operator=True)['version']
|
nonlocal machine
|
||||||
|
body={'state':state,'version':version,'reason':'Please replace the artwork' if state=='cor' else ''}
|
||||||
|
if state=='imp':
|
||||||
|
if machine is None:
|
||||||
|
machine=customer.call('/operator/machines',{'name':'Workflow '+uuid4().hex[:6],
|
||||||
|
'products':['textil']},operator=True)['id']
|
||||||
|
body['machine_id']=machine
|
||||||
|
return customer.call('/operator/orders/'+oid+'/move',body,operator=True)['version']
|
||||||
# Arte conferida is the print queue (2026-10-23): it takes approved finals only.
|
# Arte conferida is the print queue (2026-10-23): it takes approved finals only.
|
||||||
version=0
|
version=0
|
||||||
customer.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
customer.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
||||||
final_id=upload_bytes(customer,b'LOCAL FINAL VERSION ONE',order_id=oid)
|
final_one=final_png_bytes('final one')
|
||||||
|
final_id=upload_bytes(customer,final_one,name='LOCAL-FINAL-ONE.png',order_id=oid)
|
||||||
customer.call('/uploads/'+final_id,expected=404)
|
customer.call('/uploads/'+final_id,expected=404)
|
||||||
body={'version':version,'files':[{'item_index':0,'upload_id':final_id}],'note':'Manually checked final'}
|
body={'version':version,'files':[{'item_index':0,'upload_id':final_id}],'note':'Manually checked final'}
|
||||||
customer.call('/operator/orders/'+oid+'/final-files',body,expected=401)
|
customer.call('/operator/orders/'+oid+'/final-files',body,expected=401)
|
||||||
@@ -67,21 +76,21 @@ def run():
|
|||||||
detail=customer.call('/customer/orders/'+oid)
|
detail=customer.call('/customer/orders/'+oid)
|
||||||
final=detail['files'][0]
|
final=detail['files'][0]
|
||||||
link=customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download')
|
link=customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download')
|
||||||
assert urlopen(link['url']).read()==b'LOCAL FINAL VERSION ONE'
|
assert urlopen(link['url']).read()==final_one
|
||||||
guest=Client();guest.call('/session');guest.call('/customer/orders/'+oid+'/files/'+final['id']+'/download',expected=404)
|
guest=Client();guest.call('/session');guest.call('/customer/orders/'+oid+'/files/'+final['id']+'/download',expected=404)
|
||||||
version=move('tra',version)
|
version=move('tra',version)
|
||||||
# The print queue's files come named after their order, straight from storage.
|
# The print queue's files come named after their order, straight from storage.
|
||||||
queued=customer.call('/operator/queue/finals',operator=True)['files']
|
queued=customer.call('/operator/queue/finals',operator=True)['files']
|
||||||
mine=[f for f in queued if urlopen(f['url']).read()==b'LOCAL FINAL VERSION ONE']
|
mine=[f for f in queued if f['order']==oid and urlopen(f['url']).read()==final_one]
|
||||||
assert len(mine)==1 and mine[0]['name'].startswith('DTF-%d-item-1-' % mine[0]['number']), queued
|
assert len(mine)==1 and mine[0]['name'].startswith('DTF-%d-item-1-' % mine[0]['number']), queued
|
||||||
customer.call('/operator/queue/finals',expected=401)
|
customer.call('/operator/queue/finals',expected=401)
|
||||||
version=move('imp',version);version=move('cor',version)
|
version=move('imp',version);version=move('cor',version)
|
||||||
customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download',expected=404)
|
customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download',expected=404)
|
||||||
premature_final=upload_bytes(customer,b'FINAL BEFORE CUSTOMER CORRECTION',order_id=oid)
|
premature_final=upload_bytes(customer,final_png_bytes('premature'),name='LOCAL-PREMATURE-FINAL.png',order_id=oid)
|
||||||
version=customer.call('/operator/orders/'+oid+'/final-files',
|
version=customer.call('/operator/orders/'+oid+'/final-files',
|
||||||
{'version':version,'files':[{'item_index':0,'upload_id':premature_final}],
|
{'version':version,'files':[{'item_index':0,'upload_id':premature_final}],
|
||||||
'note':'Prepared before customer sent the new correction'},operator=True)['version']
|
'note':'Prepared before customer sent the new correction'},operator=True)['version']
|
||||||
correction_id=upload_bytes(customer,b'LOCAL CORRECTED ORIGINAL')
|
correction_id=upload_bytes(customer,final_png_bytes('correction'),name='LOCAL-CORRECTION.png')
|
||||||
payload={'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Replaced the artwork as requested'}
|
payload={'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Replaced the artwork as requested'}
|
||||||
guest.call('/customer/orders/'+oid+'/corrections',payload,expected=404)
|
guest.call('/customer/orders/'+oid+'/corrections',payload,expected=404)
|
||||||
customer.call('/customer/orders/'+oid+'/corrections',{**payload,'version':0},expected=409)
|
customer.call('/customer/orders/'+oid+'/corrections',{**payload,'version':0},expected=409)
|
||||||
@@ -97,7 +106,7 @@ def run():
|
|||||||
# The customer's own correction approved as it is: not treated.
|
# The customer's own correction approved as it is: not treated.
|
||||||
assert treated() is None, treated()
|
assert treated() is None, treated()
|
||||||
customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Twice'},operator=True,expected=409)
|
customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Twice'},operator=True,expected=409)
|
||||||
new_final=upload_bytes(customer,b'LOCAL FINAL VERSION TWO',order_id=oid)
|
new_final=upload_bytes(customer,final_png_bytes('final two'),name='LOCAL-FINAL-TWO.png',order_id=oid)
|
||||||
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':new_final}],'note':'Checked corrected final'},operator=True)['version']
|
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':new_final}],'note':'Checked corrected final'},operator=True)['version']
|
||||||
assert treated()=={'items':[0],'by':operator_email}, treated()
|
assert treated()=={'items':[0],'by':operator_email}, treated()
|
||||||
stats=customer.call('/operator/stats?days=7',operator=True)['treated']
|
stats=customer.call('/operator/stats?days=7',operator=True)['treated']
|
||||||
@@ -128,7 +137,7 @@ def treating():
|
|||||||
approved_quote(customer,q,items)
|
approved_quote(customer,q,items)
|
||||||
order=customer.call('/orders/dev-paid',{'quote_id':q['id']});oid=order['id'];number=order['number']
|
order=customer.call('/orders/dev-paid',{'quote_id':q['id']});oid=order['id'];number=order['number']
|
||||||
files=lambda:[f for f in customer.call('/operator/orders/'+oid+'/files',operator=True) if f['kind']=='final' and f['active']]
|
files=lambda:[f for f in customer.call('/operator/orders/'+oid+'/files',operator=True) if f['kind']=='final' and f['active']]
|
||||||
first=[upload_bytes(customer,b'LOCAL FIRST FINAL %d' % n,order_id=oid) for n in (1,2)]
|
first=[upload_bytes(customer,final_png_bytes(f'first {n}'),name=f'LOCAL-FIRST-FINAL-{n}.png',order_id=oid) for n in (1,2)]
|
||||||
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':0,'note':'Aprovado',
|
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':0,'note':'Aprovado',
|
||||||
'files':[{'item_index':i,'upload_id':u} for i,u in enumerate(first)]},operator=True)['version']
|
'files':[{'item_index':i,'upload_id':u} for i,u in enumerate(first)]},operator=True)['version']
|
||||||
# Where each item is in the stage folder, named as the folders save it.
|
# Where each item is in the stage folder, named as the folders save it.
|
||||||
@@ -137,7 +146,7 @@ def treating():
|
|||||||
assert all(f['name'].startswith('DTF-%d-item-%d' % (number,f['item'])) for f in folder['files']), folder
|
assert all(f['name'].startswith('DTF-%d-item-%d' % (number,f['item'])) for f in folder['files']), folder
|
||||||
customer.call('/operator/orders/'+oid+'/folder-files',expected=401)
|
customer.call('/operator/orders/'+oid+'/folder-files',expected=401)
|
||||||
# Saved over with the same name and sent back: item 1 changes, item 2 keeps its final.
|
# Saved over with the same name and sent back: item 1 changes, item 2 keeps its final.
|
||||||
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
|
png=final_png_bytes('treated')
|
||||||
treated=upload_bytes(customer,png,name='DTF-%d-item-1.png' % number,order_id=oid)
|
treated=upload_bytes(customer,png,name='DTF-%d-item-1.png' % number,order_id=oid)
|
||||||
both=[{'item_index':0,'upload_id':treated},{'item_index':1,'upload_id':first[1]}]
|
both=[{'item_index':0,'upload_id':treated},{'item_index':1,'upload_id':first[1]}]
|
||||||
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':both,'note':'Arte tratada'},operator=True)['version']
|
version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':both,'note':'Arte tratada'},operator=True)['version']
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -136,13 +146,16 @@
|
|||||||
const k=chaveArquivo(file);
|
const k=chaveArquivo(file);
|
||||||
let e=envios.get(k);
|
let e=envios.get(k);
|
||||||
if (!e) {
|
if (!e) {
|
||||||
|
const T=window.dtfTimings;
|
||||||
|
if(T){ if(T.uploadStart==null)T.uploadStart=performance.now();
|
||||||
|
if(!T.uploadSeen.has(k)){T.uploadSeen.add(k);T.uploadBytes+=file.size;} }
|
||||||
e={file, sent:0, done:false, failed:null, stop:new AbortController()};
|
e={file, sent:0, done:false, failed:null, stop:new AbortController()};
|
||||||
e.promise=(async()=>{
|
e.promise=(async()=>{
|
||||||
const session=await ready;
|
const session=await ready;
|
||||||
return window.dtfUpload(file,{api,scope:session.cart_scope,progress:()=>{},signal:e.stop.signal,
|
return window.dtfUpload(file,{api,scope:session.cart_scope,progress:()=>{},signal:e.stop.signal,
|
||||||
onBytes:n=>{e.sent=n;pintaEnvio();}});
|
onBytes:n=>{e.sent=n;pintaEnvio();}});
|
||||||
})();
|
})();
|
||||||
e.promise.then(()=>{e.done=true;falhas.delete(k);pintaEnvio();},
|
e.promise.then(()=>{e.done=true;if(window.dtfTimings)T.uploadEnd=performance.now();falhas.delete(k);pintaEnvio();},
|
||||||
error=>{envios.delete(k);if(error?.name!=='AbortError')falhas.set(k,{file,error});pintaEnvio();});
|
error=>{envios.delete(k);if(error?.name!=='AbortError')falhas.set(k,{file,error});pintaEnvio();});
|
||||||
envios.set(k,e);
|
envios.set(k,e);
|
||||||
}
|
}
|
||||||
@@ -327,7 +340,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 +359,11 @@
|
|||||||
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.proofYFraction!=null?{proof_y_fraction:item.proofYFraction}:{}),
|
||||||
|
...(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.');
|
||||||
@@ -351,13 +373,24 @@
|
|||||||
// "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.
|
||||||
if ($('fProva')?.checked) content.proof = true;
|
if ($('fProva')?.checked) content.proof = true;
|
||||||
if (cartSnapshot()!==initialCart) throw new Error('O carrinho mudou durante o envio. Confira os itens e envie de novo.');
|
if (cartSnapshot()!==initialCart) throw new Error('O carrinho mudou durante o envio. Confira os itens e envie de novo.');
|
||||||
const serialized = JSON.stringify(content);
|
// Browser timings for Números (item 0.12); they never affect the price.
|
||||||
|
const T=window.dtfTimings, timings={};
|
||||||
|
const nav=performance.getEntriesByType?.('navigation')?.[0];
|
||||||
|
const pageMs=nav?.domContentLoadedEventEnd || (T?.pageStart!=null?performance.now()-T.pageStart:0);
|
||||||
|
if(pageMs>0)timings.page_ms=Math.round(pageMs);
|
||||||
|
if(T?.uploadStart!=null&&T.uploadEnd!=null){
|
||||||
|
timings.upload_ms=Math.round(T.uploadEnd-T.uploadStart);
|
||||||
|
timings.upload_bytes=Math.round(T.uploadBytes||0);
|
||||||
|
}
|
||||||
|
if(T?.analysisStart!=null&&T.analysisEnd!=null)timings.analysis_ms=Math.round(T.analysisEnd-T.analysisStart);
|
||||||
|
if(T?.montageStart!=null&&T.montageEnd!=null)timings.montage_ms=Math.round(T.montageEnd-T.montageStart);
|
||||||
|
const serialized = JSON.stringify({...content,timings});
|
||||||
if (!requestKey || serialized !== requestBody) {
|
if (!requestKey || serialized !== requestBody) {
|
||||||
requestKey = crypto.randomUUID(); requestBody = serialized;
|
requestKey = crypto.randomUUID(); requestBody = serialized;
|
||||||
localStorage.setItem('dtf-request-key',requestKey);
|
localStorage.setItem('dtf-request-key',requestKey);
|
||||||
localStorage.setItem('dtf-request-body',requestBody);
|
localStorage.setItem('dtf-request-body',requestBody);
|
||||||
}
|
}
|
||||||
const quote = await api('/quotes',{request_key:requestKey,...content});
|
const quote = await api('/quotes',{request_key:requestKey,...content,timings});
|
||||||
quotedCart=initialCart;localStorage.setItem('dtf-quote-cart',quotedCart);
|
quotedCart=initialCart;localStorage.setItem('dtf-quote-cart',quotedCart);
|
||||||
draftId=quote.id; localStorage.setItem('dtf-quote',draftId);
|
draftId=quote.id; localStorage.setItem('dtf-quote',draftId);
|
||||||
await refresh(true);
|
await refresh(true);
|
||||||
@@ -473,7 +506,8 @@
|
|||||||
const titulo=node('h4','Pagamento confirmado');
|
const titulo=node('h4','Pagamento confirmado');
|
||||||
titulo.insertAdjacentHTML('afterbegin', icone('okCirculo'));
|
titulo.insertAdjacentHTML('afterbegin', icone('okCirculo'));
|
||||||
box.append(titulo,
|
box.append(titulo,
|
||||||
node('p','Recebemos seu pedido e ele já está na produção. Você acompanha cada etapa em Meus pedidos.'));
|
node('p','Recebemos seu pedido e ele já está na produção. Você acompanha cada etapa em Meus pedidos.'),
|
||||||
|
node('p','O Prumo está preparando o arquivo de impressão. Em geral leva até 1 min por 10 m; o card aparece em Meus pedidos quando fica pronto.'));
|
||||||
button('Ver meus pedidos',()=>location.assign('/conta/pedidos?order='+quote.order.id),box);
|
button('Ver meus pedidos',()=>location.assign('/conta/pedidos?order='+quote.order.id),box);
|
||||||
actions.append(box);
|
actions.append(box);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -906,7 +906,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
não deixa pagar</li>
|
não deixa pagar</li>
|
||||||
<li class="n"><b>Pontinho de recorte.</b> A impressora enxerga qualquer
|
<li class="n"><b>Pontinho de recorte.</b> A impressora enxerga qualquer
|
||||||
resíduo e imprime. Não existe pequeno demais: o site mostra onde cada um está
|
resíduo e imprime. Não existe pequeno demais: o site mostra onde cada um está
|
||||||
e só deixa pagar depois que você apagar</li>
|
e pede que você apague ou aceite imprimir assim</li>
|
||||||
<li class="n"><b>Cópias sobrepostas.</b> Duas iguais com 1 mm de diferença
|
<li class="n"><b>Cópias sobrepostas.</b> Duas iguais com 1 mm de diferença
|
||||||
saem duplicadas</li>
|
saem duplicadas</li>
|
||||||
<li class="n"><b>Menos de 96 DPI.</b> Abaixo disso não imprimimos: sai
|
<li class="n"><b>Menos de 96 DPI.</b> Abaixo disso não imprimimos: sai
|
||||||
@@ -929,7 +929,6 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
<div class="compra" id="compra">
|
<div class="compra" id="compra">
|
||||||
<div class="aoVivo" id="aoVivo"></div>
|
<div class="aoVivo" id="aoVivo"></div>
|
||||||
<div id="compraVals" hidden>
|
<div id="compraVals" hidden>
|
||||||
<div class="cLin"><span>Nota da arte</span><b id="cNota">—</b></div>
|
|
||||||
<div class="cLin"><span id="cMetroLbl">Metro</span><b id="cMetro">—</b></div>
|
<div class="cLin"><span id="cMetroLbl">Metro</span><b id="cMetro">—</b></div>
|
||||||
<div class="cLin"><span>Metragem <small>(a cada 10 cm)</small></span><b id="cMetragem">—</b></div>
|
<div class="cLin"><span>Metragem <small>(a cada 10 cm)</small></span><b id="cMetragem">—</b></div>
|
||||||
<p class="cObs" id="cObs"></p>
|
<p class="cObs" id="cObs"></p>
|
||||||
@@ -947,6 +946,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>
|
||||||
@@ -964,10 +970,9 @@ h2 em{font-style:normal;color:var(--laranja)}
|
|||||||
<div class="qh">
|
<div class="qh">
|
||||||
<div><h3 id="qNome">sua folha</h3>
|
<div><h3 id="qNome">sua folha</h3>
|
||||||
<span style="font-size:14.5px;color:var(--fraco)" id="qSub"></span></div>
|
<span style="font-size:14.5px;color:var(--fraco)" id="qSub"></span></div>
|
||||||
<div style="text-align:right"><div class="pct" id="pct">—</div>
|
<div style="display:none"><div class="pct" id="pct">—</div></div>
|
||||||
<span style="font-size:13.5px;color:var(--fraco)">qualidade</span></div>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="qbar"><i id="qbi" style="width:0%"></i></div>
|
<div class="qbar" style="display:none"><i id="qbi" style="width:0%"></i></div>
|
||||||
<div class="qitens" id="qitens"></div>
|
<div class="qitens" id="qitens"></div>
|
||||||
<div class="qbts">
|
<div class="qbts">
|
||||||
<button class="qb chama" id="qOk">Seguir para o pedido</button>
|
<button class="qb chama" id="qOk">Seguir para o pedido</button>
|
||||||
|
|||||||
1
web/kanban-icon.svg
Normal file
1
web/kanban-icon.svg
Normal 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
143
web/kanban-viewer.js
Normal 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};
|
||||||
|
};
|
||||||
|
})();
|
||||||
1632
web/kanban.css
1632
web/kanban.css
File diff suppressed because it is too large
Load Diff
224
web/kanban.html
224
web/kanban.html
@@ -2,143 +2,179 @@
|
|||||||
<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&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&family=IBM+Plex+Mono:wght@400;500&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 class="panel clip"><div class="phead"><h2>Velocidade do site e do Prumo</h2><span class="hint tip-l" tabindex="0" data-tip="Média e p95 do que o cliente sente, por pedido pago no período: abrir a página, subir o arquivo (MB/s), a conferência do Prumo, a montagem das avulsas, a geração do arquivo final por 10 m e o tempo do evento de pagamento até o card. Referências: página < 3 s; conferência < 30 s; geração < 2 min por 10 m; card em até 1 min."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
|
||||||
|
<table class="table"><thead><tr><th scope="col">Etapa</th><th scope="col" class="r">Média</th><th scope="col" class="r">p95</th><th scope="col" class="r">Amostras</th></tr></thead><tbody id="stats-speed"></tbody></table></section>
|
||||||
</section>
|
</section>
|
||||||
<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>
|
||||||
|
|||||||
2945
web/kanban.js
2945
web/kanban.js
File diff suppressed because it is too large
Load Diff
129
web/login-sheet.svg
Normal file
129
web/login-sheet.svg
Normal 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 |
@@ -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;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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,f.layout)}));
|
||||||
|
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'};
|
||||||
pintaPedido();
|
pintaPedido();
|
||||||
previa();
|
previa();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,9 +9,6 @@
|
|||||||
vals.hidden=!it;
|
vals.hidden=!it;
|
||||||
add.disabled=!it || !itemPodeEnviar(it);
|
add.disabled=!it || !itemPodeEnviar(it);
|
||||||
if(!it) return;
|
if(!it) return;
|
||||||
// One price per product (Dropstar, 2026-10-23): the grade is shown to explain
|
|
||||||
// the file, on its own line, and never changes the metre.
|
|
||||||
$('cNota').textContent = it.nota ? it.nota+'/100' : '—';
|
|
||||||
$('cMetroLbl').textContent = it.extra ? 'Metro · com '+rs(it.extra)+' de arquivo manual' : 'Metro';
|
$('cMetroLbl').textContent = it.extra ? 'Metro · com '+rs(it.extra)+' de arquivo manual' : 'Metro';
|
||||||
$('cMetro').textContent=rs(it.unit);
|
$('cMetro').textContent=rs(it.unit);
|
||||||
$('cMetragem').textContent=fmtM(it.cob)+' m';
|
$('cMetragem').textContent=fmtM(it.cob)+' m';
|
||||||
|
|||||||
@@ -4,6 +4,14 @@
|
|||||||
scope and run top to bottom, exactly as the original did. */
|
scope and run top to bottom, exactly as the original did. */
|
||||||
|
|
||||||
const $=id=>document.getElementById(id);
|
const $=id=>document.getElementById(id);
|
||||||
|
// Segundos desde um marco, para as etapas nunca ficarem mudas (item 0.12).
|
||||||
|
const segundosDesde=inicio=>inicio?Math.max(0,Math.round((Date.now()-inicio)/1000)):0;
|
||||||
|
// What the browser measured while the customer built the cart (item 0.12):
|
||||||
|
// page load, upload, Prumo's check and the loose-art montage. It only feeds
|
||||||
|
// Números; no price or acceptance depends on it.
|
||||||
|
window.dtfTimings={pageStart:performance.now(),uploadStart:null,uploadEnd:null,
|
||||||
|
uploadBytes:0,uploadSeen:new Set(),analysisStart:null,analysisEnd:null,
|
||||||
|
montageStart:null,montageEnd:null};
|
||||||
const rs=v=>'R$ '+v.toFixed(2).replace('.',',');
|
const rs=v=>'R$ '+v.toFixed(2).replace('.',',');
|
||||||
// Ícones (Lucide, licença ISC) desenhados no próprio HTML: nada a carregar, e a
|
// Ícones (Lucide, licença ISC) desenhados no próprio HTML: nada a carregar, e a
|
||||||
// cor vem do texto em volta. Os que ficam no HTML estático são os mesmos.
|
// cor vem do texto em volta. Os que ficam no HTML estático são os mesmos.
|
||||||
@@ -67,7 +75,7 @@ const ACEITA={
|
|||||||
avulsa: /[.](png|webp)$/i
|
avulsa: /[.](png|webp)$/i
|
||||||
};
|
};
|
||||||
const MEDE=/[.](png|jpe?g|webp|gif|bmp|pdf)$/i;
|
const MEDE=/[.](png|jpe?g|webp|gif|bmp|pdf)$/i;
|
||||||
const DPI_RECUSA=96, DPI_AVISA=300; // régua dos designers · 02/09/2026
|
const DPI_RECUSA=96, DPI_AVISA=200; // régua aprovada pela Dropstar · 05/11/2026
|
||||||
// A especificação do PDF limita a página a 14.400 unidades — 200 pol, 508 cm.
|
// A especificação do PDF limita a página a 14.400 unidades — 200 pol, 508 cm.
|
||||||
// Passar disso só é válido com UserUnit (PDF 1.6+), que a maioria dos programas
|
// Passar disso só é válido com UserUnit (PDF 1.6+), que a maioria dos programas
|
||||||
// não escreve: o arquivo sai fora do padrão e só o gerador lê direito.
|
// não escreve: o arquivo sai fora do padrão e só o gerador lê direito.
|
||||||
@@ -85,6 +93,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 +164,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;
|
||||||
|
|||||||
@@ -393,7 +393,7 @@ function previaAoVivo(){
|
|||||||
if(!x.previewSrc){
|
if(!x.previewSrc){
|
||||||
const esqueleto=document.createElement('div'); esqueleto.className='skel folhaSkel';
|
const esqueleto=document.createElement('div'); esqueleto.className='skel folhaSkel';
|
||||||
esqueleto.style.aspectRatio=x.med ? x.med.larg+' / '+Math.min(x.med.alt,x.med.larg*4) : '1 / 2';
|
esqueleto.style.aspectRatio=x.med ? x.med.larg+' / '+Math.min(x.med.alt,x.med.larg*4) : '1 / 2';
|
||||||
esqueleto.append(Object.assign(document.createElement('span'),{textContent:'Gerando a prévia da folha…'}));
|
esqueleto.append(Object.assign(document.createElement('span'),{textContent:'Gerando a prévia da folha… · '+segundosDesde(x.analiseInicio)+' s'}));
|
||||||
figura.append(esqueleto,legenda); painel.append(figura); return;
|
figura.append(esqueleto,legenda); painel.append(figura); return;
|
||||||
}
|
}
|
||||||
const pilha=document.createElement('div'); pilha.className='folhaPilha';
|
const pilha=document.createElement('div'); pilha.className='folhaPilha';
|
||||||
@@ -426,6 +426,9 @@ function previaAoVivo(){
|
|||||||
const prontas=artes.filter(a=>a.cm>0 && a.cm<=larguraFilme() && (a.src||a.semPrevia));
|
const 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()){
|
||||||
@@ -453,11 +493,13 @@ function motivoNota(){
|
|||||||
: 'nota '+nota+' · a resolução é o único ponto — o resto corrigimos por você';
|
: 'nota '+nota+' · a resolução é o único ponto — o resto corrigimos por você';
|
||||||
}
|
}
|
||||||
function previa(){
|
function previa(){
|
||||||
|
const T=window.dtfTimings;
|
||||||
|
if(T && T.montageStart!=null && T.montageEnd==null) T.montageEnd=performance.now();
|
||||||
// Na folha pronta o painel não tem o que mostrar: a folha vem fechada, ninguém
|
// Na folha pronta o painel não tem o que mostrar: a folha vem fechada, ninguém
|
||||||
// olhou dentro dela. Largura e metragem — o que de fato medimos — já aparecem
|
// 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=[
|
||||||
@@ -465,7 +507,6 @@ function previa(){
|
|||||||
['var(--verde)','✓','Espaço entre artes', montagemFolgaCm>=MARGEM_CM-1e-9
|
['var(--verde)','✓','Espaço entre artes', montagemFolgaCm>=MARGEM_CM-1e-9
|
||||||
? '5 mm entre as artes e nas bordas'
|
? '5 mm entre as artes e nas bordas'
|
||||||
: n1(montagemFolgaCm*10)+' mm · 5 mm não cabem na largura, a sobra fica dividida por igual'],
|
: n1(montagemFolgaCm*10)+' mm · 5 mm não cabem na largura, a sobra fica dividida por igual'],
|
||||||
[nota>=75?'var(--verde)':'var(--laranja)', nota>=75?'✓':'!','Qualidade da folha',motivoNota()],
|
|
||||||
['var(--verde)','✓','Metragem proporcional',
|
['var(--verde)','✓','Metragem proporcional',
|
||||||
'sua folha tem '+fmtM(metros)+' m e você paga '+fmtM(cob)+
|
'sua folha tem '+fmtM(metros)+' m e você paga '+fmtM(cob)+
|
||||||
' m · arredondamos só até os 10 cm mais próximos'],
|
' m · arredondamos só até os 10 cm mais próximos'],
|
||||||
|
|||||||
@@ -333,6 +333,16 @@ async function fontePdf(lib, file){
|
|||||||
function medirFolha(file){
|
function medirFolha(file){
|
||||||
return new Promise(res=>{
|
return new Promise(res=>{
|
||||||
const nome=(file.name||'').toLowerCase();
|
const nome=(file.name||'').toLowerCase();
|
||||||
|
if(/\.png$/.test(nome)){
|
||||||
|
dimensoesImagem(file).then(d=>{
|
||||||
|
if(!d || !(d.w>0) || !(d.h>0)) return res({rejected:true,reason:'Não foi possível ler as dimensões do PNG. Exporte novamente.'});
|
||||||
|
const L=larguraFilme(), measure={larg:L,alt:+(d.h/d.w*L).toFixed(1),
|
||||||
|
fonte:'dimensões do arquivo',dpiFolha:Math.round(d.w/(L/2.54)),px:d.w};
|
||||||
|
if(d.h>32767 || file.size>GRANDE_BYTES) return res({...measure,grande:true,tall:d.h>32767});
|
||||||
|
carregarImagem(file).then(img=>res(img&&img.width?{...measure,fonte:'proporção da imagem'}:null));
|
||||||
|
}).catch(()=>res({rejected:true,reason:'Não foi possível ler o PNG. Exporte novamente.'}));
|
||||||
|
return;
|
||||||
|
}
|
||||||
if(RENDERIZA.test(nome) && file.size>GRANDE_BYTES){
|
if(RENDERIZA.test(nome) && file.size>GRANDE_BYTES){
|
||||||
dimensoesImagem(file).then(d=>{
|
dimensoesImagem(file).then(d=>{
|
||||||
if(!d || !(d.w>0) || !(d.h>0)) return res(null);
|
if(!d || !(d.w>0) || !(d.h>0)) return res(null);
|
||||||
@@ -396,8 +406,9 @@ function medirFolha(file){
|
|||||||
}
|
}
|
||||||
|
|
||||||
function textoProgresso(x){
|
function textoProgresso(x){
|
||||||
if(x.med && x.med.grande) return 'gerando a prévia e conferindo a arte · '+faltaLeitura(x.leitura);
|
const tempo=x.analiseInicio?' · '+segundosDesde(x.analiseInicio)+' s':'';
|
||||||
return x.pct<50?'lendo o arquivo…':x.pct<70?'medindo a folha…':'conferindo a arte…';
|
if(x.med && x.med.grande) return 'gerando a prévia e conferindo a arte · '+faltaLeitura(x.leitura)+tempo;
|
||||||
|
return (x.pct<50?'lendo o arquivo…':x.pct<70?'medindo a folha…':'conferindo a arte…')+tempo;
|
||||||
}
|
}
|
||||||
// The file card's thumbnail (52 x 96 px, drawn at twice that for sharp screens).
|
// The file card's thumbnail (52 x 96 px, drawn at twice that for sharp screens).
|
||||||
// At 480 x 720 it is the picture the Kanban shows of the order (checkout.js).
|
// At 480 x 720 it is the picture the Kanban shows of the order (checkout.js).
|
||||||
@@ -453,9 +464,8 @@ function chipsDaFolha(a,aceito){
|
|||||||
}
|
}
|
||||||
// Resíduo e fundo chapado barram o pedido (Dropstar, 21/10/2026): o texto diz
|
// 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 em ambos os caminhos.
|
||||||
// e fica só o aceite.
|
function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
|
||||||
function avisosDaFolha(a,nome,i,aceito){
|
|
||||||
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 '+
|
||||||
@@ -465,14 +475,13 @@ function avisosDaFolha(a,nome,i,aceito){
|
|||||||
if(!a.residuos) return '';
|
if(!a.residuos) return '';
|
||||||
const n=a.residuos, varios=n>1;
|
const n=a.residuos, varios=n>1;
|
||||||
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>Esses pontos fazem parte da arte. Li e concordo em imprimir assim — eles podem sair no recorte.</span></label>';
|
||||||
'imprimir assim — '+(varios?'eles podem':'ele pode')+' se perder no recorte.</span></label>';
|
if(aceitavel && aceito) return aceite;
|
||||||
if(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
|
||||||
@@ -504,7 +513,7 @@ function pintaFolha(){
|
|||||||
if(lido){
|
if(lido){
|
||||||
medida='<div class="repMed"><b>'+n1(x.med.larg)+' × '+n1(x.med.alt)+' cm</b>'+
|
medida='<div class="repMed"><b>'+n1(x.med.larg)+' × '+n1(x.med.alt)+' cm</b>'+
|
||||||
'<span>'+escapeHTML(extDe(x.f.name))+' · '+fmt(x.f.size)+'</span></div>'+
|
'<span>'+escapeHTML(extDe(x.f.name))+' · '+fmt(x.f.size)+'</span></div>'+
|
||||||
(a? '<ul class="chips">'+chipsDaFolha(a,residuoAceito(x))+'</ul>'+avisosDaFolha(a,x.f.name,i,residuoAceito(x))+
|
(a? '<ul class="chips">'+chipsDaFolha(a,residuoAceito(x))+'</ul>'+avisosDaFolha(a,x.f.name,i,residuoAceito(x),true)+
|
||||||
detalhesDaFolha(a,i,x.detAberto) : '')+
|
detalhesDaFolha(a,i,x.detAberto) : '')+
|
||||||
// Over 150 MB the browser cannot check a PDF: said before payment, as
|
// Over 150 MB the browser cannot check a PDF: said before payment, as
|
||||||
// for a file opened by hand (Dropstar, 2026-10-23).
|
// for a file opened by hand (Dropstar, 2026-10-23).
|
||||||
@@ -664,6 +673,10 @@ function pintaArtes(){
|
|||||||
n1(sug.cm)+' cm.<button data-usar="'+i+'" data-cm="'+sug.alvo+'">Usar '+n1(sug.alvo)+' cm</button></div>'
|
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 +713,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,16 +743,12 @@ 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 notas=prontas.map(a=>Math.max(6,Math.min(100,Math.round(dpiDe(a)/300*100))));
|
const cob=montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(m);
|
||||||
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;
|
||||||
r.style.display='block'; r.className='resumoA on';
|
r.style.display='block'; r.className='resumoA on';
|
||||||
r.innerHTML='<div class="r"><span>artes com tamanho</span><b>'+prontas.length+' de '+artes.length+'</b></div>'+
|
r.innerHTML='<div class="r"><span>artes com tamanho</span><b>'+prontas.length+' de '+artes.length+'</b></div>'+
|
||||||
'<div class="r"><span>qualidade média</span><b style="color:'+
|
(m>0?'<div class="r"><span>'+(montagemFolhas?montagemFolhas.length+' folhas montadas':'folha montada')+'</span><b>'+fmtM(m)+' m</b></div>'+
|
||||||
(media>=85?'var(--verde)':media>=50?'var(--laranja)':'var(--vermelho)')+'">'+media+'%</b></div>'+
|
(cob>m+0.001?'<div class="r"><span>cobrança</span><b>'+fmtM(cob)+
|
||||||
(pior<media?'<div class="r"><span>a pior arte</span><b>'+pior+'%</b></div>':'')+
|
' m'+(cob===MINIMO_M?' · mínimo':'')+'</b></div>':''):'')+
|
||||||
(m>0?'<div class="r"><span>folha montada</span><b>'+fmtM(m)+' m</b></div>'+
|
|
||||||
(cobrar(m)>m+0.001?'<div class="r"><span>cobrança</span><b>'+fmtM(cobrar(m))+
|
|
||||||
' m'+(cobrar(m)===MINIMO_M?' · mínimo':'')+'</b></div>':''):'')+
|
|
||||||
(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>':'');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,13 +7,79 @@
|
|||||||
// 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);
|
const residuoAceito=x=>!!x.residuoAceito;
|
||||||
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;
|
||||||
|
$('mistaTit').textContent=x.f.name;
|
||||||
|
$('mistaTxt').textContent=ehFolha()?TEXTO_MISTA.folha:TEXTO_MISTA.arte;
|
||||||
|
$('mistaSep').onclick=()=>{ dlg.close(); const i=lista.indexOf(x);
|
||||||
|
if(i>=0){ lista.splice(i,1); ehFolha()?pintaFolha():pintaArtes(); } $('inp').click(); };
|
||||||
|
$('mistaSegue').onclick=()=>{ x.mistaVista=true; dlg.close(); agendaAvaliacao(); };
|
||||||
|
dlg.showModal();
|
||||||
|
}
|
||||||
|
// O traço mais fino do item (item 9, Dropstar 30/10/2026): o menor entre as
|
||||||
|
// folhas que o navegador mediu. Não aparece para o cliente; vai para a sala,
|
||||||
|
// que confere a classe de contração ao aprovar o arquivo final.
|
||||||
|
// Onde o traço mais fino cai no filme montado (0 no topo, 1 no fim): a prova
|
||||||
|
// de 15 cm é recortada em volta dele, não no começo da folha (item 0.1).
|
||||||
|
function fracaoNoFilme(layout,sourceIndex,fraction){
|
||||||
|
if(!layout || !(layout.height_cm>0)) return fraction||0;
|
||||||
|
const placement=(layout.placements||[]).find(p=>p.source_index===sourceIndex);
|
||||||
|
if(!placement) return fraction||0;
|
||||||
|
const y=placement.rotation_degrees%180===90
|
||||||
|
? placement.y_cm+placement.length_cm/2
|
||||||
|
: placement.y_cm+(fraction||0)*placement.length_cm;
|
||||||
|
return Math.max(0,Math.min(1,y/layout.height_cm));
|
||||||
|
}
|
||||||
|
function tracoDoItem(lista,layout){
|
||||||
|
const arquivos=lista||(ehFolha()?folhas:artes);
|
||||||
|
const medidas=arquivos.map((x,index)=>({index,traco:lista?tracoDaArte(x):tracoDoArquivo(x)})).filter(x=>x.traco);
|
||||||
|
if(!medidas.length) return {strokePx:null, strokeClass:null, strokeChoice:null};
|
||||||
|
const fino=medidas.reduce((a,b)=>b.traco.px<a.traco.px?b:a);
|
||||||
|
// Avisado do item 16, o cliente quis imprimir assim: fica a medida, C1.
|
||||||
|
const avisado=arquivos.some(x=>x.mistaVista && mista(lista?tracoDaArte(x):tracoDoArquivo(x)));
|
||||||
|
return {strokePx:fino.traco.px, strokeClass:fino.traco.classe, strokeChoice:avisado?'measured':null,
|
||||||
|
proofSourceIndex:fino.index,
|
||||||
|
proofYFraction:fracaoNoFilme(lista?layout:montagemLayout,fino.index,fino.traco.proofYFraction||0)};
|
||||||
|
}
|
||||||
|
// Fecha a medida da conferência quando não há mais arquivo sendo lido (0.12).
|
||||||
|
function marcaTempos(){
|
||||||
|
const T=window.dtfTimings;
|
||||||
|
if(!T || T.analysisStart==null || T.analysisEnd!=null) return;
|
||||||
|
if(!(folhas.length+artes.length)) return;
|
||||||
|
if(folhas.some(x=>x.pct!=null) || artes.some(a=>a.lendoArte)) return;
|
||||||
|
T.analysisEnd=performance.now();
|
||||||
|
}
|
||||||
// Avalia sozinho conforme o cliente sobe e preenche. Devolve o que ainda falta,
|
// 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(){
|
||||||
|
marcaTempos();
|
||||||
if(ehFolha()){
|
if(ehFolha()){
|
||||||
if(!folhas.length) return {pronto:false, falta:'Arraste sua folha montada para começar.'};
|
if(!folhas.length) return {pronto:false, falta:'Arraste sua folha montada para começar.'};
|
||||||
const pdfInvalido=folhas.find(x=>x.measurementError);
|
const pdfInvalido=folhas.find(x=>x.measurementError);
|
||||||
@@ -27,13 +93,14 @@ function avaliar(){
|
|||||||
// Resíduo e fundo chapado barram antes do pagamento, com um ponto só
|
// Resíduo e fundo chapado barram antes do pagamento, com um ponto só
|
||||||
// (Dropstar, 21/10/2026): então o pedido espera a conferência terminar.
|
// (Dropstar, 21/10/2026): então o pedido espera a conferência terminar.
|
||||||
const lendo=folhas.find(x=>x.pct!=null);
|
const lendo=folhas.find(x=>x.pct!=null);
|
||||||
if(lendo) return {pronto:false, falta:'Conferindo '+lendo.f.name+'…'};
|
if(lendo) return {pronto:false, falta:'Conferindo '+lendo.f.name+'… · '+segundosDesde(lendo.analiseInicio)+' s'};
|
||||||
const barrada=folhas.find(folhaBarrada);
|
const barrada=folhas.find(folhaBarrada);
|
||||||
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, ou marque que aceita imprimir assim.'};
|
||||||
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){
|
||||||
@@ -78,7 +145,8 @@ function avaliar(){
|
|||||||
return {pronto:true};
|
return {pronto:true};
|
||||||
}
|
}
|
||||||
if(!artes.length) return {pronto:false, falta:'Arraste suas artes para começar.'};
|
if(!artes.length) return {pronto:false, falta:'Arraste suas artes para começar.'};
|
||||||
if(artes.some(a=>a.lendo!=null)) return {pronto:false, falta:'Gerando a prévia das artes grandes…'};
|
const grande=artes.find(a=>a.lendo!=null);
|
||||||
|
if(grande) return {pronto:false, falta:'Gerando a prévia das artes grandes… · '+segundosDesde(grande.analiseInicio)+' s'};
|
||||||
if(artes.some(a=>a.decodeError || !(a.src||a.semPrevia) || !(a.px>0) || !(a.py>0)))
|
if(artes.some(a=>a.decodeError || !(a.src||a.semPrevia) || !(a.px>0) || !(a.py>0)))
|
||||||
return {pronto:false, falta:'Não conseguimos ler uma das imagens. Exporte-a novamente em PNG antes de continuar.'};
|
return {pronto:false, falta:'Não conseguimos ler uma das imagens. Exporte-a novamente em PNG antes de continuar.'};
|
||||||
if(artes.some(a=>!Number.isFinite(a.cm) || a.cm>larguraFilme()))
|
if(artes.some(a=>!Number.isFinite(a.cm) || a.cm>larguraFilme()))
|
||||||
@@ -87,10 +155,19 @@ 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.
|
||||||
|
const lendoArte=artes.find(a=>a.lendoArte);
|
||||||
|
if(lendoArte) return {pronto:false, falta:'Conferindo as artes… · '+segundosDesde(lendoArte.analiseInicio)+' s'};
|
||||||
|
const comPontos=artes.find(a=>{const an=analiseDaArte(a);return an&&an.residuos&&!a.residuoAceito;});
|
||||||
|
if(comPontos){const n=analiseDaArte(comPontos).residuos;
|
||||||
|
return {pronto:false, falta:comPontos.f.name+' tem '+n+' ponto'+(n>1?'s':'')+
|
||||||
|
' de recorte. Apague e envie de novo, ou marque que aceita imprimir assim.'};}
|
||||||
|
setTimeout(perguntaMista);
|
||||||
// metragem = altura da folha depois de montada, com os 5 mm entre peças
|
// 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…'};
|
||||||
const notas=artes.map(a=>Math.max(6,Math.min(100,Math.round(dpiDe(a)/300*100))));
|
const notas=artes.map(a=>Math.max(6,Math.min(100,Math.round(dpiDe(a)/DPI_AVISA*100))));
|
||||||
const media=Math.round(notas.reduce((s,n)=>s+n,0)/notas.length), pior=Math.min(...notas);
|
const media=Math.round(notas.reduce((s,n)=>s+n,0)/notas.length), pior=Math.min(...notas);
|
||||||
mostraNota([
|
mostraNota([
|
||||||
['ok','Montagem por nossa conta','5 mm garantidos'],
|
['ok','Montagem por nossa conta','5 mm garantidos'],
|
||||||
@@ -156,7 +233,7 @@ function ressalvaResolucao(){
|
|||||||
quantas:r.quantasBaixas, parte:Math.round(r.fracBaixa*100),
|
quantas:r.quantasBaixas, parte:Math.round(r.fracBaixa*100),
|
||||||
quantasAviso:r.quantasAviso, parteAviso:Math.round(r.fracAviso*100)} : {};
|
quantasAviso:r.quantasAviso, parteAviso:Math.round(r.fracAviso*100)} : {};
|
||||||
if(x.an.dpi<DPI_RECUSA) recusadas.push(Object.assign({nome, dpi:x.an.dpi, cm}, extra));
|
if(x.an.dpi<DPI_RECUSA) recusadas.push(Object.assign({nome, dpi:x.an.dpi, cm}, extra));
|
||||||
else if(x.an.dpi<DPI_AVISA || (r&&r.quantasAviso))
|
else if(x.an.dpi<DPI_AVISA)
|
||||||
baixas.push(Object.assign({nome, dpi:x.an.dpi, cm}, extra));
|
baixas.push(Object.assign({nome, dpi:x.an.dpi, cm}, extra));
|
||||||
});
|
});
|
||||||
geral = folhas.some(x=>x.an) ? Math.max(...folhas.filter(x=>x.an).map(x=>x.an.dpi)) : 300;
|
geral = folhas.some(x=>x.an) ? Math.max(...folhas.filter(x=>x.an).map(x=>x.an.dpi)) : 300;
|
||||||
|
|||||||
@@ -60,10 +60,182 @@ 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),hPx)};
|
||||||
|
}
|
||||||
|
// ── 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,hPx){
|
||||||
|
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,
|
||||||
|
hPx,windowRows:Math.max(1,Math.round(dpi/2.54*15)),windows:[]};
|
||||||
|
}
|
||||||
|
// 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){
|
||||||
|
const wi=Math.floor((t.inicio+y)/t.windowRows), wh=t.windows[wi]||(t.windows[wi]=new Float64Array(hist.length));
|
||||||
|
hist[max]+=0.5;wh[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)));
|
||||||
|
const wi=Math.floor((t.inicio+y)/t.windowRows), wh=t.windows[wi]||(t.windows[wi]=new Float64Array(hist.length));
|
||||||
|
hist[i]++;wh[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; } }
|
||||||
|
// Choose the 15 cm stretch with the finest 1st-percentile stroke.
|
||||||
|
let best=0, bestPx=Infinity;
|
||||||
|
t.windows.forEach((histogram,index)=>{
|
||||||
|
if(!histogram)return;
|
||||||
|
const count=histogram.reduce((a,b)=>a+b,0);
|
||||||
|
if(count<20)return;
|
||||||
|
let seen=0, width=histogram.length-1;
|
||||||
|
for(let i=1;i<histogram.length;i++){seen+=histogram[i];if(seen>=count*0.01){width=i;break;}}
|
||||||
|
if(width<bestPx){bestPx=width;best=index;}
|
||||||
|
});
|
||||||
|
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,
|
||||||
|
proofYFraction:Math.min(1,best*t.windowRows/t.hPx)};
|
||||||
}
|
}
|
||||||
// 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 +316,7 @@ 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
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -100,6 +100,10 @@ async function marcaResiduos(x){
|
|||||||
}
|
}
|
||||||
async function sel(fs){
|
async function sel(fs){
|
||||||
if(!fs.length) return;
|
if(!fs.length) return;
|
||||||
|
const T=window.dtfTimings;
|
||||||
|
if(T){const now=performance.now();
|
||||||
|
if(T.montageStart==null)T.montageStart=now;
|
||||||
|
if(T.analysisStart==null)T.analysisStart=now;}
|
||||||
fs=await Promise.all(fs.map(nomeReal));
|
fs=await Promise.all(fs.map(nomeReal));
|
||||||
// Pixels cannot tell a loose artwork from a finished sheet, so the customer
|
// Pixels cannot tell a loose artwork from a finished sheet, so the customer
|
||||||
// declares it by choosing the product in the selector above. The declaration is
|
// declares it by choosing the product in the selector above. The declaration is
|
||||||
@@ -121,7 +125,7 @@ async function sel(fs){
|
|||||||
// On their way at once; a JPG is refused at the order anyway.
|
// On their way at once; a JPG is refused at the order anyway.
|
||||||
fs.filter(f=>!/\.jpe?g$/i.test(f.name)).forEach(f=>window.dtfEnvio?.enviar(f));
|
fs.filter(f=>!/\.jpe?g$/i.test(f.name)).forEach(f=>window.dtfEnvio?.enviar(f));
|
||||||
if(ehFolha()){
|
if(ehFolha()){
|
||||||
const novas=fs.map(f=>({f, med:null, rep:1, m:0, semAnalise:null}));
|
const novas=fs.map(f=>({f, med:null, rep:1, m:0, semAnalise:null, analiseInicio:Date.now()}));
|
||||||
folhas=folhas.concat(novas); // soma, não substitui
|
folhas=folhas.concat(novas); // soma, não substitui
|
||||||
pintaFolha();
|
pintaFolha();
|
||||||
novas.forEach(x=>{
|
novas.forEach(x=>{
|
||||||
@@ -147,15 +151,27 @@ async function sel(fs){
|
|||||||
x.leitura.p=p;
|
x.leitura.p=p;
|
||||||
if(pct-mostrado>=1){ mostrado=pct; x.pct=pct; pintaProgressoFolha(x); }
|
if(pct-mostrado>=1){ mostrado=pct; x.pct=pct; pintaProgressoFolha(x); }
|
||||||
}, md.larg).then(lido=>{
|
}, md.larg).then(lido=>{
|
||||||
|
if(!lido && md.tall){
|
||||||
|
x.an=null;
|
||||||
|
x.measurementError='Não foi possível conferir este PNG alto. Divida a folha em partes menores antes de pagar.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
if(lido && folhas.includes(x)){
|
if(lido && folhas.includes(x)){
|
||||||
const cv=lido.cv;
|
const cv=lido.cv;
|
||||||
x.previewSrc=cv.toDataURL('image/webp',0.85); x.miniSrc=miniatura(cv); x.fotoSrc=miniatura(cv,480,720);
|
x.previewSrc=cv.toDataURL('image/webp',0.85); x.miniSrc=miniatura(cv); x.fotoSrc=miniatura(cv,480,720);
|
||||||
try{
|
try{
|
||||||
const an=analisarMapa(lido.mapa);
|
const an=analisarMapa(lido.mapa);
|
||||||
x.an={...an, dpi:md.dpiFolha, fonteDpi:'arquivo', grande:false};
|
x.an={...an, dpi:md.dpiFolha, fonteDpi:'arquivo', grande:false};
|
||||||
}catch(e){}
|
}catch(e){
|
||||||
|
if(md.tall){x.an=null;x.measurementError='Não foi possível conferir este PNG alto. Divida a folha em partes menores antes de pagar.';}
|
||||||
}
|
}
|
||||||
}).catch(()=>{}).finally(()=>{ x.pct=null; pintaFolha(); marcaResiduos(x); });
|
}
|
||||||
|
}).catch(()=>{
|
||||||
|
if(md.tall){
|
||||||
|
x.an=null;
|
||||||
|
x.measurementError='Não foi possível conferir este PNG alto. Divida a folha em partes menores antes de pagar.';
|
||||||
|
}
|
||||||
|
}).finally(()=>{ x.pct=null; pintaFolha(); marcaResiduos(x); });
|
||||||
}else if(md && RENDERIZA.test(x.f.name)){
|
}else if(md && RENDERIZA.test(x.f.name)){
|
||||||
carregarImagem(x.f).then(async img=>{
|
carregarImagem(x.f).then(async img=>{
|
||||||
if(img){
|
if(img){
|
||||||
@@ -203,7 +219,7 @@ async function sel(fs){
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const novos=fs.map(f=>({f,px:0,py:0,cm:0,q:1,prop:1,giro:0,esp:false}));
|
const novos=fs.map(f=>({f,px:0,py:0,cm:0,q:1,prop:1,giro:0,esp:false,analiseInicio:Date.now()}));
|
||||||
artes=novos.concat(artes); // a mais recente fica no topo da fila
|
artes=novos.concat(artes); // a mais recente fica no topo da fila
|
||||||
recemChegada=novos[0];
|
recemChegada=novos[0];
|
||||||
pintaArtes();
|
pintaArtes();
|
||||||
@@ -222,23 +238,54 @@ 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,
|
||||||
|
proofYFraction:a.tracoPx.proofYFraction};
|
||||||
|
}
|
||||||
// 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
|
||||||
|
|||||||
@@ -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
17
web/theme.js
Normal 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(); },
|
||||||
|
};
|
||||||
|
})();
|
||||||
Reference in New Issue
Block a user