Compare commits
11 Commits
94f1bfa733
...
c291f00e96
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c291f00e96 | ||
|
|
b97b895993 | ||
|
|
f78cb93ba7 | ||
|
|
3d1293a3af | ||
|
|
2bcdb060fd | ||
|
|
6351a094f4 | ||
|
|
945c9e366a | ||
|
|
054a642a61 | ||
|
|
392e7da85b | ||
|
|
d69e326125 | ||
|
|
0fc01315c7 |
@@ -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)
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ 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 Contraction, 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, hotfolder, 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,
|
||||||
@@ -105,15 +105,16 @@ 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()
|
||||||
# A proof card that got its answer is done with (app/proof.py).
|
# A proof card that got its answer is done with (app/proof.py).
|
||||||
finished = c.execute("""SELECT * FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL
|
finished = c.execute('''SELECT * FROM (
|
||||||
ORDER BY created_at DESC LIMIT %s""", (BOARD_FINISHED_LIMIT,)).fetchall()
|
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']
|
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
|
||||||
@@ -129,7 +130,7 @@ 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.
|
||||||
@@ -192,16 +193,20 @@ TREATED = """f.kind='final'
|
|||||||
|
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
|
|
||||||
@@ -209,9 +214,11 @@ 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).
|
# 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
|
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()
|
JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE p.order_id=ANY(%s) ORDER BY p.part''', (ids,)).fetchall()
|
||||||
@@ -278,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' AND parent_id IS NULL
|
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)}
|
||||||
@@ -681,23 +691,34 @@ 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}
|
||||||
|
|
||||||
@@ -708,10 +729,11 @@ def choose_contraction(uid: UUID, body: Contraction, user=Depends(can('produce')
|
|||||||
measure comes prefilled, and whoever prepares the art may change it until
|
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."""
|
the order prints. Both stay: the measure in the snapshot, the choice here."""
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
row = c.execute('SELECT snapshot,state,cancelled_at,contraction FROM dtf_local.orders WHERE id=%s FOR UPDATE',
|
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()
|
(uid,)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, 'Pedido não encontrado.')
|
raise HTTPException(404, 'Pedido não encontrado.')
|
||||||
|
proof.require_unlocked(c, row)
|
||||||
if body.item_index >= len(row['snapshot']['items']):
|
if body.item_index >= len(row['snapshot']['items']):
|
||||||
raise HTTPException(422, 'Item não encontrado no pedido.')
|
raise HTTPException(422, 'Item não encontrado no pedido.')
|
||||||
# Printing, the class still changes while the item's files wait to go
|
# Printing, the class still changes while the item's files wait to go
|
||||||
@@ -799,9 +821,16 @@ def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
|
|||||||
# Back to Arte recebida with the reason; its final is approved again.
|
# 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.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,
|
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'],))
|
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)
|
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))
|
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)
|
audit('order_proof_answered', order=parent['number'], result=body.result, operator=user)
|
||||||
return {'ok': True}
|
return {'ok': True}
|
||||||
|
|
||||||
@@ -819,7 +848,6 @@ def new_proof_card(uid: UUID, user=Depends(can('produce'))):
|
|||||||
child = proof.create_child(c, row)
|
child = proof.create_child(c, row)
|
||||||
if not child:
|
if not child:
|
||||||
raise HTTPException(409, 'Este pedido não leva prova.')
|
raise HTTPException(409, 'Este pedido não leva prova.')
|
||||||
machines.route(c)
|
|
||||||
audit('order_proof_card', order=row['number'], operator=user)
|
audit('order_proof_card', order=row['number'], operator=user)
|
||||||
return {'ok': True, 'id': child['id'], 'number': child['number']}
|
return {'ok': True, 'id': child['id'], 'number': child['number']}
|
||||||
|
|
||||||
@@ -956,9 +984,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']
|
||||||
@@ -996,6 +1025,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
|
||||||
@@ -1008,9 +1038,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'
|
||||||
@@ -1019,29 +1048,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.')
|
||||||
# Dropped on a machine's lane in Imprimindo: that machine, when it
|
if pulling:
|
||||||
# prints the product. The operator's pull stays their machine's.
|
chosen = body.machine_id or (UUID(session_machine['id']) if session_machine else row['machine_id'])
|
||||||
if pulling and body.machine_id:
|
if not chosen:
|
||||||
if account['role'] == 'operador':
|
raise HTTPException(409, 'Escolha a máquina que está puxando este card.')
|
||||||
if str(body.machine_id) != session_machine['id']:
|
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.")
|
raise HTTPException(409, f"Você está na {session_machine['name']}: o que você puxa vai para ela.")
|
||||||
else:
|
target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (chosen,)).fetchone()
|
||||||
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']:
|
if not target or not target['active']:
|
||||||
raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.')
|
raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.')
|
||||||
if machines.product_family(row) not in target['products']:
|
if machines.product_family(row) not in target['products']:
|
||||||
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
|
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
|
||||||
row['machine_id'] = body.machine_id
|
linked = c.execute('''SELECT machine_id FROM dtf_local.orders WHERE parent_id=%s
|
||||||
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=true WHERE id=%s', (body.machine_id, uid))
|
AND proof_result='ok' AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone()
|
||||||
if pulling and session_machine and not body.machine_id and (account['role'] == 'operador' or not row['machine_chosen']):
|
if linked and linked['machine_id'] and chosen != linked['machine_id']:
|
||||||
prints = c.execute('SELECT products FROM dtf_local.machines WHERE id=%s', (session_machine['id'],)).fetchone()
|
raise HTTPException(409, 'Puxe o pedido na mesma máquina que imprimiu a prova.')
|
||||||
if machines.product_family(row) in (prints or {}).get('products', []):
|
row['machine_id'] = chosen
|
||||||
row['machine_id'] = session_machine['id']
|
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s', (chosen, uid))
|
||||||
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=true WHERE id=%s',
|
if row['parent_id']:
|
||||||
(session_machine['id'], uid))
|
c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s',
|
||||||
elif account['role'] == 'operador':
|
(chosen, row['parent_id']))
|
||||||
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
|
||||||
@@ -1077,9 +1103,10 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
|
|||||||
hotfolder.start(c, uid)
|
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'}
|
||||||
@@ -1104,9 +1131,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():
|
||||||
@@ -1328,6 +1356,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)
|
||||||
@@ -1349,9 +1421,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."""
|
||||||
@@ -1634,7 +1729,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:
|
||||||
@@ -1642,4 +1737,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',
|
||||||
|
|||||||
@@ -231,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)}
|
||||||
|
|
||||||
@@ -248,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
|
||||||
|
|
||||||
|
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -190,6 +190,9 @@ class Item(StrictModel):
|
|||||||
# A sheet with fine lines and solid areas (item 16): the customer kept the
|
# 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).
|
# measure (protect the fine lines) or chose to protect the solid areas (C3).
|
||||||
stroke_choice: Literal['measured', 'client_c3'] | None = None
|
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
|
split: Split | None = None
|
||||||
|
|
||||||
@model_validator(mode='after')
|
@model_validator(mode='after')
|
||||||
@@ -237,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
|
||||||
@@ -245,6 +261,8 @@ 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')
|
@model_validator(mode='after')
|
||||||
def splits_complete(self):
|
def splits_complete(self):
|
||||||
|
|||||||
@@ -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:
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -121,7 +121,6 @@ def create_order(c, quote, payment, origin):
|
|||||||
c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (order['id'],))
|
c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (order['id'],))
|
||||||
# An order with a proof gets its proof card (app/proof.py).
|
# An order with a proof gets its proof card (app/proof.py).
|
||||||
proof.create_child(c, order)
|
proof.create_child(c, order)
|
||||||
machines.route(c)
|
|
||||||
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']:
|
||||||
|
|||||||
@@ -17,10 +17,12 @@ band, so its size does not matter. Any other file above LARGE_SOURCE_BYTES
|
|||||||
is prepared by hand from the original.
|
is prepared by hand from the original.
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
|
import multiprocessing
|
||||||
import os
|
import os
|
||||||
import shutil
|
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
|
||||||
@@ -38,7 +40,8 @@ from .tiny import purchase_order
|
|||||||
LOCAL = ZoneInfo('America/Sao_Paulo')
|
LOCAL = ZoneInfo('America/Sao_Paulo')
|
||||||
|
|
||||||
# A 15 m part takes minutes to write; a long film, several parts.
|
# A 15 m part takes minutes to write; a long film, several parts.
|
||||||
CLAIM_TIMEOUT = timedelta(minutes=60)
|
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)))
|
||||||
# Read band by band, whatever their size.
|
# Read band by band, whatever their size.
|
||||||
@@ -55,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))
|
||||||
@@ -67,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):
|
||||||
@@ -75,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)''',
|
||||||
@@ -90,16 +132,19 @@ def render_one(storage):
|
|||||||
'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.'})
|
||||||
|
audit('print_file_timeout', order=str(job['order_id']), item=job['item_index'])
|
||||||
|
return True
|
||||||
|
if outcome == 'error':
|
||||||
final = job['attempts'] + 1 >= MAX_ATTEMPTS
|
final = job['attempts'] + 1 >= MAX_ATTEMPTS
|
||||||
finish(job, 'failed' if final else 'pending', {'error': type(exc).__name__})
|
finish(job, 'failed' if final else 'pending', {'error': result,
|
||||||
|
'reason': 'A geração falhou. Gere de novo.' if final else ''})
|
||||||
return True
|
return True
|
||||||
scratch, parts, detail = result
|
scratch, parts, detail = result
|
||||||
stored = []
|
stored = []
|
||||||
@@ -120,18 +165,30 @@ def render_one(storage):
|
|||||||
for part, (uid, _, size, _) in zip(detail['parts'], stored):
|
for part, (uid, _, size, _) in zip(detail['parts'], stored):
|
||||||
part.update(upload_id=str(uid), size=size)
|
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:
|
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''', (stored[0][0], Jsonb(detail), job['id']))
|
finished_at=now(),claim_token=NULL,claimed_at=NULL WHERE id=%s''', (stored[0][0], Jsonb(detail), job['id']))
|
||||||
c.execute('DELETE FROM dtf_local.print_parts WHERE order_id=%s AND item_index=%s',
|
c.execute('DELETE FROM dtf_local.print_parts WHERE order_id=%s AND item_index=%s',
|
||||||
(job['order_id'], job['item_index']))
|
(job['order_id'], job['item_index']))
|
||||||
for number, (uid, _, _, _) in enumerate(stored, 1):
|
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)',
|
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))
|
(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))
|
audit('print_file_ready', order=str(job['order_id']), item=job['item_index'], parts=len(stored))
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -162,8 +219,8 @@ def footer(job, item):
|
|||||||
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')
|
proof_of = job['snapshot'].get('proof_of')
|
||||||
if proof_of:
|
if proof_of:
|
||||||
return ' · '.join(['DROPSTAR', f'Prova do pedido {purchase_order(proof_of)}',
|
return ' · '.join(['DROPSTAR', f'PROVA do #{proof_of}',
|
||||||
f'Item {job["item_index"] + 1}/{count}', day])
|
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
|
||||||
@@ -193,11 +250,12 @@ def produce(storage, job, item, uploads):
|
|||||||
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'])
|
||||||
proof_of = job['snapshot'].get('proof_of')
|
proof_of = job['snapshot'].get('proof_of')
|
||||||
# A proof card's file: the first 30 cm, DTF-N-item-1-prova.png (app/proof.py).
|
# The child owns its final file; the class names its proof.
|
||||||
prefix = (file_prefix(proof_of, job['item_index']) + '-prova' if proof_of
|
prefix = (f'DTF-{job["number"]}-prova-{item.get("stroke_class") or "C3"}' if proof_of
|
||||||
else file_prefix(job['number'], job['item_index']))
|
else file_prefix(job['number'], job['item_index']))
|
||||||
parts, detail = render(item, files, output, prefix, footer=footer(job, item), tiles=True,
|
parts, detail = render(item, files, output, prefix, footer=footer(job, item), tiles=True,
|
||||||
limit_cm=PROOF_SHEET_CM if proof_of else None)
|
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:
|
||||||
shutil.rmtree(output, ignore_errors=True)
|
shutil.rmtree(output, ignore_errors=True)
|
||||||
raise
|
raise
|
||||||
@@ -208,7 +266,8 @@ 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):
|
||||||
|
|||||||
@@ -395,6 +395,21 @@ def part_cuts(production, part_cm=None):
|
|||||||
return cuts
|
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):
|
def _font(size):
|
||||||
return ImageFont.load_default(size=size)
|
return ImageFont.load_default(size=size)
|
||||||
|
|
||||||
@@ -425,12 +440,14 @@ def footer_band(text, width):
|
|||||||
|
|
||||||
# ---- The file ---------------------------------------------------------------
|
# ---- The file ---------------------------------------------------------------
|
||||||
|
|
||||||
def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False, limit_cm=None):
|
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`.
|
"""Write the PNG part(s) of one approved order item into `out_dir`.
|
||||||
|
|
||||||
`files` maps each source index to (local path, original name). With
|
`files` maps each source index to (local path, original name). With
|
||||||
`tiles`, each part's pieces for the Kanban's viewer go in
|
`tiles`, each part's pieces for the Kanban's viewer go in
|
||||||
out_dir/tiles/<part name>/<level>/<index>.png (app/printtiles.py).
|
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.
|
Returns the parts, [(path, name)], and the evidence the Kanban shows.
|
||||||
"""
|
"""
|
||||||
production = item['production']
|
production = item['production']
|
||||||
@@ -439,12 +456,13 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False,
|
|||||||
sources = [Source(*files[index]) for index in range(len(production['sources']))]
|
sources = [Source(*files[index]) for index in range(len(production['sources']))]
|
||||||
try:
|
try:
|
||||||
vector = {index for index, source in enumerate(sources) if source.pdf}
|
vector = {index for index, source in enumerate(sources) if source.pdf}
|
||||||
lowest = check_layout(item, [source.size for source in sources], vector)
|
lowest = check_layout(item, [source.size for source in sources], vector, proof=bool(limit_cm))
|
||||||
width = px(production['film_width_cm'])
|
width = px(production['film_width_cm'])
|
||||||
pieces = sorted((Piece(placement, sources[placement['source_index']])
|
pieces = sorted((Piece(placement, sources[placement['source_index']])
|
||||||
for placement in production['placements']), key=lambda piece: piece.y)
|
for placement in production['placements']), key=lambda piece: piece.y)
|
||||||
# A proof sheet is the film's first `limit_cm` (app/proof.py).
|
# A proof sheet is a 15 cm window around the finest stroke; a normal
|
||||||
cuts = ([Decimal(0), min(Decimal(str(production['height_cm'])), Decimal(str(limit_cm)))] if limit_cm
|
# 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))
|
else part_cuts(production, part_cm))
|
||||||
count = len(cuts) - 1
|
count = len(cuts) - 1
|
||||||
parts, manifests = [], []
|
parts, manifests = [], []
|
||||||
|
|||||||
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)
|
||||||
28
app/proof.py
28
app/proof.py
@@ -14,6 +14,7 @@ from decimal import Decimal
|
|||||||
from uuid import NAMESPACE_URL, uuid4, uuid5
|
from uuid import NAMESPACE_URL, uuid4, uuid5
|
||||||
|
|
||||||
from psycopg.types.json import Jsonb
|
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 '
|
||||||
@@ -33,13 +34,13 @@ def needs_proof(snapshot):
|
|||||||
#
|
#
|
||||||
# An order with a proof becomes a parent and a child. The child, the card
|
# 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
|
# "Prova", is an order of its own (orders.parent_id) with a pre-built proof
|
||||||
# sheet of up to 30 cm, DTF-N-item-1-prova.png, and follows the normal flow up
|
# 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
|
# 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
|
# 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
|
# 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
|
# 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.
|
# sale: it is not in Tiny, Números, the customer's account or their e-mails.
|
||||||
PROOF_SHEET_CM = Decimal('30')
|
PROOF_SHEET_CM = Decimal('15')
|
||||||
# Three proofs at most per order, one per item (Dropstar, 2026-10-23).
|
# Three proofs at most per order, one per item (Dropstar, 2026-10-23).
|
||||||
MAX_PROOFS = 3
|
MAX_PROOFS = 3
|
||||||
PROVIDER = 'prova'
|
PROVIDER = 'prova'
|
||||||
@@ -55,8 +56,20 @@ def create_child(c, parent):
|
|||||||
if parent.get('parent_id') or not needs_proof(parent['snapshot']):
|
if parent.get('parent_id') or not needs_proof(parent['snapshot']):
|
||||||
return None
|
return None
|
||||||
from .printjobs import queue
|
from .printjobs import queue
|
||||||
snapshot = {**parent['snapshot'], 'items': parent['snapshot']['items'][:MAX_PROOFS],
|
# A class has one proof. When several items share it, use the one with the
|
||||||
'proof_of': parent['number']}
|
# 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)
|
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 *''',
|
VALUES(%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
|
||||||
(uuid4(), proof_identity(parent['id']), Jsonb(snapshot), Jsonb({'provider': PROVIDER}),
|
(uuid4(), proof_identity(parent['id']), Jsonb(snapshot), Jsonb({'provider': PROVIDER}),
|
||||||
@@ -74,3 +87,10 @@ def open_child(c, parent_id):
|
|||||||
def waiting(c, order):
|
def waiting(c, order):
|
||||||
"""Whether the order waits for its proof: it has a proof card without an OK."""
|
"""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']))
|
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.')
|
||||||
|
|||||||
@@ -78,9 +78,15 @@ def approve(c, row, items, reviewer):
|
|||||||
'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']}
|
**({'stroke_px': original['stroke_px'], 'stroke_class': original['stroke_class']}
|
||||||
if original.get('stroke_class') else {}),
|
if original.get('stroke_class') else {}),
|
||||||
**({'stroke_choice': original['stroke_choice']} if original.get('stroke_choice') 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 {})})
|
**({'split': original['split']} if original.get('split') else {})})
|
||||||
bill_splits(priced)
|
bill_splits(priced)
|
||||||
metres = sum(Decimal(i['billed_metres']) for i in priced)
|
metres = sum(Decimal(i['billed_metres']) for i in priced)
|
||||||
@@ -93,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']))
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -235,6 +236,8 @@ INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id)
|
|||||||
|
|
||||||
-- 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.
|
||||||
@@ -284,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()
|
||||||
@@ -303,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,
|
||||||
|
|||||||
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.
|
||||||
@@ -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
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -180,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');
|
||||||
@@ -305,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);
|
||||||
@@ -350,10 +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');
|
||||||
// A ready sheet takes no acceptance (Dropstar, 2026-11-03): the designer
|
// A ready sheet now offers the same acceptance as loose art (Dropstar,
|
||||||
// cannot clean a closed sheet, so the dot always sends it back.
|
// 2026-11-05): the dots may be part of the art; the customer can take them.
|
||||||
assert.deepEqual(await evaluate(`({box:!!document.querySelector('[data-residuo]'),
|
assert.deepEqual(await evaluate(`({box:!!document.querySelector('[data-residuo]'),
|
||||||
text:$('lista').textContent.includes('Estou ciente'),stopped:itemAtual===null})`),{box:false,text:false,stopped:true});
|
text:$('lista').textContent.includes('Li e concordo'),stopped:itemAtual===null})`),{box:true,text:true,stopped:true});
|
||||||
|
await evaluate(`(()=>{const el=document.querySelector('[data-residuo]');el.checked=true;
|
||||||
|
el.dispatchEvent(new Event('change',{bubbles:true}));})()`);
|
||||||
|
await waitFor(()=>evaluate('itemAtual!==null'),'accepted residue lets the sheet through');
|
||||||
await evaluate(`folhas=[];pintaFolha()`);
|
await evaluate(`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']
|
||||||
|
|||||||
@@ -36,15 +36,15 @@ CUSTOMER = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'print-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()
|
||||||
|
|
||||||
|
|
||||||
@@ -93,7 +93,7 @@ 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))
|
||||||
# A 300 DPI PNG on a transparent background (item 13): the layout's 10 cm
|
# A 300 DPI PNG on a transparent background (item 13): the layout's 10 cm
|
||||||
# and the 1,5 cm footer band, outside the billed length.
|
# and the 1,5 cm footer band, outside the billed length.
|
||||||
film = download_png(client, row['upload_id'])
|
film = download_png(client, row['upload_id'])
|
||||||
@@ -141,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
|
||||||
@@ -167,10 +171,7 @@ def run():
|
|||||||
# Item 10: printing, the file goes once into its machine's hot folder for
|
# Item 10: printing, the file goes once into its machine's hot folder for
|
||||||
# its class; Flexi taking it is reported; leaving Imprimindo withdraws
|
# its class; Flexi taking it is reported; leaving Imprimindo withdraws
|
||||||
# what Flexi did not take.
|
# what Flexi did not take.
|
||||||
tag = uuid4().hex[:6]
|
|
||||||
machine = client.call('/operator/machines', {'name': f'Hot {tag}', 'products': ['textil']}, operator=True)['id']
|
|
||||||
try:
|
try:
|
||||||
client.call('/operator/orders/' + oid + '/machine', {'machine_id': machine}, operator=True)
|
|
||||||
# No class measured or chosen: the part waits for one.
|
# 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]
|
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)
|
client.call('/operator/orders/' + oid + '/contraction', {'item_index': 0, 'value': 'C2'}, operator=True)
|
||||||
@@ -212,6 +213,7 @@ def run():
|
|||||||
unread = upload_bytes(client, b'LOCAL PRINT TEST - NOT AN IMAGE', name='LOCAL-PROOF-TEST.cdr')
|
unread = upload_bytes(client, b'LOCAL PRINT TEST - NOT AN IMAGE', name='LOCAL-PROOF-TEST.cdr')
|
||||||
long = loose_item(unread, copies=1)
|
long = loose_item(unread, copies=1)
|
||||||
long['metres'] = '10.5'
|
long['metres'] = '10.5'
|
||||||
|
long['proof_y_fraction'] = '0.8'
|
||||||
long['production'] = {**long['production'], 'height_cm': 1050,
|
long['production'] = {**long['production'], 'height_cm': 1050,
|
||||||
'placements': [{**long['production']['placements'][0], 'y_cm': 1040}]}
|
'placements': [{**long['production']['placements'][0], 'y_cm': 1040}]}
|
||||||
parent = paid_order(client, long)
|
parent = paid_order(client, long)
|
||||||
@@ -220,18 +222,27 @@ def run():
|
|||||||
card = next(o for o in board if o['id'] == mine['proof_card']['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['proof_parent']['number'] == parent['number'] and card['state'] == 'rec', card
|
||||||
assert card['snapshot']['proof_of'] == parent['number'] and card['payment'] == {'provider': 'prova'}
|
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:
|
with db.connect() as c:
|
||||||
assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key LIKE %s', (card['id'] + '%',)).fetchone()
|
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'],))
|
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (card['id'],))
|
||||||
final = upload_bytes(client, b'LOCAL PROOF FINAL FIXTURE', order_id=parent['id'])
|
final = str(uuid4())
|
||||||
version = client.call('/operator/orders/' + parent['id'] + '/final-files',
|
held = client.call('/operator/orders/' + parent['id'] + '/final-files',
|
||||||
{'version': parent['version'], 'files': [{'item_index': 0, 'upload_id': final}],
|
{'version': parent['version'], 'files': [{'item_index': 0, 'upload_id': final}],
|
||||||
'note': 'Local proof test final'}, operator=True)['version']
|
'note': 'Local proof test final'}, operator=True, expected=409)
|
||||||
version = client.call('/operator/orders/' + parent['id'] + '/move', {'state': 'tra', 'version': version},
|
|
||||||
operator=True)['version']
|
|
||||||
held = client.call('/operator/orders/' + parent['id'] + '/move', {'state': 'imp', 'version': version},
|
|
||||||
operator=True, expected=409)
|
|
||||||
assert 'Aguardando prova' in held['detail'], held
|
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']},
|
client.call('/operator/orders/' + card['id'] + '/move', {'state': 'fin', 'version': card['version']},
|
||||||
operator=True, expected=409)
|
operator=True, expected=409)
|
||||||
# Reprovada needs its reason; the order goes back to Arte recebida.
|
# Reprovada needs its reason; the order goes back to Arte recebida.
|
||||||
@@ -244,7 +255,16 @@ def run():
|
|||||||
mine = next(o for o in board if o['id'] == parent['id'])
|
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['state'] == 'rec' and mine['proof_card']['proof_result'] == 'rejected', mine['proof_card']
|
||||||
assert mine['proof_card']['proof_reason'] == 'Cor do fundo errada'
|
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'
|
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.
|
# A new card, and Prova OK lets the order into the queue.
|
||||||
again = client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True)
|
again = client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True)
|
||||||
client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True, expected=409)
|
client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True, expected=409)
|
||||||
@@ -252,7 +272,7 @@ def run():
|
|||||||
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (again['id'],))
|
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)
|
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'])
|
mine = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == parent['id'])
|
||||||
assert mine['proof_ok_at'] and mine['proof_card']['proof_result'] == 'ok', mine
|
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')
|
print('PASS: an order with a proof waits for its proof card, which is answered OK or rejected in Revisão')
|
||||||
|
|
||||||
# A customer cannot see or reuse another order's generated file.
|
# A customer cannot see or reuse another order's generated file.
|
||||||
@@ -313,7 +333,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')
|
||||||
|
|
||||||
|
|||||||
@@ -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'
|
||||||
@@ -245,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')
|
||||||
@@ -262,28 +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).
|
||||||
# Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão comes before Finalizado.
|
held=client.call('/operator/orders/'+oid+'/move',{'state':'cor','version':0},operator=True,expected=409)
|
||||||
for state in ('cor','rec','tra','imp','rev','fin'):
|
|
||||||
if state=='tra':
|
|
||||||
# The queue takes approved final files only.
|
|
||||||
client.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
|
||||||
files=[{'item_index':i,'upload_id':upload_bytes(client,b'LOCAL FINAL FIXTURE '+str(i).encode(),order_id=oid)} for i in range(4)]
|
|
||||||
result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True)
|
|
||||||
version=result['version']
|
|
||||||
if state=='imp':
|
|
||||||
# Above 10 m the proof comes first (app/proof.py): the order waits
|
|
||||||
# outside the queue for Prova OK on its proof card in Revisão.
|
|
||||||
held=client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version},operator=True,expected=409)
|
|
||||||
assert 'Aguardando prova' in held['detail'], held
|
assert 'Aguardando prova' in held['detail'], held
|
||||||
card=next(o for o in client.call('/operator/board',operator=True)['orders'] if o['id']==oid)['proof_card']
|
card=next(o for o in board['orders'] if o['id']==oid)['proof_card']
|
||||||
from app.core import db
|
from app.core import db
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s",(card['id'],))
|
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)
|
client.call('/operator/orders/'+card['id']+'/proof-answer',{'result':'ok'},operator=True)
|
||||||
version+=1
|
version=next(o for o in client.call('/operator/board',operator=True)['orders'] if o['id']==oid)['version']
|
||||||
moved=client.call('/operator/orders/'+oid+'/move',{'state':state,'version':version,'reason':'Local test correction' if state=='cor' else ''},operator=True)
|
client.call('/operator/orders/'+oid+'/move',{'state':'cor','version':version},operator=True,expected=422)
|
||||||
|
# Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão comes before Finalizado.
|
||||||
|
machine=None
|
||||||
|
for state in ('cor','rec','tra','imp','rev','fin'):
|
||||||
|
if state=='tra':
|
||||||
|
# The queue takes approved final files only.
|
||||||
|
client.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
|
||||||
|
files=[{'item_index':i,'upload_id':upload_bytes(client,final_png_bytes(str(i)),name=f'LOCAL-FINAL-{i}.png',order_id=oid)} for i in range(4)]
|
||||||
|
result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True)
|
||||||
|
version=result['version']
|
||||||
|
body={'state':state,'version':version,'reason':'Local test correction' if state=='cor' else ''}
|
||||||
|
if state=='imp':
|
||||||
|
if machine is None:
|
||||||
|
machine=client.call('/operator/machines',{'name':'Smoke '+uuid4().hex[:6],'products':['textil']},operator=True)['id']
|
||||||
|
body['machine_id']=machine
|
||||||
|
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()
|
||||||
|
|||||||
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
|
||||||
@@ -338,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.
|
||||||
@@ -381,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:
|
||||||
@@ -494,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']]
|
||||||
@@ -508,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']
|
||||||
|
|||||||
@@ -146,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);
|
||||||
}
|
}
|
||||||
@@ -359,6 +362,7 @@
|
|||||||
residue_accepted:item.residueAccepted||0,
|
residue_accepted:item.residueAccepted||0,
|
||||||
...(item.strokeClass?{stroke_px:item.strokePx,stroke_class:item.strokeClass}:{}),
|
...(item.strokeClass?{stroke_px:item.strokePx,stroke_class:item.strokeClass}:{}),
|
||||||
...(item.strokeChoice?{stroke_choice:item.strokeChoice}:{}),
|
...(item.strokeChoice?{stroke_choice:item.strokeChoice}:{}),
|
||||||
|
...(item.proofYFraction!=null?{proof_y_fraction:item.proofYFraction}:{}),
|
||||||
...(item.split?{split:item.split}:{})});
|
...(item.split?{split:item.split}:{})});
|
||||||
}
|
}
|
||||||
const service = entrega.tipo==='retira' ? 'pickup' : entrega.servico;
|
const service = entrega.tipo==='retira' ? 'pickup' : entrega.servico;
|
||||||
@@ -369,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);
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -971,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>
|
||||||
|
|||||||
@@ -262,6 +262,9 @@ main{padding:0}
|
|||||||
.card.open,.mini.open{border-color:var(--ink);box-shadow:0 0 0 1px var(--ink)}
|
.card.open,.mini.open{border-color:var(--ink);box-shadow:0 0 0 1px var(--ink)}
|
||||||
.card.off{opacity:.7}
|
.card.off{opacity:.7}
|
||||||
.card[draggable=true]{cursor:grab}
|
.card[draggable=true]{cursor:grab}
|
||||||
|
.card:focus-visible,.mini:focus-visible{outline:2px solid var(--acc);outline-offset:2px}
|
||||||
|
.card-open{display:inline-flex;align-items:center;justify-content:center;gap:5px;align-self:flex-start;min-height:28px;padding:4px 8px;border:1px solid var(--ln2);border-radius:7px;background:var(--sf3);color:var(--tx);font:inherit;font-size:11px;font-weight:600;cursor:pointer}
|
||||||
|
.card-open:hover,.card-open:focus-visible{border-color:var(--acc);color:var(--acc)}
|
||||||
.ctop{display:grid;grid-template-columns:56px minmax(0,1fr);gap:12px;align-items:center}
|
.ctop{display:grid;grid-template-columns:56px minmax(0,1fr);gap:12px;align-items:center}
|
||||||
.thumb{width:56px;height:56px;border-radius:8px;padding:4px;border:0;box-shadow:inset 0 0 0 1px var(--ln);background:repeating-conic-gradient(var(--chka) 0 25%,var(--chkb) 0 50%) 0 0/8px 8px}
|
.thumb{width:56px;height:56px;border-radius:8px;padding:4px;border:0;box-shadow:inset 0 0 0 1px var(--ln);background:repeating-conic-gradient(var(--chka) 0 25%,var(--chkb) 0 50%) 0 0/8px 8px}
|
||||||
.thumb img{transition:transform .5s cubic-bezier(.2,.8,.2,1)}
|
.thumb img{transition:transform .5s cubic-bezier(.2,.8,.2,1)}
|
||||||
@@ -418,6 +421,9 @@ main{padding:0}
|
|||||||
.inote.bad,.inote.bad .i{color:var(--bad)}
|
.inote.bad,.inote.bad .i{color:var(--bad)}
|
||||||
.inotes .callout{margin:2px 0}
|
.inotes .callout{margin:2px 0}
|
||||||
.links{display:flex;gap:8px;margin-top:18px;flex-wrap:wrap}
|
.links{display:flex;gap:8px;margin-top:18px;flex-wrap:wrap}
|
||||||
|
.originals{position:relative;border:1px solid var(--ln);border-radius:8px;padding:8px 12px}
|
||||||
|
.originals summary{cursor:pointer;font-weight:600}
|
||||||
|
.originals .btn{margin:8px 8px 0 0}
|
||||||
.facts3{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));border:1px solid var(--ln);border-radius:12px;overflow:hidden}
|
.facts3{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));border:1px solid var(--ln);border-radius:12px;overflow:hidden}
|
||||||
.fact{padding:14px 16px;display:flex;flex-direction:column;gap:3px;min-width:0;border-right:1px solid var(--ln)}
|
.fact{padding:14px 16px;display:flex;flex-direction:column;gap:3px;min-width:0;border-right:1px solid var(--ln)}
|
||||||
.fact:last-child{border-right:0}
|
.fact:last-child{border-right:0}
|
||||||
|
|||||||
@@ -142,6 +142,8 @@
|
|||||||
<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>
|
<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>
|
||||||
<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="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>
|
||||||
</div>
|
</div>
|
||||||
|
<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>
|
||||||
<section class="panel clip">
|
<section class="panel clip">
|
||||||
|
|||||||
134
web/kanban.js
134
web/kanban.js
@@ -229,8 +229,8 @@ async function api(path,body){
|
|||||||
const r=await fetch('/api/operator'+path,{headers:{'Content-Type':'application/json'},...(body===undefined?{}:{method:'POST',body:JSON.stringify(body)})});
|
const r=await fetch('/api/operator'+path,{headers:{'Content-Type':'application/json'},...(body===undefined?{}:{method:'POST',body:JSON.stringify(body)})});
|
||||||
const d=await r.json();if(!r.ok){const error=new Error(typeof d.detail==='string'?d.detail:'Confira os campos ('+r.status+').');error.status=r.status;throw error;}return d;
|
const d=await r.json();if(!r.ok){const error=new Error(typeof d.detail==='string'?d.detail:'Confira os campos ('+r.status+').');error.status=r.status;throw error;}return d;
|
||||||
}
|
}
|
||||||
function download(uid){return async()=>{
|
function download(uid,orderId){return async()=>{
|
||||||
const result=await api('/uploads/'+uid+'/download');
|
const result=await api('/uploads/'+uid+'/download'+(orderId?'?order_id='+encodeURIComponent(orderId):''));
|
||||||
const link=node('a');link.href=result.url;link.referrerPolicy='no-referrer';link.download=result.name;link.click();
|
const link=node('a');link.href=result.url;link.referrerPolicy='no-referrer';link.download=result.name;link.click();
|
||||||
};}
|
};}
|
||||||
// ---- Automatic folder ------------------------------------------------------
|
// ---- Automatic folder ------------------------------------------------------
|
||||||
@@ -670,6 +670,7 @@ function printState(order){
|
|||||||
if((order.corrections||[]).length)return {text:'Correção recebida',tone:'warn'};
|
if((order.corrections||[]).length)return {text:'Correção recebida',tone:'warn'};
|
||||||
const rows=order.print_files||[], items=order.snapshot.items.length;
|
const rows=order.print_files||[], items=order.snapshot.items.length;
|
||||||
const ready=rows.filter(r=>r.status==='ready').length;
|
const ready=rows.filter(r=>r.status==='ready').length;
|
||||||
|
if(rows.some(r=>r.status==='failed'||r.timed_out))return {text:'Falhou ao gerar',tone:'warn'};
|
||||||
if(rows.some(r=>r.status==='pending'||r.status==='rendering'))return {text:'Gerando arquivo…',tone:''};
|
if(rows.some(r=>r.status==='pending'||r.status==='rendering'))return {text:'Gerando arquivo…',tone:''};
|
||||||
if(ready===items)return {text:'Falta aprovar o final',tone:'warn'};
|
if(ready===items)return {text:'Falta aprovar o final',tone:'warn'};
|
||||||
if(rows.some(r=>r.status==='manual'||r.status==='failed'))
|
if(rows.some(r=>r.status==='manual'||r.status==='failed'))
|
||||||
@@ -849,9 +850,10 @@ function renderBoard(){
|
|||||||
const filtered=Object.entries(boardFilter).some(([key,value])=>value&&key!=='product')||!!boardFilter.product;
|
const filtered=Object.entries(boardFilter).some(([key,value])=>value&&key!=='product')||!!boardFilter.product;
|
||||||
$('kan').replaceChildren(...Object.entries(board.states).map(([state,title])=>{
|
$('kan').replaceChildren(...Object.entries(board.states).map(([state,title])=>{
|
||||||
const column=node('section',undefined,'col');column.dataset.state=state;column.setAttribute('aria-label',title);
|
const column=node('section',undefined,'col');column.dataset.state=state;column.setAttribute('aria-label',title);
|
||||||
// A queue: the order paid first is on top, the newest at the bottom, however
|
// Working columns are queues; Finalizado shows the most recently ready order first.
|
||||||
// the list was put together (older finished ones, one opened from the search).
|
const orders=board.orders.filter(o=>o.state===state&&matches(o)).sort((a,b)=>state==='fin'
|
||||||
const orders=board.orders.filter(o=>o.state===state&&matches(o)).sort((a,b)=>queueKey(a)-queueKey(b)||a.number-b.number);
|
? new Date(b.finished_at||b.updated_at)-new Date(a.finished_at||a.updated_at)||b.id.localeCompare(a.id)
|
||||||
|
: queueKey(a)-queueKey(b)||a.number-b.number);
|
||||||
const head=node('header',undefined,'colhead');
|
const head=node('header',undefined,'colhead');
|
||||||
head.append(svgIcon(GLYPH[state],'sg'+(state==='cor'?' cor':'')));
|
head.append(svgIcon(GLYPH[state],'sg'+(state==='cor'?' cor':'')));
|
||||||
const text=node('span',undefined,'coltx');text.append(node('h2',title));
|
const text=node('span',undefined,'coltx');text.append(node('h2',title));
|
||||||
@@ -1024,8 +1026,9 @@ function productLine(items){
|
|||||||
// A card drags forward when this profile makes that move, or up and down
|
// A card drags forward when this profile makes that move, or up and down
|
||||||
// when it sets the column's order; a card of another operator's machine does not.
|
// when it sets the column's order; a card of another operator's machine does not.
|
||||||
function draggable(c,order){
|
function draggable(c,order){
|
||||||
c.draggable=!order.cancelled_at&&mayAct(order)&&(mayReorder(order.state)||board.transitions[order.state].some(s=>s!=='cor'&&mayMove(order.state,s)));
|
c.draggable=!order.cancelled_at&&!waitingProof(order)&&mayAct(order)&&(mayReorder(order.state)||board.transitions[order.state].some(s=>s!=='cor'&&mayMove(order.state,s)));
|
||||||
c.onclick=()=>openPanel(order.id);
|
c.onclick=()=>openPanel(order.id);
|
||||||
|
c.onkeydown=e=>{if(e.target===c&&(e.key==='Enter'||e.key===' ')){e.preventDefault();openPanel(order.id);}};
|
||||||
c.ondragstart=e=>{
|
c.ondragstart=e=>{
|
||||||
dragging=order;
|
dragging=order;
|
||||||
e.dataTransfer.setData('text/plain',order.id);
|
e.dataTransfer.setData('text/plain',order.id);
|
||||||
@@ -1040,8 +1043,8 @@ function draggable(c,order){
|
|||||||
function card(order,place){
|
function card(order,place){
|
||||||
const s=order.snapshot, mine=isMine(order)&&order.state!=='fin'&&!order.cancelled_at;
|
const s=order.snapshot, mine=isMine(order)&&order.state!=='fin'&&!order.cancelled_at;
|
||||||
const [step,tone]=nextStep(order,place);
|
const [step,tone]=nextStep(order,place);
|
||||||
const c=node('button',undefined,'card'+(mine?' mine':'')+(tone==='live'?' live':'')+(order.id===openOrder?' open':'')+(order.cancelled_at?' off':''));
|
const c=node('div',undefined,'card'+(mine?' mine':'')+(tone==='live'?' live':'')+(order.id===openOrder?' open':'')+(order.cancelled_at?' off':''));
|
||||||
c.type='button';c.dataset.card=order.id;
|
c.tabIndex=0;c.setAttribute('role','button');c.dataset.card=order.id;
|
||||||
const who=buyer(s);
|
const who=buyer(s);
|
||||||
c.setAttribute('aria-label','Pedido #'+order.number+', '+who.title+': '+step);
|
c.setAttribute('aria-label','Pedido #'+order.number+', '+who.title+': '+step);
|
||||||
const top=node('span',undefined,'ctop'), info=node('span',undefined,'cinfo');
|
const top=node('span',undefined,'ctop'), info=node('span',undefined,'cinfo');
|
||||||
@@ -1065,7 +1068,7 @@ function card(order,place){
|
|||||||
next.append(node('span',step,'stx'));
|
next.append(node('span',step,'stx'));
|
||||||
foot.append(next);
|
foot.append(next);
|
||||||
const flag=flagNode(cardFlags(order));if(flag)foot.append(flag);
|
const flag=flagNode(cardFlags(order));if(flag)foot.append(flag);
|
||||||
c.append(foot);
|
c.append(foot,cardOpenAction(order));
|
||||||
draggable(c,order);
|
draggable(c,order);
|
||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
@@ -1073,7 +1076,7 @@ function card(order,place){
|
|||||||
// nothing else. A pickup waiting more than two days is said in warning.
|
// nothing else. A pickup waiting more than two days is said in warning.
|
||||||
const PICKUP_WARN_DAYS=2;
|
const PICKUP_WARN_DAYS=2;
|
||||||
function miniCard(order){
|
function miniCard(order){
|
||||||
const c=node('button',undefined,'mini'+(order.id===openOrder?' open':''));c.type='button';c.dataset.card=order.id;
|
const c=node('div',undefined,'mini'+(order.id===openOrder?' open':''));c.tabIndex=0;c.setAttribute('role','button');c.dataset.card=order.id;
|
||||||
const who=buyer(order.snapshot);
|
const who=buyer(order.snapshot);
|
||||||
const row=node('span',undefined,'crow');row.append(node('span','#'+order.number,'num'),node('span',metres(orderMetres(order)),'age'));
|
const row=node('span',undefined,'crow');row.append(node('span','#'+order.number,'num'),node('span',metres(orderMetres(order)),'age'));
|
||||||
const name=node('span',who.title,'cname');name.title=who.mail||who.title;
|
const name=node('span',who.title,'cname');name.title=who.mail||who.title;
|
||||||
@@ -1085,7 +1088,7 @@ function miniCard(order){
|
|||||||
else if(days>=PICKUP_WARN_DAYS){text='Não retirado, '+plural(days,'dia','dias');ic=IC.bag;warn=true;}
|
else if(days>=PICKUP_WARN_DAYS){text='Não retirado, '+plural(days,'dia','dias');ic=IC.bag;warn=true;}
|
||||||
else{text='Aguardando retirada';ic=IC.bag;}
|
else{text='Aguardando retirada';ic=IC.bag;}
|
||||||
const done=node('span',undefined,'done'+(warn?' warn':''));done.append(svgIcon(ic,'i s'),text);
|
const done=node('span',undefined,'done'+(warn?' warn':''));done.append(svgIcon(ic,'i s'),text);
|
||||||
c.append(row,name,done);
|
c.append(row,name,done,cardOpenAction(order));
|
||||||
c.setAttribute('aria-label','Pedido #'+order.number+', '+who.title+': '+text);
|
c.setAttribute('aria-label','Pedido #'+order.number+', '+who.title+': '+text);
|
||||||
draggable(c,order);
|
draggable(c,order);
|
||||||
return c;
|
return c;
|
||||||
@@ -1120,9 +1123,10 @@ async function reorder(order,column,y){
|
|||||||
await load();
|
await load();
|
||||||
}
|
}
|
||||||
async function loadOlderFinished(){
|
async function loadOlderFinished(){
|
||||||
const shown=board.orders.filter(o=>o.state==='fin').sort((a,b)=>a.created_at<b.created_at?-1:1);
|
const shown=board.orders.filter(o=>o.state==='fin').sort((a,b)=>
|
||||||
|
new Date(a.finished_at||a.updated_at)-new Date(b.finished_at||b.updated_at)||a.id.localeCompare(b.id));
|
||||||
const oldest=shown[0];const params=new URLSearchParams({limit:'50'});
|
const oldest=shown[0];const params=new URLSearchParams({limit:'50'});
|
||||||
if(oldest){params.set('before_created_at',oldest.created_at);params.set('before_id',oldest.id);}
|
if(oldest){params.set('before_finished_at',oldest.finished_at||oldest.updated_at);params.set('before_id',oldest.id);}
|
||||||
const page=absorb(await api('/orders/finished?'+params));
|
const page=absorb(await api('/orders/finished?'+params));
|
||||||
const known=new Set(board.orders.map(o=>o.id));
|
const known=new Set(board.orders.map(o=>o.id));
|
||||||
const fresh=page.orders.filter(o=>!known.has(o.id));
|
const fresh=page.orders.filter(o=>!known.has(o.id));
|
||||||
@@ -1398,7 +1402,7 @@ function moreMenu(order,buttonClass='btn sq ghost'){
|
|||||||
if(!order.cancelled_at){
|
if(!order.cancelled_at){
|
||||||
// Undo a mistaken move: one stage back, internal reason, no customer message.
|
// Undo a mistaken move: one stage back, internal reason, no customer message.
|
||||||
const previous=board.back?.[order.state];
|
const previous=board.back?.[order.state];
|
||||||
if(previous&&mayMove(order.state,previous)&&mayAct(order))item(IC.back,'Voltar para '+board.states[previous],()=>backDialog(order,previous)).dataset.back=previous;
|
if(previous&&!waitingProof(order)&&mayMove(order.state,previous)&&mayAct(order))item(IC.back,'Voltar para '+board.states[previous],()=>backDialog(order,previous)).dataset.back=previous;
|
||||||
if(order.state!=='fin'&&!waitingContact(order)&&may('produce'))
|
if(order.state!=='fin'&&!waitingContact(order)&&may('produce'))
|
||||||
item(IC.phone,'Aguardando contato',()=>contactDialog(order)).dataset.contact='';
|
item(IC.phone,'Aguardando contato',()=>contactDialog(order)).dataset.contact='';
|
||||||
if(!isTest(order)&&may('rework'))item(IC.rework,'Abrir retrabalho',()=>reworkForm(order));
|
if(!isTest(order)&&may('rework'))item(IC.rework,'Abrir retrabalho',()=>reworkForm(order));
|
||||||
@@ -1432,7 +1436,9 @@ function contactNotice(order,canClear){
|
|||||||
box.append(ico,p);
|
box.append(ico,p);
|
||||||
const zap=whatsappLink(order.snapshot.customer.zap);
|
const zap=whatsappLink(order.snapshot.customer.zap);
|
||||||
if(zap){const a=node('a','Abrir conversa','btn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.prepend(svgIcon(IC.chat,'i s'));box.append(a);}
|
if(zap){const a=node('a','Abrir conversa','btn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.prepend(svgIcon(IC.chat,'i s'));box.append(a);}
|
||||||
if(canClear)box.append(button('Contato feito',async()=>{
|
// A proof order closes its contact wait with Prova OK, the only button
|
||||||
|
// (item 0.1). Other orders still need a way to record that contact is done.
|
||||||
|
if(canClear&&!needsProof(order))box.append(button('Contato feito',async()=>{
|
||||||
await api('/orders/'+order.id+'/contact',{waiting:false});say('Contato registrado: a marca saiu do pedido #'+order.number+'.');await load();},'btn'));
|
await api('/orders/'+order.id+'/contact',{waiting:false});say('Contato registrado: a marca saiu do pedido #'+order.number+'.');await load();},'btn'));
|
||||||
return box;
|
return box;
|
||||||
}
|
}
|
||||||
@@ -1518,6 +1524,11 @@ function nextBox(order){
|
|||||||
const note=text=>body.push(node('p',text,'nnote'));
|
const note=text=>body.push(node('p',text,'nnote'));
|
||||||
const can=to=>mayMove(st,to)&&mayAct(order);
|
const can=to=>mayMove(st,to)&&mayAct(order);
|
||||||
const moveBtn=(to,label,className='btn pri lg')=>{const b=button(label||'Mover para '+board.states[to],()=>move(order,to),className);b.dataset.move=to;return b;};
|
const moveBtn=(to,label,className='btn pri lg')=>{const b=button(label||'Mover para '+board.states[to],()=>move(order,to),className);b.dataset.move=to;return b;};
|
||||||
|
if(waitingProof(order)){
|
||||||
|
title='Aguardando prova do #'+order.proof_card.number;
|
||||||
|
note('O pedido segue para Arte conferida após Prova OK no card da prova. Você pode abrir o arquivo para consultar.');
|
||||||
|
return composeNext(title,body,main,more);
|
||||||
|
}
|
||||||
// A proof card in Revisão waits for its answer (Dropstar, 2026-11-03).
|
// A proof card in Revisão waits for its answer (Dropstar, 2026-11-03).
|
||||||
if(order.proof_parent&&st==='rev'){
|
if(order.proof_parent&&st==='rev'){
|
||||||
title='Responder a prova';
|
title='Responder a prova';
|
||||||
@@ -1551,6 +1562,14 @@ function nextBox(order){
|
|||||||
const p=node('p',undefined,'nnote');p.append(node('b','Prova reprovada: '),order.proof_card.proof_reason);body.push(p);
|
const p=node('p',undefined,'nnote');p.append(node('b','Prova reprovada: '),order.proof_card.proof_reason);body.push(p);
|
||||||
if(may('produce'))more.push(button('Nova prova',async()=>{await api('/orders/'+order.id+'/proof-card',{});await load();say('Nova prova criada.');},'btn lg'));
|
if(may('produce'))more.push(button('Nova prova',async()=>{await api('/orders/'+order.id+'/proof-card',{});await load();say('Nova prova criada.');},'btn lg'));
|
||||||
}
|
}
|
||||||
|
if(st==='rec'&&order.proof_parent){
|
||||||
|
title=finalDone(order)?'Conferir a prova':'Gerando a prova';
|
||||||
|
note(finalDone(order)?'Abra o PNG gerado pelo Prumo e confirme a contração.':'O Prumo prepara até 15 cm por classe e aprova o PNG final automaticamente.');
|
||||||
|
if(finalDone(order)&&may('produce'))main.push(checkButton(order,'btn pri lg'));
|
||||||
|
if((order.print_files||[]).some(r=>r.status==='failed'||r.status==='manual'||r.timed_out)&&may('produce'))
|
||||||
|
more.push(button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn lg'));
|
||||||
|
return composeNext(title,body,main,more);
|
||||||
|
}
|
||||||
if(st==='rec'||st==='cor'){
|
if(st==='rec'||st==='cor'){
|
||||||
if(!finalDone(order)&&trans.includes('tra')){
|
if(!finalDone(order)&&trans.includes('tra')){
|
||||||
if(st==='rec')title='Aprovar o arquivo final';
|
if(st==='rec')title='Aprovar o arquivo final';
|
||||||
@@ -1694,7 +1713,7 @@ function readyFinals(order){
|
|||||||
const fixes=order.corrections||[];
|
const fixes=order.corrections||[];
|
||||||
return order.snapshot.items.map((item,index)=>{
|
return order.snapshot.items.map((item,index)=>{
|
||||||
const fix=fixes.find(f=>f.item_index===index);
|
const fix=fixes.find(f=>f.item_index===index);
|
||||||
if(fix)return fix.expired?null:{files:[{upload_id:fix.upload_id,name:fix.name}],name:fix.name,source:'correction',label:'Correção do cliente ('+fix.name+')'};
|
if(fix)return fix.expired||!fix.name.toLowerCase().endsWith('.png')?null:{files:[{upload_id:fix.upload_id,name:fix.name}],name:fix.name,source:'correction',label:'Correção do cliente ('+fix.name+')'};
|
||||||
const made=fixes.length?null:(order.print_files||[]).find(r=>r.item_index===index&&r.status==='ready');
|
const made=fixes.length?null:(order.print_files||[]).find(r=>r.item_index===index&&r.status==='ready');
|
||||||
if(!made)return null;
|
if(!made)return null;
|
||||||
const original=made.detail?.source==='original', files=generatedFiles(made);
|
const original=made.detail?.source==='original', files=generatedFiles(made);
|
||||||
@@ -1720,7 +1739,8 @@ function finalDialog(order,ready,{replace=false}={}){
|
|||||||
slot.append(node('span',label,'lbl'));
|
slot.append(node('span',label,'lbl'));
|
||||||
const input=node('input');input.multiple=true;input.required=true;input.dataset.finalItem=index;
|
const input=node('input');input.multiple=true;input.required=true;input.dataset.finalItem=index;
|
||||||
input.setAttribute('aria-label','Arquivo final, '+label);
|
input.setAttribute('aria-label','Arquivo final, '+label);
|
||||||
const drop=dropField(input,{hint:'PNG, PDF ou TIFF, do tamanho da impressão.'});
|
input.accept='.png,image/png';
|
||||||
|
const drop=dropField(input,{hint:'PNG transparente a 300 DPI, do tamanho da impressão.'});
|
||||||
const file=ready[index];
|
const file=ready[index];
|
||||||
if(file){
|
if(file){
|
||||||
const use=node('input');use.checked=true;use.dataset.useGenerated=index;input.required=false;drop.hidden=true;
|
const use=node('input');use.checked=true;use.dataset.useGenerated=index;input.required=false;drop.hidden=true;
|
||||||
@@ -1740,6 +1760,7 @@ function finalDialog(order,ready,{replace=false}={}){
|
|||||||
const generated=input.generated?.();
|
const generated=input.generated?.();
|
||||||
if(generated){refs.push(...generated.map(upload_id=>({item_index:index,upload_id})));continue;}
|
if(generated){refs.push(...generated.map(upload_id=>({item_index:index,upload_id})));continue;}
|
||||||
for(const file of input.files){
|
for(const file of input.files){
|
||||||
|
if(!file.name.toLowerCase().endsWith('.png'))throw Error('O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.');
|
||||||
const uid=await dtfUpload(file,{api,startPath:'/orders/'+order.id+'/uploads',scope:'operator:'+order.id+':'+order.version,progress:text=>say(text)});
|
const uid=await dtfUpload(file,{api,startPath:'/orders/'+order.id+'/uploads',scope:'operator:'+order.id+':'+order.version,progress:text=>say(text)});
|
||||||
refs.push({item_index:index,upload_id:uid});
|
refs.push({item_index:index,upload_id:uid});
|
||||||
}
|
}
|
||||||
@@ -1762,12 +1783,20 @@ const FOLDER_PATH_KEY='folder-path';
|
|||||||
function checkButton(order,className='btn'){
|
function checkButton(order,className='btn'){
|
||||||
const b=button('Abrir e conferir',()=>openCheck(order),className);b.prepend(svgIcon(IC.eye||IC.file,'i m'));return b;
|
const b=button('Abrir e conferir',()=>openCheck(order),className);b.prepend(svgIcon(IC.eye||IC.file,'i m'));return b;
|
||||||
}
|
}
|
||||||
|
function cardOpenAction(order){
|
||||||
|
const action=button('Abrir arquivo',()=>openCheck(order),'card-open');
|
||||||
|
action.prepend(svgIcon(IC.eye||IC.file,'i s'));
|
||||||
|
return action;
|
||||||
|
}
|
||||||
async function openCheck(order){
|
async function openCheck(order){
|
||||||
const {files}=await api('/orders/'+order.id+'/view');
|
const {files}=await api('/orders/'+order.id+'/view');
|
||||||
if(!files.length){say('Ainda não há arquivo para abrir.',true);return;}
|
if(!files.length){say('Ainda não há arquivo para abrir.',true);return;}
|
||||||
openViewer(files,{title:'#'+order.number,onClose:()=>{
|
openViewer(files,{title:'#'+order.number,onClose:()=>{
|
||||||
const now=board.orders.find(o=>o.id===order.id)||order;
|
const now=board.orders.find(o=>o.id===order.id)||order;
|
||||||
if(now.state==='rec'&&!now.cancelled_at&&may('produce')&&mayMove('rec','tra'))isOk(now);}});
|
if(now.state==='rec'&&!now.cancelled_at&&!waitingProof(now)&&may('produce')&&mayMove('rec','tra')){
|
||||||
|
if(openOrder!==order.id)openPanel(order.id);
|
||||||
|
isOk(now);
|
||||||
|
}}});
|
||||||
}
|
}
|
||||||
// "Está OK?" (Dropstar, 2026-10-29): the class of each item, prefilled with
|
// "Está OK?" (Dropstar, 2026-10-29): the class of each item, prefilled with
|
||||||
// the measure, and the art either goes on to Arte conferida, its final
|
// the measure, and the art either goes on to Arte conferida, its final
|
||||||
@@ -1908,6 +1937,7 @@ function itemNote(text,tone=''){
|
|||||||
}
|
}
|
||||||
function itemCard(order,item,index){
|
function itemCard(order,item,index){
|
||||||
const row=(order.print_files||[]).find(r=>r.item_index===index), spec=item.production;
|
const row=(order.print_files||[]).find(r=>r.item_index===index), spec=item.production;
|
||||||
|
const printStatus=row?.timed_out?'failed':row?.status;
|
||||||
const box=node('section',undefined,'item');box.setAttribute('aria-label','Item '+(index+1));
|
const box=node('section',undefined,'item');box.setAttribute('aria-label','Item '+(index+1));
|
||||||
const info=node('div',undefined,'iinfo');
|
const info=node('div',undefined,'iinfo');
|
||||||
const count=order.snapshot.items.length;
|
const count=order.snapshot.items.length;
|
||||||
@@ -1924,19 +1954,22 @@ function itemCard(order,item,index){
|
|||||||
info.append(dl);
|
info.append(dl);
|
||||||
const notes=node('div',undefined,'inotes');
|
const notes=node('div',undefined,'inotes');
|
||||||
if(item.quality_status==='warning')notes.append(itemNote('O cliente aceitou a ressalva de resolução.','warn'));
|
if(item.quality_status==='warning')notes.append(itemNote('O cliente aceitou a ressalva de resolução.','warn'));
|
||||||
if(item.residue_accepted)notes.append(itemNote('Resíduo aceito pelo cliente: '+residueNote(item)+'.','warn'));
|
if(item.residue_accepted)notes.append(itemNote('Resíduo: '+item.residue_accepted+' pontos, aceito pelo cliente'+
|
||||||
|
(item.residue_accepted_at?' às '+when(item.residue_accepted_at):'')+'.','warn'));
|
||||||
if(item.stroke_choice)notes.append(itemNote('Traços finos e áreas chapadas no mesmo arquivo: '+
|
if(item.stroke_choice)notes.append(itemNote('Traços finos e áreas chapadas no mesmo arquivo: '+
|
||||||
(item.stroke_choice==='client_c3'?'o cliente escolheu proteger as áreas chapadas (C3); o traço fino pode sumir em tecido escuro.'
|
(item.stroke_choice==='client_c3'?'o cliente escolheu proteger as áreas chapadas (C3); o traço fino pode sumir em tecido escuro.'
|
||||||
:'o cliente foi avisado e quis imprimir assim mesmo (C1).'),'warn'));
|
:'o cliente foi avisado e quis imprimir assim mesmo (C1).')+
|
||||||
|
(item.stroke_choice_at?' Aceito às '+when(item.stroke_choice_at)+'.':''),'warn'));
|
||||||
if(mirroredItem(item))notes.append(itemNote(MIRROR_NOTE+'.','bad'));
|
if(mirroredItem(item))notes.append(itemNote(MIRROR_NOTE+'.','bad'));
|
||||||
// After a customer correction, that file is the artwork: the generated
|
// After a customer correction, that file is the artwork: the generated
|
||||||
// print file, or the reason it could not be made, no longer applies.
|
// print file, or the reason it could not be made, no longer applies.
|
||||||
const fix=(order.corrections||[]).find(f=>f.item_index===index);
|
const fix=(order.corrections||[]).find(f=>f.item_index===index);
|
||||||
if(fix)notes.append(itemNote('Correção do cliente recebida: '+fix.name,'ok'));
|
if(fix)notes.append(itemNote('Correção do cliente recebida: '+fix.name,'ok'));
|
||||||
else if(!row)notes.append(itemNote('Arquivo de impressão ainda não gerado.'));
|
else if(!row)notes.append(itemNote('Arquivo de impressão ainda não gerado.'));
|
||||||
else if(row.status==='manual'||row.status==='failed'){
|
else if(printStatus==='manual'||printStatus==='failed'){
|
||||||
const call=node('div',undefined,'callout warn'),ico=node('span',undefined,'cico');ico.append(svgIcon(IC.alert,'i m'));
|
const call=node('div',undefined,'callout warn'),ico=node('span',undefined,'cico');ico.append(svgIcon(IC.alert,'i m'));
|
||||||
const p=node('p');p.append(node('b',row.status==='failed'?'Falhou ao gerar. ':'Preparar à mão. '),row.detail?.reason||'Monte a folha a partir do original.');
|
const p=node('p');p.append(node('b',printStatus==='failed'?'Falhou ao gerar'+(row.finished_at||row.timeout_at?' às '+when(row.finished_at||row.timeout_at):'')+'. ':'Preparar à mão. '),
|
||||||
|
row.timed_out?'Tempo limite excedido. Gere de novo.':row.detail?.reason||'Monte a folha a partir do original.');
|
||||||
call.append(ico,p);notes.append(call);
|
call.append(ico,p);notes.append(call);
|
||||||
}else{
|
}else{
|
||||||
const original=row.status==='ready'&&row.detail?.source==='original';
|
const original=row.status==='ready'&&row.detail?.source==='original';
|
||||||
@@ -1956,10 +1989,11 @@ function itemCard(order,item,index){
|
|||||||
const made=generatedFiles(row);
|
const made=generatedFiles(row);
|
||||||
made.forEach((f,k)=>links.append(dl_(made.length>1?'Parte '+(k+1)+' de '+made.length:/\.pdf$/i.test(f.name)?'PDF':'PNG',f.upload_id)));
|
made.forEach((f,k)=>links.append(dl_(made.length>1?'Parte '+(k+1)+' de '+made.length:/\.pdf$/i.test(f.name)?'PDF':'PNG',f.upload_id)));
|
||||||
}
|
}
|
||||||
item.uploads.forEach((uid,i)=>links.append(dl_(item.uploads.length>1?'Original '+(i+1):'Arquivo original',uid)));
|
const originals=node('details',undefined,'originals');originals.append(node('summary','Originais ('+item.uploads.length+')'));
|
||||||
if(spec?.placements){const m=button('Manifesto',()=>manifest(spec,contractionRecord(item,order.contraction?.[index])),'btn');m.prepend(svgIcon(IC.file,'i m'));links.append(m);}
|
item.uploads.forEach((uid,i)=>originals.append(downloadButton('Original '+(i+1),download(uid,order.id),'btn')));
|
||||||
|
links.append(originals);
|
||||||
if(row?.status==='ready')links.prepend(checkButton(order));
|
if(row?.status==='ready')links.prepend(checkButton(order));
|
||||||
if(may('produce')&&!fix&&['rec','tra'].includes(order.state)&&(!row||row.status==='manual'||row.status==='failed')){
|
if(may('produce')&&!fix&&['rec','tra'].includes(order.state)&&!waitingProof(order)&&(!row||row.status==='manual'||row.status==='failed'||row.timed_out)){
|
||||||
const again=button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn');again.prepend(svgIcon(IC.refresh,'i m'));links.append(again);}
|
const again=button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn');again.prepend(svgIcon(IC.refresh,'i m'));links.append(again);}
|
||||||
info.append(links);
|
info.append(links);
|
||||||
box.append(itemPreview(item),info);return box;
|
box.append(itemPreview(item),info);return box;
|
||||||
@@ -1967,6 +2001,14 @@ function itemCard(order,item,index){
|
|||||||
// Arquivos: every final, current or replaced, and the way to send a new one.
|
// Arquivos: every final, current or replaced, and the way to send a new one.
|
||||||
function filesView(order,revisions,view){
|
function filesView(order,revisions,view){
|
||||||
const out=[];
|
const out=[];
|
||||||
|
const layouts=node('div',undefined,'links');
|
||||||
|
order.snapshot.items.forEach((item,index)=>{
|
||||||
|
if(item.production?.placements){
|
||||||
|
const b=button('Manifesto · item '+(index+1),()=>manifest(item.production,contractionRecord(item,order.contraction?.[index])),'btn');
|
||||||
|
b.prepend(svgIcon(IC.file,'i m'));layouts.append(b);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if(layouts.children.length)out.push(layouts);
|
||||||
if(revisions.length){
|
if(revisions.length){
|
||||||
const panel=node('div',undefined,'tpanel');
|
const panel=node('div',undefined,'tpanel');
|
||||||
const table=node('table',undefined,'table');
|
const table=node('table',undefined,'table');
|
||||||
@@ -1984,7 +2026,7 @@ function filesView(order,revisions,view){
|
|||||||
}else out.push(node('p','Nenhum arquivo final ainda.','empty'));
|
}else out.push(node('p','Nenhum arquivo final ainda.','empty'));
|
||||||
// Replacing an approved final, while the art is still in Arte recebida or Correção;
|
// Replacing an approved final, while the art is still in Arte recebida or Correção;
|
||||||
// in Arte conferida, the queue, the order goes back to Arte recebida first.
|
// in Arte conferida, the queue, the order goes back to Arte recebida first.
|
||||||
if(may('produce')&&['rec','cor'].includes(order.state)&&finalDone(order)&&!order.cancelled_at){
|
if(may('produce')&&['rec','cor'].includes(order.state)&&finalDone(order)&&!order.cancelled_at&&!order.proof_parent){
|
||||||
const open=button('Enviar nova versão',async()=>finalDialog(order,readyFinals(order).map(()=>null),{replace:true}),'btn');
|
const open=button('Enviar nova versão',async()=>finalDialog(order,readyFinals(order).map(()=>null),{replace:true}),'btn');
|
||||||
open.prepend(svgIcon(IC.upload,'i m'));open.classList.add('self-start');out.push(open);
|
open.prepend(svgIcon(IC.upload,'i m'));open.classList.add('self-start');out.push(open);
|
||||||
}
|
}
|
||||||
@@ -2045,6 +2087,12 @@ function historyView(order,rows,view){
|
|||||||
};
|
};
|
||||||
for(const r of [...rows].reverse())list.append(entry(r.back?'Voltou para '+stateName(r.to_state):stateName(r.to_state),
|
for(const r of [...rows].reverse())list.append(entry(r.back?'Voltou para '+stateName(r.to_state):stateName(r.to_state),
|
||||||
r.operator+(r.machine?', na '+r.machine:''),r.created_at,r.reason));
|
r.operator+(r.machine?', na '+r.machine:''),r.created_at,r.reason));
|
||||||
|
for(const item of order.snapshot.items){
|
||||||
|
if(item.residue_accepted_at)list.append(entry('Resíduo aceito','cliente',item.residue_accepted_at,
|
||||||
|
item.residue_accepted+' pontos'));
|
||||||
|
if(item.stroke_choice_at)list.append(entry('Traço fino aceito','cliente',item.stroke_choice_at,
|
||||||
|
item.stroke_choice==='client_c3'?'proteger chapado (C3)':'imprimir assim (C1)'));
|
||||||
|
}
|
||||||
list.append(entry('Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento':
|
list.append(entry('Pedido recebido',board.environment==='local'&&order.payment?.provider==='fake'?'pagamento de teste':isTest(order)?'teste, sem pagamento':
|
||||||
paidOutside(order)?ORIGINS[order.origin]+', pago fora do site ('+PAID_OUTSIDE[order.payment.method]+'), registrado por '+order.payment.operator:ORIGINS[order.origin]||'Site',
|
paidOutside(order)?ORIGINS[order.origin]+', pago fora do site ('+PAID_OUTSIDE[order.payment.method]+'), registrado por '+order.payment.operator:ORIGINS[order.origin]||'Site',
|
||||||
order.created_at,paidOutside(order)?order.payment.note:''));
|
order.created_at,paidOutside(order)?order.payment.note:''));
|
||||||
@@ -2111,28 +2159,28 @@ function paintMyMachine(){
|
|||||||
for(const id of ['my-machine','rail-machine'])$(id).onclick=()=>askMachine(true);
|
for(const id of ['my-machine','rail-machine'])$(id).onclick=()=>askMachine(true);
|
||||||
$('account-machine').onclick=()=>{$('account-menu').hidden=true;askMachine(true);};
|
$('account-machine').onclick=()=>{$('account-menu').hidden=true;askMachine(true);};
|
||||||
|
|
||||||
// The order's machine: chosen, or the first that prints its product.
|
// The machine is recorded when the card is pulled into Imprimindo.
|
||||||
function machineCard(order){
|
function machineCard(order){
|
||||||
const box=node('div',undefined,'fact');box.append(node('span','Máquina','lbl'));
|
const box=node('div',undefined,'fact');box.append(node('span','Máquina','lbl'));
|
||||||
const current=order.machine;
|
const current=order.machine;
|
||||||
|
const pulled=order.machine_pulled;
|
||||||
|
const detail=pulled?'Puxada por '+pulled.by+' em '+when(pulled.at):current?'Escolhida para este pedido':'Definida quando alguém puxar o card';
|
||||||
// The operator's orders go to the machine that pulls them (item 12).
|
// The operator's orders go to the machine that pulls them (item 12).
|
||||||
if(!may('print')||ME?.role==='operador'||!board.machines?.length){
|
if(!may('print')||ME?.role==='operador'||!board.machines?.length||waitingProof(order)||!['rec','tra','cor'].includes(order.state)){
|
||||||
box.append(node('b',current?current.name:'Nenhuma máquina cadastrada'),
|
box.append(node('b',current?current.name:'Aguardando máquina'),node('span',detail));
|
||||||
node('span',current?.chosen?'Escolhida para este pedido':current?'Escolhida automaticamente':'Nenhuma máquina imprime este produto'));
|
|
||||||
return box;
|
return box;
|
||||||
}
|
}
|
||||||
const select=node('select');select.setAttribute('aria-label','Máquina do pedido');
|
const select=node('select');select.setAttribute('aria-label','Máquina do pedido');
|
||||||
const auto=node('option','Automática'+(current&&!current.chosen?' ('+current.name+')':''));auto.value='';select.append(auto);
|
const auto=node('option','Sem máquina');auto.value='';select.append(auto);
|
||||||
const family=order.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv')?'uv':'textil';
|
const family=order.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv')?'uv':'textil';
|
||||||
for(const m of board.machines.filter(m=>m.active&&m.products.includes(family)||m.id===current?.id)){
|
for(const m of board.machines.filter(m=>m.active&&m.products.includes(family)||m.id===current?.id)){
|
||||||
const o=node('option',m.name+', '+machineLoad(m));o.value=m.id;select.append(o);
|
const o=node('option',m.name+', '+machineLoad(m));o.value=m.id;select.append(o);
|
||||||
}
|
}
|
||||||
select.value=current?.chosen?current.id:'';
|
select.value=current?.id||'';
|
||||||
select.onchange=async()=>{try{await api('/orders/'+order.id+'/machine',{machine_id:select.value||null});
|
select.onchange=async()=>{try{await api('/orders/'+order.id+'/machine',{machine_id:select.value||null});
|
||||||
say(select.value?'Pedido enviado para '+select.selectedOptions[0].textContent+'.':'Máquina automática pelo produto.');await load();}
|
say(select.value?'Pedido enviado para '+select.selectedOptions[0].textContent+'.':'O pedido aguarda uma máquina.');await load();}
|
||||||
catch(e){say(e.message,true);}};
|
catch(e){say(e.message,true);}};
|
||||||
box.append(node('b',current?current.name:'Nenhuma'),
|
box.append(node('b',current?current.name:'Aguardando máquina'),node('span',detail),select);
|
||||||
node('span',current?.chosen?'Escolhida para este pedido':current?'Escolhida automaticamente quando o pedido chegou':'Nenhuma máquina imprime este produto'),select);
|
|
||||||
return box;
|
return box;
|
||||||
}
|
}
|
||||||
// "120,00 m de 300,00 m" or "120,00 m em aberto".
|
// "120,00 m de 300,00 m" or "120,00 m em aberto".
|
||||||
@@ -2513,6 +2561,17 @@ async function loadStats(){
|
|||||||
tr.append(name,node('td',st?duration(st.median_hours):'—','r strong'),
|
tr.append(name,node('td',st?duration(st.median_hours):'—','r strong'),
|
||||||
node('td',now?plural(now.orders,'pedido','pedidos')+', o mais antigo há '+duration(now.oldest_hours):'nenhum','muted'));
|
node('td',now?plural(now.orders,'pedido','pedidos')+', o mais antigo há '+duration(now.oldest_hours):'nenhum','muted'));
|
||||||
return tr;}));
|
return tr;}));
|
||||||
|
// Speed (item 0.12): average and p95 of what the customer feels.
|
||||||
|
const secs=v=>v==null?'—':v<60?Math.max(1,Math.round(v))+' s':Math.round(v/60)+' min';
|
||||||
|
const speedFmt=s=>s.unit==='MB/s'
|
||||||
|
? (v=>v==null?'—':v.toFixed(1).replace('.',',')+' MB/s')
|
||||||
|
: (v=>s.unit==='s'?secs(v):String(v));
|
||||||
|
$('stats-speed').replaceChildren(...(data.speed||[]).map(s=>{
|
||||||
|
const tr=node('tr'),fmt=speedFmt(s);
|
||||||
|
tr.append(node('td',s.label),node('td',fmt(s.average),'r'),node('td',fmt(s.p95),'r'),
|
||||||
|
node('td',String(s.samples),'r'));
|
||||||
|
if(!s.samples)tr.classList.add('off');
|
||||||
|
return tr;}));
|
||||||
}
|
}
|
||||||
const emptyRow=(text,span)=>{const tr=node('tr');const td=node('td',text,'empty');td.colSpan=span;tr.append(td);return tr;};
|
const emptyRow=(text,span)=>{const tr=node('tr');const td=node('td',text,'empty');td.colSpan=span;tr.append(td);return tr;};
|
||||||
// Metres per day: one series of columns from one baseline, the period's
|
// Metres per day: one series of columns from one baseline, the period's
|
||||||
@@ -2804,8 +2863,9 @@ function quoteItem(item,fields,priced,index=0,count=1){
|
|||||||
grid.append(m,gr);info.append(grid);
|
grid.append(m,gr);info.append(grid);
|
||||||
}
|
}
|
||||||
const links=node('div',undefined,'links');
|
const links=node('div',undefined,'links');
|
||||||
item.uploads.forEach((uid,i)=>links.append(downloadButton(item.uploads.length>1?'Original '+(i+1):'Arquivo original',download(uid),'btn')));
|
const originals=node('details',undefined,'originals');originals.append(node('summary','Originais ('+item.uploads.length+')'));
|
||||||
if(spec?.placements){const b=button('Manifesto',()=>manifest(spec,contractionRecord(item)),'btn');b.prepend(svgIcon(IC.file,'i m'));links.append(b);}
|
item.uploads.forEach((uid,i)=>originals.append(downloadButton('Original '+(i+1),download(uid,order.id),'btn')));
|
||||||
|
links.append(originals);
|
||||||
info.append(links);box.append(tall,info);return box;
|
info.append(links);box.append(tall,info);return box;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -123,7 +123,7 @@ function carrinho(){
|
|||||||
localFiles:f.artes.map(x=>x.f), fotos:f.artes.map(x=>x.fotoSrc||null),
|
localFiles:f.artes.map(x=>x.f), fotos:f.artes.map(x=>x.fotoSrc||null),
|
||||||
metros:+(f.layout.height_cm/100).toFixed(4),
|
metros:+(f.layout.height_cm/100).toFixed(4),
|
||||||
production:{version:3,film_width_cm:larguraFilme(),sources:f.artes.map(fonteDaArte),...f.layout},
|
production:{version:3,film_width_cm:larguraFilme(),sources:f.artes.map(fonteDaArte),...f.layout},
|
||||||
residueAccepted:residuosDasArtes(f.artes), ...tracoDoItem(f.artes)}));
|
residueAccepted:residuosDasArtes(f.artes), ...tracoDoItem(f.artes,f.layout)}));
|
||||||
layout=null;
|
layout=null;
|
||||||
}else{
|
}else{
|
||||||
if(!montagemLayout) return;
|
if(!montagemLayout) return;
|
||||||
@@ -144,7 +144,7 @@ function carrinho(){
|
|||||||
residueAccepted:residuosAceitos(),
|
residueAccepted:residuosAceitos(),
|
||||||
// The thinnest stroke and its contraction class (item 9), for the room.
|
// The thinnest stroke and its contraction class (item 9), for the room.
|
||||||
...tracoDoItem(),
|
...tracoDoItem(),
|
||||||
desc:(partes?partes.length+' folhas · ':'')+fmtM(cob)+' m · '+rs(unit)+'/m · nota '+nota};
|
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,12 @@
|
|||||||
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);
|
||||||
|
// 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 +73,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.
|
||||||
|
|||||||
@@ -493,6 +493,8 @@ 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.
|
||||||
@@ -505,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);
|
||||||
@@ -453,9 +463,7 @@ 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. Só na arte avulsa (Dropstar, 03/11/2026): a folha pronta
|
|
||||||
// com resíduo volta, porque o designer não limpa folha fechada.
|
|
||||||
function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
|
function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
|
||||||
if(a.grande) return '';
|
if(a.grande) return '';
|
||||||
if(a.fundoChapado) return /\.jpe?g$/i.test(nome||'')
|
if(a.fundoChapado) return /\.jpe?g$/i.test(nome||'')
|
||||||
@@ -466,8 +474,7 @@ function avisosDaFolha(a,nome,i,aceito,aceitavel=false){
|
|||||||
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(aceitavel && aceito) return aceite;
|
||||||
return '<p class="avisoF"><b>'+(varios?'Sobraram ':'Sobrou ')+n+(varios?' pontos':' ponto')+
|
return '<p class="avisoF"><b>'+(varios?'Sobraram ':'Sobrou ')+n+(varios?' pontos':' ponto')+
|
||||||
' de recorte na sua folha.</b> São restos da remoção de fundo: não aparecem na sua tela, mas a '+
|
' de recorte na sua folha.</b> São restos da remoção de fundo: não aparecem na sua tela, mas a '+
|
||||||
@@ -505,7 +512,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).
|
||||||
@@ -736,14 +743,9 @@ function resumoArtes(){
|
|||||||
if(!prontas.length){ r.style.display='none'; return; }
|
if(!prontas.length){ r.style.display='none'; return; }
|
||||||
const m=montagemCm/100; // a mesma folha que aparece ao lado
|
const m=montagemCm/100; // a mesma folha que aparece ao lado
|
||||||
const cob=montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(m);
|
const cob=montagemFolhas ? cobrarFolhas(montagemFolhas) : cobrar(m);
|
||||||
const notas=prontas.map(a=>Math.max(6,Math.min(100,Math.round(dpiDe(a)/300*100))));
|
|
||||||
const media=Math.round(notas.reduce((s,n)=>s+n,0)/notas.length), pior=Math.min(...notas);
|
|
||||||
const 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:'+
|
|
||||||
(media>=85?'var(--verde)':media>=50?'var(--laranja)':'var(--vermelho)')+'">'+media+'%</b></div>'+
|
|
||||||
(pior<media?'<div class="r"><span>a pior arte</span><b>'+pior+'%</b></div>':'')+
|
|
||||||
(m>0?'<div class="r"><span>'+(montagemFolhas?montagemFolhas.length+' folhas montadas':'folha montada')+'</span><b>'+fmtM(m)+' m</b></div>'+
|
(m>0?'<div class="r"><span>'+(montagemFolhas?montagemFolhas.length+' folhas montadas':'folha montada')+'</span><b>'+fmtM(m)+' m</b></div>'+
|
||||||
(cob>m+0.001?'<div class="r"><span>cobrança</span><b>'+fmtM(cob)+
|
(cob>m+0.001?'<div class="r"><span>cobrança</span><b>'+fmtM(cob)+
|
||||||
' m'+(cob===MINIMO_M?' · mínimo':'')+'</b></div>':''):'')+
|
' m'+(cob===MINIMO_M?' · mínimo':'')+'</b></div>':''):'')+
|
||||||
|
|||||||
@@ -7,8 +7,7 @@
|
|||||||
// 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.
|
||||||
// A folha pronta não aceita resíduo (Dropstar, 03/11/2026): só a arte avulsa.
|
const residuoAceito=x=>!!x.residuoAceito;
|
||||||
const residuoAceito=()=>false;
|
|
||||||
const folhaBarrada=x=>!!(x.an && !x.an.grande && (x.an.fundoChapado || (x.an.residuos && !residuoAceito(x))));
|
const folhaBarrada=x=>!!(x.an && !x.an.grande && (x.an.fundoChapado || (x.an.residuos && !residuoAceito(x))));
|
||||||
// Quantos pontos o cliente aceitou imprimir, somadas as folhas: vai no item.
|
// Quantos pontos o cliente aceitou imprimir, somadas as folhas: vai no item.
|
||||||
// the sheet of loose art inherits what each artwork accepted
|
// the sheet of loose art inherits what each artwork accepted
|
||||||
@@ -37,29 +36,50 @@ function perguntaMista(){
|
|||||||
const lista=ehFolha()?folhas:artes;
|
const lista=ehFolha()?folhas:artes;
|
||||||
const x=lista.find(y=>!y.mistaVista && mista(tracoDoArquivo(y)));
|
const x=lista.find(y=>!y.mistaVista && mista(tracoDoArquivo(y)));
|
||||||
if(!x) return;
|
if(!x) return;
|
||||||
x.mistaVista=true;
|
|
||||||
$('mistaTit').textContent=x.f.name;
|
$('mistaTit').textContent=x.f.name;
|
||||||
$('mistaTxt').textContent=ehFolha()?TEXTO_MISTA.folha:TEXTO_MISTA.arte;
|
$('mistaTxt').textContent=ehFolha()?TEXTO_MISTA.folha:TEXTO_MISTA.arte;
|
||||||
$('mistaSep').onclick=()=>{ dlg.close(); const i=lista.indexOf(x);
|
$('mistaSep').onclick=()=>{ dlg.close(); const i=lista.indexOf(x);
|
||||||
if(i>=0){ lista.splice(i,1); ehFolha()?pintaFolha():pintaArtes(); } $('inp').click(); };
|
if(i>=0){ lista.splice(i,1); ehFolha()?pintaFolha():pintaArtes(); } $('inp').click(); };
|
||||||
$('mistaSegue').onclick=()=>{ dlg.close(); agendaAvaliacao(); };
|
$('mistaSegue').onclick=()=>{ x.mistaVista=true; dlg.close(); agendaAvaliacao(); };
|
||||||
dlg.showModal();
|
dlg.showModal();
|
||||||
}
|
}
|
||||||
// O traço mais fino do item (item 9, Dropstar 30/10/2026): o menor entre as
|
// 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,
|
// 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.
|
// que confere a classe de contração ao aprovar o arquivo final.
|
||||||
function tracoDoItem(lista){
|
// 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 arquivos=lista||(ehFolha()?folhas:artes);
|
||||||
const medidas=arquivos.map(x=>lista?tracoDaArte(x):tracoDoArquivo(x)).filter(Boolean);
|
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};
|
if(!medidas.length) return {strokePx:null, strokeClass:null, strokeChoice:null};
|
||||||
const fino=medidas.reduce((a,b)=>b.px<a.px?b:a);
|
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.
|
// 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)));
|
const avisado=arquivos.some(x=>x.mistaVista && mista(lista?tracoDaArte(x):tracoDoArquivo(x)));
|
||||||
return {strokePx:fino.px, strokeClass:fino.classe, strokeChoice:avisado?'measured':null};
|
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);
|
||||||
@@ -78,7 +98,7 @@ function avaliar(){
|
|||||||
if(barrada) return {pronto:false, falta:barrada.an.fundoChapado
|
if(barrada) return {pronto:false, falta:barrada.an.fundoChapado
|
||||||
? barrada.f.name+' está sem fundo transparente. Exporte a folha com fundo transparente, em PNG ou PDF, e envie de novo.'
|
? barrada.f.name+' está sem fundo transparente. Exporte a folha com fundo transparente, em PNG ou PDF, e envie de novo.'
|
||||||
: barrada.f.name+' tem '+barrada.an.residuos+' ponto'+(barrada.an.residuos>1?'s':'')+
|
: barrada.f.name+' tem '+barrada.an.residuos+' ponto'+(barrada.an.residuos>1?'s':'')+
|
||||||
' de recorte. Apague e envie de novo.'};
|
' de recorte. Apague e envie de novo, ou marque que aceita imprimir assim.'};
|
||||||
metros=folhaTotalM();
|
metros=folhaTotalM();
|
||||||
setTimeout(perguntaMista);
|
setTimeout(perguntaMista);
|
||||||
reencaixado=false;
|
reencaixado=false;
|
||||||
@@ -145,7 +165,7 @@ function avaliar(){
|
|||||||
// 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'],
|
||||||
@@ -211,7 +231,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;
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ function novoMapa(wPx,hPx,larguraCm){
|
|||||||
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))};
|
traco:novoTraco(wPx,wPx/(larguraCm/2.54),hPx)};
|
||||||
}
|
}
|
||||||
// ── Traço mais fino (Dropstar, 30/10/2026): a contração do Flexi vem dele.
|
// ── 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
|
// Tinta é alfa acima de 40; a distância de cada pixel de tinta ao fundo sai de
|
||||||
@@ -89,13 +89,14 @@ function tintaPerto(t,lim,r,de,ate){
|
|||||||
// O contexto de cada faixa: as linhas acima e abaixo que ela lê sem medir. Um
|
// 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
|
// 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.
|
// a faixa sempre o vê inteiro; o que encosta na borda cortada é traço.
|
||||||
function novoTraco(wPx,dpi){
|
function novoTraco(wPx,dpi,hPx){
|
||||||
const cisco=Math.ceil(TRACO_CISCO*(dpi/300)**2), ctx=Math.min(120,Math.max(TRACO_D,cisco));
|
const cisco=Math.ceil(TRACO_CISCO*(dpi/300)**2), ctx=Math.min(120,Math.max(TRACO_D,cisco));
|
||||||
const linhas=TRACO_FAIXA+2*ctx;
|
const linhas=TRACO_FAIXA+2*ctx;
|
||||||
return {w:wPx,dpi,linhas,ctx,cisco,tinta:new Uint8Array(wPx*linhas),dist:new Uint16Array(wPx*linhas),
|
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),
|
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),
|
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};
|
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
|
// 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.
|
// 30 px não são traço e saem antes da distância. Vizinhos nas oito direções.
|
||||||
@@ -183,7 +184,9 @@ function tracoFaixa(t,fim){
|
|||||||
// conta, na última faixa, ou dois pixels soltos de borda viram o menor
|
// 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
|
// traço de uma arte toda chapada. O comprimento do eixo é cerca de metade
|
||||||
// do contorno da região além do limite.
|
// do contorno da região além do limite.
|
||||||
if(d>=CAP){ if(at(x-1,y)<CAP||at(x+1,y)<CAP||at(x,y-1)<CAP||at(x,y+1)<CAP){hist[max]+=0.5;t.total+=0.5;} continue; }
|
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
|
// 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.
|
// de um canto sempre há um vizinho mais fundo, e o canto não conta.
|
||||||
let iguais=0, eixo=true;
|
let iguais=0, eixo=true;
|
||||||
@@ -197,7 +200,8 @@ function tracoFaixa(t,fim){
|
|||||||
// Largura par: o eixo tem dois pixels, e os iguais passam de dois.
|
// 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 larg=iguais>=4?2*d/10:2*d/10-1;
|
||||||
const i=Math.max(1,Math.min(max,Math.round(larg*escala)));
|
const i=Math.max(1,Math.min(max,Math.round(larg*escala)));
|
||||||
hist[i]++;t.total++;
|
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.
|
// As últimas linhas ficam como contexto da próxima faixa.
|
||||||
if(!fim){
|
if(!fim){
|
||||||
@@ -216,8 +220,18 @@ function tracoFim(t){
|
|||||||
if(!t.total) return t.lido=null;
|
if(!t.total) return t.lido=null;
|
||||||
let soma=0, px=1;
|
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; } }
|
for(let i=1;i<t.hist.length;i++){ soma+=t.hist[i]; if(soma>=t.total*0.01){ px=i; break; } }
|
||||||
// largos: a parte da tinta em áreas chapadas, de 20 px ou mais (item 16)
|
// Choose the 15 cm stretch with the finest 1st-percentile stroke.
|
||||||
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};
|
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){
|
||||||
@@ -306,4 +320,3 @@ function analisarMapa(m){
|
|||||||
traco: m.traco ? tracoFim(m.traco) : null
|
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
|
||||||
@@ -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){
|
||||||
@@ -267,7 +283,8 @@ function analiseDaArte(a){
|
|||||||
function tracoDaArte(a){
|
function tracoDaArte(a){
|
||||||
if(!a.tracoPx || !(a.cm>0)) return null;
|
if(!a.tracoPx || !(a.cm>0)) return null;
|
||||||
const px=Math.max(1,Math.round(a.tracoPx.px*300/dpiDe(a)));
|
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};
|
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
|
||||||
|
|||||||
Reference in New Issue
Block a user