diff --git a/app/api/artwork.py b/app/api/artwork.py index 7b650d9..8a49182 100644 --- a/app/api/artwork.py +++ b/app/api/artwork.py @@ -8,6 +8,7 @@ from uuid import UUID from fastapi import APIRouter, Depends, HTTPException from ..core import db +from .. import proof from ..artwork import submit_files from ..core.auth import can, operator from ..core.models import ArtworkSubmission, UploadStart @@ -18,9 +19,14 @@ router = APIRouter() @router.post('/api/operator/orders/{oid}/uploads') def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))): + if not body.name.lower().endswith('.png'): + raise HTTPException(422, 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.') with db.connect() as c: - row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone() + row = c.execute('SELECT id,state,parent_id,proof_ok_at FROM dtf_local.orders WHERE id=%s', (oid,)).fetchone() if not row: raise HTTPException(404, 'Order not found') + if row['parent_id']: + raise HTTPException(409, 'A prova recebe o PNG final automaticamente.') + proof.require_unlocked(c, row) if row['state'] not in ('rec','cor'): raise HTTPException(409, 'Order is not in artwork review') return begin_upload(body, session_id=operator_identity(user)) @@ -52,4 +58,7 @@ def final_files(oid: UUID, body: ArtworkSubmission, user=Depends(can('produce')) with db.connect() as c: order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (oid,)).fetchone() if not order: raise HTTPException(404, 'Order not found') + if order['parent_id']: + raise HTTPException(409, 'O arquivo final da prova é gerado automaticamente. Use Gerar de novo se falhar.') + proof.require_unlocked(c, order) return submit_files(c,order,body,operator_identity(user),'final',user) diff --git a/app/api/operator.py b/app/api/operator.py index 4dca8f3..c757aec 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -17,7 +17,7 @@ from ..core import db from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can, client_ip, operator, login_failed, may_move, may_reorder, password_matches, throttle) 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 tiny 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') def board(user=Depends(operator)): 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 # 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. 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). - finished = c.execute("""SELECT * FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL - ORDER BY created_at DESC LIMIT %s""", (BOARD_FINISHED_LIMIT,)).fetchall() + finished = c.execute('''SELECT * FROM ( + SELECT o.*, COALESCE((SELECT max(m.created_at) FROM dtf_local.movements m + WHERE m.order_id=o.id AND m.to_state='fin' AND NOT m.back), o.updated_at) AS finished_at + FROM dtf_local.orders o WHERE o.state='fin' AND o.parent_id IS NULL + ) f ORDER BY finished_at DESC,id DESC LIMIT %s''', (BOARD_FINISHED_LIMIT,)).fetchall() finished_total = c.execute("SELECT count(*) AS n FROM dtf_local.orders WHERE state='fin' AND parent_id IS NULL").fetchone()['n'] pending = c.execute(f'''SELECT q.* FROM dtf_local.quotes q 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 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'] - 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 # for nothing the factory will make. The board carries the count; the # Pagamentos tab pages through them until someone records a resolution. @@ -192,16 +193,20 @@ TREATED = """f.kind='final' def assign_machines(c, orders): - """Each order's machine as stored (app/machines.py gives it): chosen by - someone, or automatic. None while no machine prints its product. In - Imprimindo, also which of its machine's two places it holds.""" + """Each machine, its pull attribution, and its printing place.""" names = {str(m['id']): m['name'] for m in c.execute('SELECT id,name FROM dtf_local.machines').fetchall()} 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: key = str(order.get('machine_id') or '') order['machine'] = ({'id': key, 'name': names[key], 'chosen': bool(order.get('machine_chosen'))} if key in names else None) 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 @@ -209,9 +214,11 @@ def with_print_files(c, orders): """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.""" 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 limit, 'thumbnails': thumbnails(c, orders), 'names': company_names(c, orders)} @@ -681,23 +691,34 @@ class MachineChoice(StrictModel): @router.post('/api/operator/orders/{uid}/machine') 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). - Not the operator: their pull makes an order their machine's (item 12).""" + """Exceptional manual choice before printing; the operator's pull is final.""" if request.state.operator['role'] == 'operador': raise HTTPException(403, 'A máquina do pedido é a de quem puxa para Imprimindo.') 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(): - raise HTTPException(404, 'Máquina não encontrada.') + current = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() + 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 RETURNING number, state, cancelled_at''', (body.machine_id, body.machine_id is not None, uid)).fetchone() - if not row: - raise HTTPException(404, 'Pedido não encontrado.') - machines.route(c) - # Printing already: the machine it goes to must have a place in Imprimindo. - if row['state'] == 'imp' and not row['cancelled_at']: - now = c.execute('SELECT machine_id FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() - if name := machines.full(c, now['machine_id'], uid): - raise HTTPException(409, f'{name} já tem {machines.PRINTING_CAP} em Imprimindo.') + if current['parent_id']: + c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s', + (body.machine_id, body.machine_id is not None, current['parent_id'])) + elif linked and linked['proof_result'] is None and linked['state'] in ('rec', 'tra', 'cor'): + c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=%s WHERE id=%s', + (body.machine_id, body.machine_id is not None, linked['id'])) audit('order_machine_chosen', order=row['number'], machine=str(body.machine_id or ''), operator=user) 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 the order prints. Both stay: the measure in the snapshot, the choice here.""" with db.connect() as c: - row = c.execute('SELECT snapshot,state,cancelled_at,contraction FROM dtf_local.orders WHERE id=%s FOR UPDATE', + row = c.execute('SELECT id,parent_id,proof_ok_at,snapshot,state,cancelled_at,contraction FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone() if not row: raise HTTPException(404, 'Pedido não encontrado.') + proof.require_unlocked(c, row) if body.item_index >= len(row['snapshot']['items']): raise HTTPException(422, 'Item não encontrado no pedido.') # Printing, the class still changes while the item's files wait to go @@ -799,6 +821,7 @@ def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))): # Back to Arte recebida with the reason; its final is approved again. c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (parent['id'],)) c.execute('''UPDATE dtf_local.orders SET state='rec', proof_ok_at=NULL, proof_ok_by=NULL, queue_key=NULL, + machine_id=NULL,machine_chosen=false, version=version+1, updated_at=now() WHERE id=%s''', (parent['id'],)) c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) VALUES(%s,%s,'rec',%s,%s)''', (parent['id'], parent['state'], user, label)) @@ -819,7 +842,6 @@ def new_proof_card(uid: UUID, user=Depends(can('produce'))): child = proof.create_child(c, row) if not child: raise HTTPException(409, 'Este pedido não leva prova.') - machines.route(c) audit('order_proof_card', order=row['number'], operator=user) return {'ok': True, 'id': child['id'], 'number': child['number']} @@ -956,9 +978,10 @@ def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(oper if not body.after and not body.before: raise HTTPException(422, 'Informe entre quais pedidos ele fica.') 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: raise HTTPException(404, 'Order not found') + proof.require_unlocked(c, row) if not may_reorder(request.state.operator['role'], row['state']): raise HTTPException(403, 'Seu perfil não muda a ordem dos pedidos desta etapa.') mine = request.state.operator['machine'] @@ -996,6 +1019,7 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)): raise HTTPException(409, 'O pedido mudou. Clique em Atualizar.') if row.get('cancelled_at'): raise HTTPException(409, 'Pedido cancelado.') + proof.require_unlocked(c, row) if body.state == row['state']: return row back = BACK.get(row['state']) == body.state @@ -1008,9 +1032,8 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)): raise HTTPException(422, 'Informe o motivo da correção.') if back and not body.reason.strip(): 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 - # makes it that machine's ("a máquina real do card é a que puxou"); an - # operator pulls any card but moves only their machine's. + # The machine of this session takes a card when it is pulled. A proof + # and its parent must keep the same physical machine. account = request.state.operator session_machine = account['machine'] pulling = row['state'] == 'tra' and body.state == 'imp' @@ -1019,29 +1042,26 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)): raise HTTPException(409, 'Escolha a máquina em que você está.') 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.') - # Dropped on a machine's lane in Imprimindo: that machine, when it - # prints the product. The operator's pull stays their machine's. - if pulling and body.machine_id: - if account['role'] == 'operador': - if str(body.machine_id) != session_machine['id']: - raise HTTPException(409, f"Você está na {session_machine['name']}: o que você puxa vai para ela.") - else: - target = c.execute('SELECT name, products, active FROM dtf_local.machines WHERE id=%s', - (body.machine_id,)).fetchone() - if not target or not target['active']: - raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.') - if machines.product_family(row) not in target['products']: - raise HTTPException(409, f"A {target['name']} não imprime este produto.") - row['machine_id'] = body.machine_id - c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=true WHERE id=%s', (body.machine_id, uid)) - if pulling and session_machine and not body.machine_id and (account['role'] == 'operador' or not row['machine_chosen']): - prints = c.execute('SELECT products FROM dtf_local.machines WHERE id=%s', (session_machine['id'],)).fetchone() - if machines.product_family(row) in (prints or {}).get('products', []): - row['machine_id'] = session_machine['id'] - c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=true WHERE id=%s', - (session_machine['id'], uid)) - elif account['role'] == 'operador': - raise HTTPException(409, f"A {session_machine['name']} não imprime este produto.") + if pulling: + chosen = body.machine_id or (UUID(session_machine['id']) if session_machine else row['machine_id']) + if not chosen: + raise HTTPException(409, 'Escolha a máquina que está puxando este card.') + if account['role'] == 'operador' and str(chosen) != session_machine['id']: + raise HTTPException(409, f"Você está na {session_machine['name']}: o que você puxa vai para ela.") + target = c.execute('SELECT name,products,active FROM dtf_local.machines WHERE id=%s', (chosen,)).fetchone() + if not target or not target['active']: + raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.') + if machines.product_family(row) not in target['products']: + raise HTTPException(409, f"A {target['name']} não imprime este produto.") + linked = c.execute('''SELECT machine_id FROM dtf_local.orders WHERE parent_id=%s + AND proof_result='ok' AND cancelled_at IS NULL ORDER BY created_at DESC LIMIT 1''', (uid,)).fetchone() + if linked and linked['machine_id'] and chosen != linked['machine_id']: + raise HTTPException(409, 'Puxe o pedido na mesma máquina que imprimiu a prova.') + row['machine_id'] = chosen + c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s', (chosen, uid)) + if row['parent_id']: + c.execute('UPDATE dtf_local.orders SET machine_id=%s,machine_chosen=true WHERE id=%s', + (chosen, row['parent_id'])) # Arte conferida is the queue: what enters it has its final files approved. if body.state in ('tra','imp'): coverage = c.execute(f'''SELECT DISTINCT f.item_index FROM dtf_local.order_files f @@ -1077,9 +1097,10 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)): hotfolder.start(c, uid) # A pickup reaching Finalizado has its receipt due (item 14), once. 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 - 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"; # Finalizado its "Pronto para envio" (Dropstar's flow, 2026-10-23). events = {'tra':'production_started','cor':'correction_needed','fin':'ready'} @@ -1104,9 +1125,10 @@ def regenerate(uid: UUID, user=Depends(can('produce'))): """Queue generation again for items that failed or went to manual preparation, and for orders paid before the generator existed.""" 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: raise HTTPException(404, 'Order not found') + proof.require_unlocked(c, row) if row['state'] not in ('rec','tra'): 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(): @@ -1634,7 +1656,7 @@ def queue_folder(body: FolderSync, user=Depends(can('print'))): @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: row = c.execute('SELECT * FROM dtf_local.uploads WHERE id=%s AND complete', (uid,)).fetchone() if not row: @@ -1642,4 +1664,15 @@ def download(uid: UUID, user=Depends(operator)): if row['expires_at'] <= datetime.now(timezone.utc): raise HTTPException(410, 'Artwork retention expired') 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} diff --git a/app/api/users.py b/app/api/users.py index 6c6a040..16eb4d0 100644 --- a/app/api/users.py +++ b/app/api/users.py @@ -231,7 +231,6 @@ def create_machine(body: MachineIn, user=Depends(can('users'))): raise HTTPException(409, 'Já existe uma máquina com este nome.') c.execute('INSERT INTO dtf_local.machines(id,name,products,active,limit_metres) VALUES(%s,%s,%s,%s,%s)', (mid, body.name.strip(), sorted(set(body.products)), body.active, body.limit_metres)) - machines.route(c) audit('machine_created', operator=user, machine=body.name) return {'id': str(mid)} @@ -248,20 +247,21 @@ def update_machine(mid: UUID, body: MachineIn, user=Depends(can('users'))): raise HTTPException(404, 'Máquina não encontrada.') if not body.active: release_sessions(c, mid) - machines.route(c) audit('machine_updated', operator=user, machine=body.name) return {'ok': True} @router.post('/api/operator/machines/{mid}/delete') def delete_machine(mid: UUID, user=Depends(can('users'))): - """Its orders go back to the automatic choice; its operators lose it.""" + """Its orders lose that machine; its operators lose the session choice.""" with db.connect() as c: + if c.execute("SELECT 1 FROM dtf_local.orders WHERE machine_id=%s AND state='imp' AND cancelled_at IS NULL LIMIT 1", + (mid,)).fetchone(): + raise HTTPException(409, 'Há pedido imprimindo nesta máquina. Termine ou mova o pedido antes de excluí-la.') release_sessions(c, mid) row = c.execute('DELETE FROM dtf_local.machines WHERE id=%s RETURNING name', (mid,)).fetchone() if not row: raise HTTPException(404, 'Máquina não encontrada.') - machines.route(c) audit('machine_deleted', operator=user, machine=row['name']) return {'ok': True} diff --git a/app/artwork.py b/app/artwork.py index 95b3eac..281088f 100644 --- a/app/artwork.py +++ b/app/artwork.py @@ -9,7 +9,8 @@ from uuid import UUID, uuid4 from fastapi import HTTPException -from .runtime import upload_row +from .runtime import upload_row, storage +from .printpng_validate import require_final_png from .scanning import require_clean @@ -84,6 +85,8 @@ def submit_files(c, order, body, identity, kind, actor): if not upload['complete']: raise HTTPException(409, 'Espere o envio de todos os arquivos terminar.') require_clean(upload) + if kind == 'final': + require_final_png(storage, upload) # Attached once, except a correction approved as its own final. if c.execute('SELECT id FROM dtf_local.order_files WHERE upload_id=%s'+(" AND kind<>'correction'" if corrected else ''), (ref.upload_id,)).fetchone(): diff --git a/app/machines.py b/app/machines.py index a9dcb8d..eb89e8c 100644 --- a/app/machines.py +++ b/app/machines.py @@ -1,20 +1,8 @@ -"""The print machines: which one each order goes to, and how loaded each is. - -An order gets its machine once, and keeps it: someone's choice in the order -panel, or else the active machine that prints its product with the fewest -metres still open, among those below their limit (or, all of them full, the -least loaded anyway; the machine then shows it is over its limit). A machine -switched off, deleted or no longer printing the product gives its automatic -orders back to that choice, unless they are already printing. -""" +"""The print machines, their load and the two printing places on each one.""" from decimal import Decimal # Not finished: the work still ahead of a machine. OPEN = ('rec', 'tra', 'imp', 'cor') -# Stages an automatic order may still move from: not once it is printing. -MOVABLE = ('rec', 'tra', 'cor') -# One routing at a time, so two at once cannot both pick the same "least loaded". -LOCK = 7_041_901 # Two orders at most in Imprimindo per machine (Dropstar, 2026-10-29): one # printing, the next being ripped by FlexiPRINT meanwhile. A third would # make the RIP choke; two mean the next sheet is ready when one ends. @@ -44,49 +32,6 @@ def loads(c): return result -def pick(machines, load, order): - """The machine for one order, or None when none prints its product.""" - family, metres = product_family(order), order_metres(order) - able = [m for m in machines if m['active'] and family in m['products']] - if not able: - return None - used = lambda m: load.get(str(m['id']), Decimal(0)) - room = [m for m in able if m['limit_metres'] is None or used(m) + metres <= m['limit_metres']] - # min() keeps the first of equals: the machine registered first. - return min(room or able, key=used) - - -def route(c): - """Give every open order without a machine its automatic one.""" - # A choice whose machine was deleted is no choice any more. - c.execute('UPDATE dtf_local.orders SET machine_chosen=false WHERE machine_id IS NULL AND machine_chosen') - # Automatic orders on a machine that can no longer take them, before printing. - c.execute('''UPDATE dtf_local.orders o SET machine_id=NULL FROM dtf_local.machines m - WHERE o.machine_id=m.id AND NOT o.machine_chosen AND o.state=ANY(%s) AND o.cancelled_at IS NULL - AND (NOT m.active OR NOT ((CASE WHEN o.snapshot->'items'->0->>'mode' IN ('uv','uvfile') - THEN 'uv' ELSE 'textil' END)=ANY(m.products)))''', (list(MOVABLE),)) - waiting = c.execute('''SELECT id, snapshot FROM dtf_local.orders - WHERE machine_id IS NULL AND cancelled_at IS NULL AND state=ANY(%s) - ORDER BY created_at, number''', (list(OPEN),)).fetchall() - if not waiting: - return 0 - c.execute('SELECT pg_advisory_xact_lock(%s)', (LOCK,)) - machines = c.execute('''SELECT id, products, active, limit_metres FROM dtf_local.machines - ORDER BY created_at, name''').fetchall() - load = {k: v['metres'] for k, v in loads(c).items()} - routed = 0 - for order in waiting: - machine = pick(machines, load, order) - if machine is None: - continue - if c.execute('''UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=false - WHERE id=%s AND machine_id IS NULL RETURNING id''', (machine['id'], order['id'])).fetchone(): - key = str(machine['id']) - load[key] = load.get(key, Decimal(0)) + order_metres(order) - routed += 1 - return routed - - def rows(c, with_operators=False): """Every machine with its load, for the Kanban.""" machines = c.execute('''SELECT id, name, products, active, limit_metres FROM dtf_local.machines diff --git a/app/payments.py b/app/payments.py index a2ccc9c..424fe36 100644 --- a/app/payments.py +++ b/app/payments.py @@ -16,7 +16,7 @@ from uuid import UUID, uuid4 from psycopg.types.json import Jsonb -from . import machines, mail, proof +from . import mail, proof from .core.auth import audit from .core.models import PRODUCTION_VERSIONS from .printjobs import queue as queue_print_files @@ -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'],)) # An order with a proof gets its proof card (app/proof.py). proof.create_child(c, order) - machines.route(c) if is_test(order): return order, True mail.order_paid(c, order, PUBLIC_ORIGIN) diff --git a/app/printjobs.py b/app/printjobs.py index b773bd7..109f1dd 100644 --- a/app/printjobs.py +++ b/app/printjobs.py @@ -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. """ import logging +import multiprocessing import os import shutil import tempfile import time +from queue import Empty from datetime import timedelta from decimal import Decimal from zoneinfo import ZoneInfo @@ -38,7 +40,8 @@ from .tiny import purchase_order LOCAL = ZoneInfo('America/Sao_Paulo') # 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 LARGE_SOURCE_BYTES = int(os.environ.get('PRINT_DECODE_MAX_BYTES', str(300 * 1024 * 1024))) # Read band by band, whatever their size. @@ -55,9 +58,10 @@ def queue(c, order_id, items, only_missing=False): if only_missing: c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s) ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0, - claimed_at=NULL, finished_at=NULL, detail='{}' - WHERE dtf_local.print_files.status IN ('failed','manual')''', - (uuid4(), order_id, index)) + claimed_at=NULL, claim_token=NULL, finished_at=NULL, upload_id=NULL, detail='{}' + WHERE dtf_local.print_files.status IN ('failed','manual') OR + (dtf_local.print_files.status='rendering' AND dtf_local.print_files.claimed_at= 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 scratch, parts, detail = result stored = [] @@ -120,18 +165,30 @@ def render_one(storage): for part, (uid, _, size, _) in zip(detail['parts'], stored): part.update(upload_id=str(uid), size=size) with connect() as c: + current = c.execute('''SELECT 1 FROM dtf_local.print_files WHERE id=%s AND claim_token=%s + AND status='rendering' FOR UPDATE''', (job['id'], job['claim_token'])).fetchone() + if not current: + return True for uid, name, size, key in stored: c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete, expires_at,scan_state,scan_reason,scanned_at) VALUES(%s,%s,%s,%s,%s,'',true,%s,'clean','generated from scanned artwork',now())''', (uid, generated_identity(job['order_id']), name, size, key, expiry)) 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', (job['order_id'], job['item_index'])) for number, (uid, _, _, _) in enumerate(stored, 1): c.execute('INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id) VALUES(%s,%s,%s,%s)', (job['order_id'], job['item_index'], number, uid)) + if job['snapshot'].get('proof_of'): + c.execute('''UPDATE dtf_local.order_files SET active=false + WHERE order_id=%s AND item_index=%s AND kind='final' ''', + (job['order_id'], job['item_index'])) + c.execute('''INSERT INTO dtf_local.order_files + (id,order_id,upload_id,item_index,kind,note,created_by) + VALUES(%s,%s,%s,%s,'final','Prova gerada automaticamente pelo Prumo','Prumo')''', + (uuid4(), job['order_id'], stored[0][0], job['item_index'])) audit('print_file_ready', order=str(job['order_id']), item=job['item_index'], parts=len(stored)) return True @@ -162,8 +219,8 @@ def footer(job, item): billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',') proof_of = job['snapshot'].get('proof_of') if proof_of: - return ' · '.join(['DROPSTAR', f'Prova do pedido {purchase_order(proof_of)}', - f'Item {job["item_index"] + 1}/{count}', day]) + return ' · '.join(['DROPSTAR', f'PROVA do #{proof_of}', + f'Classe {item.get("stroke_class") or "C3"}', day]) fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}', f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m'] # A mirrored artwork (UV only) is named on the sheet, for the room to see @@ -193,8 +250,8 @@ def produce(storage, job, item, uploads): storage.fetch(uploads[upload_id]['object_key'], local) files[index] = (local, uploads[upload_id]['name']) 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). - prefix = (file_prefix(proof_of, job['item_index']) + '-prova' if proof_of + # The child owns its final file; the class names its proof. + prefix = (f'DTF-{job["number"]}-prova-{item.get("stroke_class") or "C3"}' if proof_of else file_prefix(job['number'], job['item_index'])) parts, detail = render(item, files, output, prefix, footer=footer(job, item), tiles=True, limit_cm=PROOF_SHEET_CM if proof_of else None) @@ -208,7 +265,8 @@ def finish(job, status, detail): with connect() as c: c.execute('''UPDATE dtf_local.print_files SET status=%s, detail=%s, finished_at=CASE WHEN %s='pending' THEN NULL ELSE now() END, - claimed_at=NULL WHERE id=%s''', (status, Jsonb(detail), status, job['id'])) + claimed_at=NULL,claim_token=NULL WHERE id=%s AND claim_token=%s AND status='rendering' ''', + (status, Jsonb(detail), status, job['id'], job['claim_token'])) def render_loop(storage): diff --git a/app/printpng_validate.py b/app/printpng_validate.py new file mode 100644 index 0000000..92c9201 --- /dev/null +++ b/app/printpng_validate.py @@ -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) diff --git a/app/proof.py b/app/proof.py index 23b6ab6..64e6b01 100644 --- a/app/proof.py +++ b/app/proof.py @@ -14,6 +14,7 @@ from decimal import Decimal from uuid import NAMESPACE_URL, uuid4, uuid5 from psycopg.types.json import Jsonb +from fastapi import HTTPException PROOF_ABOVE_METRES = Decimal('10') CUSTOMER_NOTE = ('O cliente pediu uma prova antes de imprimir: mande a foto da prova pelo WhatsApp ' @@ -33,13 +34,13 @@ def needs_proof(snapshot): # # An order with a proof becomes a parent and a child. The child, the card # "Prova", is an order of its own (orders.parent_id) with a pre-built proof -# sheet of up to 30 cm, DTF-N-item-1-prova.png, and follows the normal flow up +# sheet of up to 15 cm per contraction class, and follows the normal flow up # to Revisão. The parent waits outside the queue, "Aguardando prova". On the # child, the Vendedor (Gestão and the Administrador too) marks Prova OK, and # the parent enters the queue; or Prova reprovada, with its reason, and the # parent goes back to Arte recebida and the child closes. The child is no # sale: it is not in Tiny, Números, the customer's account or their e-mails. -PROOF_SHEET_CM = Decimal('30') +PROOF_SHEET_CM = Decimal('15') # Three proofs at most per order, one per item (Dropstar, 2026-10-23). MAX_PROOFS = 3 PROVIDER = 'prova' @@ -55,8 +56,20 @@ def create_child(c, parent): if parent.get('parent_id') or not needs_proof(parent['snapshot']): return None from .printjobs import queue - snapshot = {**parent['snapshot'], 'items': parent['snapshot']['items'][:MAX_PROOFS], - 'proof_of': parent['number']} + # A class has one proof. When several items share it, use the one with the + # finest measured line; no metre or product value is sold on this card. + classes = {} + for index, item in enumerate(parent['snapshot']['items']): + kind = item.get('stroke_class') or 'C3' + width = item.get('stroke_px') or 10000 + if kind not in classes or width < classes[kind][0]: + classes[kind] = (width, index, item) + selected = [classes[kind] for kind in ('C1', 'C2', 'C3') if kind in classes][:MAX_PROOFS] + proof_items = [{**item, 'billed_metres': '0', 'total_cents': 0, 'unit_cents': 0, + 'proof_parent_item_index': index} for _, index, item in selected] + freight = {**parent['snapshot'].get('freight', {}), 'total_cents': 0} + snapshot = {**parent['snapshot'], 'items': proof_items, 'total_cents': 0, + 'freight': freight, 'proof_of': parent['number']} child = c.execute('''INSERT INTO dtf_local.orders(id,owner,snapshot,payment,origin,parent_id,machine_id,machine_chosen) VALUES(%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''', (uuid4(), proof_identity(parent['id']), Jsonb(snapshot), Jsonb({'provider': PROVIDER}), @@ -74,3 +87,10 @@ def open_child(c, parent_id): def waiting(c, order): """Whether the order waits for its proof: it has a proof card without an OK.""" return not order.get('parent_id') and not order.get('proof_ok_at') and bool(open_child(c, order['id'])) + + +def require_unlocked(c, order): + """A parent cannot enter production or have its final changed before the proof answer.""" + if waiting(c, order): + child = open_child(c, order['id']) + raise HTTPException(409, f'Aguardando prova do #{child["number"]}: responda no card da prova.') diff --git a/app/schema.sql b/app/schema.sql index 493ffbe..9cb2d6a 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -136,6 +136,7 @@ CREATE TABLE IF NOT EXISTS dtf_local.print_files ( created_at timestamptz NOT NULL DEFAULT now(), finished_at timestamptz, UNIQUE(order_id,item_index) ); +ALTER TABLE dtf_local.print_files ADD COLUMN IF NOT EXISTS claim_token uuid; -- Each run of the off-server database backup (ops/db_backup.py), which the -- Kanban shows so a backup that stopped working does not go unnoticed. @@ -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. ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS back boolean NOT NULL DEFAULT false; +CREATE INDEX IF NOT EXISTS movements_finished_latest ON dtf_local.movements(order_id, created_at DESC) + WHERE to_state='fin' AND NOT back; -- The Kanban lists payment events a person must act on (money without an -- order, or a reversed payment on an existing order) until resolved. @@ -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 ADD CONSTRAINT operators_role CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro')); --- The print machines, and which products each prints. An order keeps the --- machine someone chose (machine_chosen) or the one given automatically: the --- active machine of its product with the fewest metres open (app/machines.py). --- limit_metres: the metres open a machine takes before the next order goes to --- another one; NULL is no limit. +-- Print machines and which products each prints. An order gets its machine +-- when someone pulls it into Imprimindo; no machine is assigned at payment. +-- limit_metres remains the load shown for a machine. CREATE TABLE IF NOT EXISTS dtf_local.machines ( id uuid PRIMARY KEY, name text UNIQUE NOT NULL, products text[] NOT NULL DEFAULT '{}', active boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now() @@ -303,6 +304,15 @@ DO $$ BEGIN INSERT INTO dtf_local.migrations VALUES('machine-chosen-v1'); END IF; END $$; +-- Remove the old automatic suggestions before printing. Keep real choices +-- and machines already printing, whose hot-folder files may be in flight. +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='machine-pull-only-v1') THEN + UPDATE dtf_local.orders SET machine_id=NULL, machine_chosen=false + WHERE NOT machine_chosen AND state IN ('rec','tra','cor'); + INSERT INTO dtf_local.migrations VALUES('machine-pull-only-v1'); + END IF; +END $$; -- The machines an operator works on; none means every machine. CREATE TABLE IF NOT EXISTS dtf_local.operator_machines ( operator_id uuid NOT NULL REFERENCES dtf_local.operators(id) ON DELETE CASCADE, diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index 2f4ce73..59a903a 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -205,6 +205,7 @@ try{ // Open the order's panel from its card, then click the real transition // buttons there, including the rerender after each move. await kanban.click('[data-tab="board"]'); + assert.equal(await kanban.eval(`!!document.querySelector('[data-card="${oid}"] .card-open')`),true); await kanban.click(`[data-card="${oid}"]`); await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel'); // Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão before Finalizado. @@ -233,6 +234,13 @@ try{ await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`); await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state); if(state==='tra'){ + // The file opens from the card itself, without first expanding the order. + await kanban.eval('closePanel()'); + await kanban.click(`[data-card="${oid}"] .card-open`); + await waitFor(()=>kanban.eval(`!!document.querySelector('.viewer[open]')`),'file viewer from the card'); + assert.equal(await kanban.eval(`$('drawer').hidden`),true); + await kanban.click('.viewer .vbtn.pri'); + await kanban.click(`[data-card="${oid}"]`); // Entering the queue moves its file to Arte conferida, whole and named after the order. const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1'; await waitFor(async()=>(await savedFiles('2. Arte conferida')).some(n=>n.startsWith(prefix)&&!n.endsWith('.baixando')),'final file in Arte conferida',45000); diff --git a/tests/finished_order_test.py b/tests/finished_order_test.py new file mode 100644 index 0000000..c961b28 --- /dev/null +++ b/tests/finished_order_test.py @@ -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() diff --git a/tests/machine_pull_test.py b/tests/machine_pull_test.py new file mode 100644 index 0000000..f776fec --- /dev/null +++ b/tests/machine_pull_test.py @@ -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() diff --git a/tests/payment_test.py b/tests/payment_test.py index 6cacfa3..ebbe3ea 100644 --- a/tests/payment_test.py +++ b/tests/payment_test.py @@ -153,7 +153,8 @@ def run(): assert tester.call('/operator/quotes/' + test_quote + '/test-order', {}, operator=True)['id'] == order['id'] version = order['version'] # Arte conferida, the print queue, takes the order once its final is approved. - final = upload_bytes(tester, b'TEST ORDER FINAL', order_id=order['id']) + from tests.smoke_test import final_png_bytes + final = upload_bytes(tester, final_png_bytes('test order'), name='TEST-ORDER-FINAL.png', order_id=order['id']) version = tester.call('/operator/orders/' + order['id'] + '/final-files', {'version': version, 'files': [{'item_index': 0, 'upload_id': final}], 'note': 'Teste'}, operator=True)['version'] diff --git a/tests/print_file_test.py b/tests/print_file_test.py index b7d2f2a..c6d955f 100644 --- a/tests/print_file_test.py +++ b/tests/print_file_test.py @@ -36,15 +36,15 @@ CUSTOMER = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'print-test@ def artwork(kind='PNG'): - image = Image.new('RGBA', (600, 300), (0, 0, 0, 0)) - for x in range(40, 560): - for y in range(40, 260): + image = Image.new('RGBA', (1600, 800), (0, 0, 0, 0)) + for x in range(40, 1560): + for y in range(40, 760): image.putpixel((x, y), (220, 30, 60, 255)) out = io.BytesIO() if kind == 'PDF': image.convert('RGB').save(out, 'PDF', resolution=72) else: - image.save(out, kind) + image.save(out, kind, dpi=(300, 300)) return out.getvalue() @@ -93,7 +93,7 @@ def run(): uid = upload_bytes(client, artwork(), name='LOCAL-PRINT-TEST.png') order = paid_order(client, loose_item(uid)) order, row = wait_print(client, order['id'], 'ready') - assert row['detail']['placements'] == 2 and row['detail']['min_dpi'] == round(600 / (20 / 2.54)) + 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 # and the 1,5 cm footer band, outside the billed length. film = download_png(client, row['upload_id']) @@ -142,7 +142,10 @@ def run(): version += 1 # Printing, the folders still get the file of an order they hold (to take # it to Finalizado later), and no one else's. - client.call('/operator/orders/' + oid + '/move', {'state': 'imp', 'version': version}, operator=True) + machine = client.call('/operator/machines', {'name': 'Print test '+uuid4().hex[:6], + 'products': ['textil']}, operator=True)['id'] + client.call('/operator/orders/' + oid + '/move', {'state': 'imp', 'version': version, + 'machine_id': machine}, operator=True) version += 1 held = client.call('/operator/queue/folder', {'early': True, 'held': [oid]}, operator=True) assert [(f['state'], f['upload_id']) for f in held['files'] if f['order'] == oid] == [('imp', str(row['upload_id']))], held @@ -223,15 +226,17 @@ def run(): with db.connect() as c: assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key LIKE %s', (card['id'] + '%',)).fetchone() c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (card['id'],)) - final = upload_bytes(client, b'LOCAL PROOF FINAL FIXTURE', order_id=parent['id']) - version = client.call('/operator/orders/' + parent['id'] + '/final-files', - {'version': parent['version'], 'files': [{'item_index': 0, 'upload_id': final}], - 'note': 'Local proof test final'}, operator=True)['version'] - version = client.call('/operator/orders/' + parent['id'] + '/move', {'state': 'tra', 'version': version}, - operator=True)['version'] - held = client.call('/operator/orders/' + parent['id'] + '/move', {'state': 'imp', 'version': version}, - operator=True, expected=409) + final = str(uuid4()) + held = client.call('/operator/orders/' + parent['id'] + '/final-files', + {'version': parent['version'], 'files': [{'item_index': 0, 'upload_id': final}], + 'note': 'Local proof test final'}, operator=True, expected=409) assert 'Aguardando prova' in held['detail'], held + for path, body in [('/move', {'state': 'tra', 'version': parent['version']}), + ('/contraction', {'item_index': 0, 'value': 'C1'}), + ('/machine', {'machine_id': None}), + ('/queue', {'after': card['id']})]: + held = client.call('/operator/orders/' + parent['id'] + path, body, operator=True, expected=409) + assert 'Aguardando prova' in held['detail'], (path, held) client.call('/operator/orders/' + card['id'] + '/move', {'state': 'fin', 'version': card['version']}, operator=True, expected=409) # Reprovada needs its reason; the order goes back to Arte recebida. @@ -245,6 +250,11 @@ def run(): assert mine['state'] == 'rec' and mine['proof_card']['proof_result'] == 'rejected', mine['proof_card'] assert mine['proof_card']['proof_reason'] == 'Cor do fundo errada' assert not [o for o in board if o['id'] == card['id']], 'an answered proof card leaves the board' + # Rejection releases the parent for corrected artwork, until a new proof card is opened. + final = upload_bytes(client, artwork(), name='LOCAL-PROOF-FINAL.png', order_id=parent['id']) + version = client.call('/operator/orders/' + parent['id'] + '/final-files', + {'version': mine['version'], 'files': [{'item_index': 0, 'upload_id': final}], + 'note': 'Local proof test final'}, operator=True)['version'] # A new card, and Prova OK lets the order into the queue. again = client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True) client.call('/operator/orders/' + parent['id'] + '/proof-card', {}, operator=True, expected=409) @@ -252,7 +262,7 @@ def run(): c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (again['id'],)) client.call('/operator/orders/' + again['id'] + '/proof-answer', {'result': 'ok'}, operator=True) mine = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == parent['id']) - assert mine['proof_ok_at'] and mine['proof_card']['proof_result'] == 'ok', mine + 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') # A customer cannot see or reuse another order's generated file. @@ -313,7 +323,7 @@ def run(): finished = client.call('/operator/orders/finished?limit=1', operator=True) if finished['orders']: last = finished['orders'][-1] - client.call('/operator/orders/finished?before_created_at=' + last['created_at'].replace('+', '%2B') + client.call('/operator/orders/finished?before_finished_at=' + last['finished_at'].replace('+', '%2B') + '&before_id=' + last['id'], operator=True) print('PASS: send log, payment history and finished orders page and filter') diff --git a/tests/smoke_test.py b/tests/smoke_test.py index 76c29fb..2f686eb 100644 --- a/tests/smoke_test.py +++ b/tests/smoke_test.py @@ -7,12 +7,25 @@ import hashlib import http.cookiejar import json import os +import struct +import zlib from pathlib import Path import time from urllib.error import HTTPError from urllib.request import build_opener, HTTPCookieProcessor, Request, urlopen from uuid import uuid4 + +def final_png_bytes(label='final'): + """A tiny real RGBA PNG tagged 300 DPI for operator final-file tests.""" + def chunk(kind, body): + return struct.pack('>I', len(body)) + kind + body + struct.pack('>I', zlib.crc32(kind + body) & 0xffffffff) + red = hashlib.sha256(label.encode()).digest()[0] + row = b'\x00' + bytes((red, 30, 60, 255, 0, 0, 0, 0)) + return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 2, 1, 8, 6, 0, 0, 0)) + + chunk(b'pHYs', struct.pack('>IIB', 11811, 11811, 1)) + + chunk(b'IDAT', zlib.compress(row)) + chunk(b'IEND', b'')) + if Path('.env').exists(): for line in Path('.env').read_text().splitlines(): if line.strip() and not line.startswith('#') and '=' in line: @@ -269,7 +282,7 @@ def run(): if state=='tra': # The queue takes approved final files only. client.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409) - files=[{'item_index':i,'upload_id':upload_bytes(client,b'LOCAL FINAL FIXTURE '+str(i).encode(),order_id=oid)} for i in range(4)] + files=[{'item_index':i,'upload_id':upload_bytes(client,final_png_bytes(str(i)),name=f'LOCAL-FINAL-{i}.png',order_id=oid)} for i in range(4)] result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True) version=result['version'] if state=='imp': diff --git a/tests/test_printpng_validate.py b/tests/test_printpng_validate.py new file mode 100644 index 0000000..27c6afa --- /dev/null +++ b/tests/test_printpng_validate.py @@ -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() diff --git a/tests/workflow_test.py b/tests/workflow_test.py index 5062f59..30fbee1 100644 --- a/tests/workflow_test.py +++ b/tests/workflow_test.py @@ -2,7 +2,7 @@ import os from uuid import uuid4 from urllib.request import urlopen -from tests.smoke_test import Client, approved_quote, upload_bytes, item_spec, register +from tests.smoke_test import Client, approved_quote, upload_bytes, item_spec, register, final_png_bytes def run(): customer=Client();other=Client();customer.call('/session');other.call('/session') @@ -55,7 +55,8 @@ def run(): # Arte conferida is the print queue (2026-10-23): it takes approved finals only. version=0 customer.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409) - final_id=upload_bytes(customer,b'LOCAL FINAL VERSION ONE',order_id=oid) + final_one=final_png_bytes('final one') + final_id=upload_bytes(customer,final_one,name='LOCAL-FINAL-ONE.png',order_id=oid) customer.call('/uploads/'+final_id,expected=404) body={'version':version,'files':[{'item_index':0,'upload_id':final_id}],'note':'Manually checked final'} customer.call('/operator/orders/'+oid+'/final-files',body,expected=401) @@ -67,21 +68,21 @@ def run(): detail=customer.call('/customer/orders/'+oid) final=detail['files'][0] link=customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download') - assert urlopen(link['url']).read()==b'LOCAL FINAL VERSION ONE' + assert urlopen(link['url']).read()==final_one guest=Client();guest.call('/session');guest.call('/customer/orders/'+oid+'/files/'+final['id']+'/download',expected=404) version=move('tra',version) # The print queue's files come named after their order, straight from storage. queued=customer.call('/operator/queue/finals',operator=True)['files'] - mine=[f for f in queued if urlopen(f['url']).read()==b'LOCAL FINAL VERSION ONE'] + mine=[f for f in queued if urlopen(f['url']).read()==final_one] assert len(mine)==1 and mine[0]['name'].startswith('DTF-%d-item-1-' % mine[0]['number']), queued customer.call('/operator/queue/finals',expected=401) version=move('imp',version);version=move('cor',version) customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download',expected=404) - premature_final=upload_bytes(customer,b'FINAL BEFORE CUSTOMER CORRECTION',order_id=oid) + premature_final=upload_bytes(customer,final_png_bytes('premature'),name='LOCAL-PREMATURE-FINAL.png',order_id=oid) version=customer.call('/operator/orders/'+oid+'/final-files', {'version':version,'files':[{'item_index':0,'upload_id':premature_final}], 'note':'Prepared before customer sent the new correction'},operator=True)['version'] - correction_id=upload_bytes(customer,b'LOCAL CORRECTED ORIGINAL') + correction_id=upload_bytes(customer,final_png_bytes('correction'),name='LOCAL-CORRECTION.png') payload={'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Replaced the artwork as requested'} guest.call('/customer/orders/'+oid+'/corrections',payload,expected=404) customer.call('/customer/orders/'+oid+'/corrections',{**payload,'version':0},expected=409) @@ -97,7 +98,7 @@ def run(): # The customer's own correction approved as it is: not treated. assert treated() is None, treated() customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':correction_id}],'note':'Twice'},operator=True,expected=409) - new_final=upload_bytes(customer,b'LOCAL FINAL VERSION TWO',order_id=oid) + new_final=upload_bytes(customer,final_png_bytes('final two'),name='LOCAL-FINAL-TWO.png',order_id=oid) version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':[{'item_index':0,'upload_id':new_final}],'note':'Checked corrected final'},operator=True)['version'] assert treated()=={'items':[0],'by':operator_email}, treated() stats=customer.call('/operator/stats?days=7',operator=True)['treated'] @@ -128,7 +129,7 @@ def treating(): approved_quote(customer,q,items) order=customer.call('/orders/dev-paid',{'quote_id':q['id']});oid=order['id'];number=order['number'] files=lambda:[f for f in customer.call('/operator/orders/'+oid+'/files',operator=True) if f['kind']=='final' and f['active']] - first=[upload_bytes(customer,b'LOCAL FIRST FINAL %d' % n,order_id=oid) for n in (1,2)] + first=[upload_bytes(customer,final_png_bytes(f'first {n}'),name=f'LOCAL-FIRST-FINAL-{n}.png',order_id=oid) for n in (1,2)] version=customer.call('/operator/orders/'+oid+'/final-files',{'version':0,'note':'Aprovado', 'files':[{'item_index':i,'upload_id':u} for i,u in enumerate(first)]},operator=True)['version'] # Where each item is in the stage folder, named as the folders save it. @@ -137,7 +138,7 @@ def treating(): assert all(f['name'].startswith('DTF-%d-item-%d' % (number,f['item'])) for f in folder['files']), folder customer.call('/operator/orders/'+oid+'/folder-files',expected=401) # Saved over with the same name and sent back: item 1 changes, item 2 keeps its final. - png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4 + png=final_png_bytes('treated') treated=upload_bytes(customer,png,name='DTF-%d-item-1.png' % number,order_id=oid) both=[{'item_index':0,'upload_id':treated},{'item_index':1,'upload_id':first[1]}] version=customer.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':both,'note':'Arte tratada'},operator=True)['version'] diff --git a/web/kanban.css b/web/kanban.css index e03bd8f..ed82a8b 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -262,6 +262,9 @@ main{padding:0} .card.open,.mini.open{border-color:var(--ink);box-shadow:0 0 0 1px var(--ink)} .card.off{opacity:.7} .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} .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)} @@ -418,6 +421,9 @@ main{padding:0} .inote.bad,.inote.bad .i{color:var(--bad)} .inotes .callout{margin:2px 0} .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} .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} diff --git a/web/kanban.js b/web/kanban.js index 2eced2f..6984738 100644 --- a/web/kanban.js +++ b/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 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()=>{ - const result=await api('/uploads/'+uid+'/download'); +function download(uid,orderId){return async()=>{ + 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(); };} // ---- Automatic folder ------------------------------------------------------ @@ -670,6 +670,7 @@ function printState(order){ if((order.corrections||[]).length)return {text:'Correção recebida',tone:'warn'}; const rows=order.print_files||[], items=order.snapshot.items.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(ready===items)return {text:'Falta aprovar o final',tone:'warn'}; 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; $('kan').replaceChildren(...Object.entries(board.states).map(([state,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 - // 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)=>queueKey(a)-queueKey(b)||a.number-b.number); + // Working columns are queues; Finalizado shows the most recently ready order first. + const orders=board.orders.filter(o=>o.state===state&&matches(o)).sort((a,b)=>state==='fin' + ? 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'); head.append(svgIcon(GLYPH[state],'sg'+(state==='cor'?' cor':''))); 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 // when it sets the column's order; a card of another operator's machine does not. 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.onkeydown=e=>{if(e.target===c&&(e.key==='Enter'||e.key===' ')){e.preventDefault();openPanel(order.id);}}; c.ondragstart=e=>{ dragging=order; e.dataTransfer.setData('text/plain',order.id); @@ -1040,8 +1043,8 @@ function draggable(c,order){ function card(order,place){ const s=order.snapshot, mine=isMine(order)&&order.state!=='fin'&&!order.cancelled_at; 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':'')); - c.type='button';c.dataset.card=order.id; + const c=node('div',undefined,'card'+(mine?' mine':'')+(tone==='live'?' live':'')+(order.id===openOrder?' open':'')+(order.cancelled_at?' off':'')); + c.tabIndex=0;c.setAttribute('role','button');c.dataset.card=order.id; const who=buyer(s); c.setAttribute('aria-label','Pedido #'+order.number+', '+who.title+': '+step); 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')); foot.append(next); const flag=flagNode(cardFlags(order));if(flag)foot.append(flag); - c.append(foot); + c.append(foot,cardOpenAction(order)); draggable(c,order); return c; } @@ -1073,7 +1076,7 @@ function card(order,place){ // nothing else. A pickup waiting more than two days is said in warning. const PICKUP_WARN_DAYS=2; 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 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; @@ -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{text='Aguardando retirada';ic=IC.bag;} 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); draggable(c,order); return c; @@ -1120,9 +1123,10 @@ async function reorder(order,column,y){ await load(); } async function loadOlderFinished(){ - const shown=board.orders.filter(o=>o.state==='fin').sort((a,b)=>a.created_ato.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'}); - 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 known=new Set(board.orders.map(o=>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){ // Undo a mistaken move: one stage back, internal reason, no customer message. 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')) item(IC.phone,'Aguardando contato',()=>contactDialog(order)).dataset.contact=''; if(!isTest(order)&&may('rework'))item(IC.rework,'Abrir retrabalho',()=>reworkForm(order)); @@ -1432,8 +1436,6 @@ function contactNotice(order,canClear){ box.append(ico,p); 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(canClear)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')); return box; } // In correction, the customer has to be told: a message ready to send on @@ -1518,6 +1520,11 @@ function nextBox(order){ const note=text=>body.push(node('p',text,'nnote')); 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;}; + 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). if(order.proof_parent&&st==='rev'){ title='Responder a prova'; @@ -1551,6 +1558,14 @@ function nextBox(order){ 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(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(!finalDone(order)&&trans.includes('tra')){ if(st==='rec')title='Aprovar o arquivo final'; @@ -1694,7 +1709,7 @@ function readyFinals(order){ const fixes=order.corrections||[]; return order.snapshot.items.map((item,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'); if(!made)return null; const original=made.detail?.source==='original', files=generatedFiles(made); @@ -1720,7 +1735,8 @@ function finalDialog(order,ready,{replace=false}={}){ slot.append(node('span',label,'lbl')); const input=node('input');input.multiple=true;input.required=true;input.dataset.finalItem=index; 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]; if(file){ const use=node('input');use.checked=true;use.dataset.useGenerated=index;input.required=false;drop.hidden=true; @@ -1740,6 +1756,7 @@ function finalDialog(order,ready,{replace=false}={}){ const generated=input.generated?.(); if(generated){refs.push(...generated.map(upload_id=>({item_index:index,upload_id})));continue;} 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)}); refs.push({item_index:index,upload_id:uid}); } @@ -1762,12 +1779,20 @@ const FOLDER_PATH_KEY='folder-path'; 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; } +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){ const {files}=await api('/orders/'+order.id+'/view'); if(!files.length){say('Ainda não há arquivo para abrir.',true);return;} openViewer(files,{title:'#'+order.number,onClose:()=>{ 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 // the measure, and the art either goes on to Arte conferida, its final @@ -1908,6 +1933,7 @@ function itemNote(text,tone=''){ } function itemCard(order,item,index){ 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 info=node('div',undefined,'iinfo'); const count=order.snapshot.items.length; @@ -1924,19 +1950,22 @@ function itemCard(order,item,index){ info.append(dl); 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.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: '+ (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')); // After a customer correction, that file is the artwork: the generated // print file, or the reason it could not be made, no longer applies. const fix=(order.corrections||[]).find(f=>f.item_index===index); 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.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 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); }else{ const original=row.status==='ready'&&row.detail?.source==='original'; @@ -1956,10 +1985,11 @@ function itemCard(order,item,index){ 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))); } - item.uploads.forEach((uid,i)=>links.append(dl_(item.uploads.length>1?'Original '+(i+1):'Arquivo original',uid))); - 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);} + const originals=node('details',undefined,'originals');originals.append(node('summary','Originais ('+item.uploads.length+')')); + 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(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);} info.append(links); box.append(itemPreview(item),info);return box; @@ -1967,6 +1997,14 @@ function itemCard(order,item,index){ // Arquivos: every final, current or replaced, and the way to send a new one. function filesView(order,revisions,view){ 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){ const panel=node('div',undefined,'tpanel'); const table=node('table',undefined,'table'); @@ -1984,7 +2022,7 @@ function filesView(order,revisions,view){ }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; // 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'); open.prepend(svgIcon(IC.upload,'i m'));open.classList.add('self-start');out.push(open); } @@ -2045,6 +2083,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), 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': 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:'')); @@ -2111,28 +2155,28 @@ function paintMyMachine(){ for(const id of ['my-machine','rail-machine'])$(id).onclick=()=>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){ const box=node('div',undefined,'fact');box.append(node('span','Máquina','lbl')); 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). - if(!may('print')||ME?.role==='operador'||!board.machines?.length){ - box.append(node('b',current?current.name:'Nenhuma máquina cadastrada'), - node('span',current?.chosen?'Escolhida para este pedido':current?'Escolhida automaticamente':'Nenhuma máquina imprime este produto')); + if(!may('print')||ME?.role==='operador'||!board.machines?.length||waitingProof(order)||!['rec','tra','cor'].includes(order.state)){ + box.append(node('b',current?current.name:'Aguardando máquina'),node('span',detail)); return box; } 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'; 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); } - 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}); - 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);}}; - box.append(node('b',current?current.name:'Nenhuma'), - node('span',current?.chosen?'Escolhida para este pedido':current?'Escolhida automaticamente quando o pedido chegou':'Nenhuma máquina imprime este produto'),select); + box.append(node('b',current?current.name:'Aguardando máquina'),node('span',detail),select); return box; } // "120,00 m de 300,00 m" or "120,00 m em aberto". @@ -2804,8 +2848,9 @@ function quoteItem(item,fields,priced,index=0,count=1){ grid.append(m,gr);info.append(grid); } 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'))); - if(spec?.placements){const b=button('Manifesto',()=>manifest(spec,contractionRecord(item)),'btn');b.prepend(svgIcon(IC.file,'i m'));links.append(b);} + const originals=node('details',undefined,'originals');originals.append(node('summary','Originais ('+item.uploads.length+')')); + 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; }