diff --git a/app/api/artwork.py b/app/api/artwork.py index 82a4152..7b650d9 100644 --- a/app/api/artwork.py +++ b/app/api/artwork.py @@ -28,16 +28,18 @@ def begin_final(oid: UUID, body: UploadStart, user=Depends(can('produce'))): def final_status(uid: UUID, user=Depends(operator)): return upload_status(uid,session_id=operator_identity(user)) +# The parts of an upload its operator started: a final (produce) or the +# photo of a signed pickup receipt (deliver, which includes produce). @router.post('/api/operator/uploads/{uid}/parts/{number}') -def final_part(uid: UUID, number: int, user=Depends(can('produce'))): +def final_part(uid: UUID, number: int, user=Depends(can('deliver'))): return part_url(uid,number,session_id=operator_identity(user)) @router.post('/api/operator/uploads/{uid}/complete') -def final_complete(uid: UUID, user=Depends(can('produce'))): +def final_complete(uid: UUID, user=Depends(can('deliver'))): return complete_upload(uid,session_id=operator_identity(user)) @router.delete('/api/operator/uploads/{uid}') -def final_cancel(uid: UUID, user=Depends(can('produce'))): +def final_cancel(uid: UUID, user=Depends(can('deliver'))): return cancel_upload(uid,session_id=operator_identity(user)) @router.get('/api/operator/orders/{oid}/files') diff --git a/app/api/operator.py b/app/api/operator.py index 456a01d..d415136 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -15,12 +15,13 @@ from pydantic import Field 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 Move, OperatorLogin, Resolution, Review, StrictModel +from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart from ..printjobs import file_prefix, queue as queue_print_files -from .. import cnpj, machines, mail, payments, proof, quote_review +from .. import cnpj, machines, mail, payments, proof, quote_review, receipt from .. import tiny from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES, - TRANSITIONS, payment, enqueue, freight, quote_view, storage) + TRANSITIONS, payment, enqueue, freight, operator_identity, quote_view, storage, upload_row) +from .uploads import begin_upload from ..scanning import require_clean router = APIRouter() @@ -694,6 +695,105 @@ def proof_ok(uid: UUID, user=Depends(can('print'))): return {'ok': True, 'version': row['version']} +def paid_with(c, order): + """How the order was paid, for its receipt: pix, card, cash, credit, or + 'teste' for an operator's test order.""" + paid = order.get('payment') or {} + if paid.get('provider') == 'teste': + return 'teste' + if paid.get('provider') == payments.MANUAL_PROVIDER: + return paid.get('method') + row = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved' + ORDER BY created_at DESC LIMIT 1''', (order['quote_id'],)).fetchone() + return row and row['method'] + + +@router.get('/api/operator/orders/{uid}/receipt') +def pickup_receipt(uid: UUID, user=Depends(operator)): + """The pickup receipt's PDF (item 14), for the folder to save or someone + to print again.""" + with db.connect() as c: + order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() + if not order: + raise HTTPException(404, 'Pedido não encontrado.') + if not receipt.is_pickup(order['snapshot']): + raise HTTPException(409, 'Só pedido de retirada tem recibo.') + body = receipt.render(order, paid_with(c, order)) + return Response(body, media_type='application/pdf', + headers={'Content-Disposition': f'inline; filename="{receipt.file_name(order)}"'}) + + +@router.post('/api/operator/orders/{uid}/receipt/claim') +def claim_receipt(uid: UUID, user=Depends(can('print'))): + """One computer's folder takes the receipt to save: once, so the counter's + queue never prints it twice.""" + with db.connect() as c: + row = c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=now(), receipt_saved_by=%s + WHERE id=%s AND receipt_due_at IS NOT NULL AND receipt_saved_at IS NULL AND cancelled_at IS NULL + RETURNING number''', (user, uid)).fetchone() + if not row: + raise HTTPException(409, 'Este recibo já foi salvo.') + audit('pickup_receipt_saved', order=row['number'], operator=user) + return {'ok': True} + + +@router.post('/api/operator/orders/{uid}/receipt/release') +def release_receipt(uid: UUID, user=Depends(can('print'))): + """The folder could not save the receipt it took: another computer may.""" + with db.connect() as c: + c.execute('''UPDATE dtf_local.orders SET receipt_saved_at=NULL, receipt_saved_by=NULL + WHERE id=%s AND receipt_saved_by=%s''', (uid, user)) + return {'ok': True} + + +def pickup_order(c, uid, lock=False): + """An order in Finalizado to be picked up, or why it cannot be marked.""" + order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s' + (' FOR UPDATE' if lock else ''), (uid,)).fetchone() + if not order: + raise HTTPException(404, 'Pedido não encontrado.') + if order['cancelled_at'] or order['state'] != 'fin' or not receipt.is_pickup(order['snapshot']): + raise HTTPException(409, 'Só um pedido de retirada em Finalizado é marcado como retirado.') + if order['picked_up_at']: + raise HTTPException(409, 'Este pedido já foi marcado como retirado.') + return order + + +@router.post('/api/operator/orders/{uid}/pickup-uploads') +def begin_pickup_photo(uid: UUID, body: UploadStart, user=Depends(can('deliver'))): + """The photo of the signed receipt, sent before marking the order.""" + with db.connect() as c: + pickup_order(c, uid) + return begin_upload(body, session_id=operator_identity(user)) + + +class PickedUp(StrictModel): + photo: UUID | None = None + + +PHOTO_TYPES = ('.jpg', '.jpeg', '.png', '.webp', '.heic', '.heif') + + +@router.post('/api/operator/orders/{uid}/picked-up') +def picked_up(uid: UUID, body: PickedUp, user=Depends(can('deliver'))): + """"Retirado": when and who handed the order over, and the photo of the + signed receipt when there is one (item 14). Finalizado means ready; this + closes the cycle. The photo is kept 30 days, as the order's files are.""" + with db.connect() as c: + order = pickup_order(c, uid, lock=True) + if body.photo: + photo = upload_row(c, body.photo, operator_identity(user), lock=True) + if not photo['complete']: + raise HTTPException(409, 'Espere a foto terminar de enviar.') + if not photo['name'].lower().endswith(PHOTO_TYPES): + raise HTTPException(422, 'A foto do recibo precisa ser uma imagem (JPG, PNG, WebP ou HEIC).') + require_clean(photo) + c.execute("UPDATE dtf_local.uploads SET expires_at=now()+interval '30 days' WHERE id=%s", (body.photo,)) + row = c.execute('''UPDATE dtf_local.orders SET picked_up_at=now(), picked_up_by=%s, picked_up_photo=%s + WHERE id=%s RETURNING picked_up_at''', (user, body.photo, uid)).fetchone() + audit('order_picked_up', order=order['number'], operator=user, photo=bool(body.photo)) + return {'ok': True, 'picked_up_at': row['picked_up_at']} + + class QueuePlace(StrictModel): """Where a dragged card lands: between two orders of its column, either of them absent at the top or the bottom.""" @@ -775,7 +875,11 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)): c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind='final'", (uid,)) c.execute('INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back) VALUES(%s,%s,%s,%s,%s,%s)', (uid,row['state'],body.state,user,body.reason,back)) - changed = c.execute('UPDATE dtf_local.orders SET state=%s, version=version+1, updated_at=now(), queue_key=NULL WHERE id=%s RETURNING *', (body.state,uid)).fetchone() + # 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, + 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() # 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'} @@ -1244,8 +1348,14 @@ def queue_folder(body: FolderSync, request: Request, user=Depends(can('print'))) files = named_files(rows) held = c.execute('SELECT id,state,cancelled_at FROM dtf_local.orders WHERE id=ANY(%s)', (body.held,)).fetchall() if body.held else [] + # The pickup receipts no computer saved yet (item 14), due since the + # folders were chosen: one that was off catches up, like the files. + due = c.execute('''SELECT id, number FROM dtf_local.orders WHERE receipt_due_at IS NOT NULL + AND receipt_saved_at IS NULL AND cancelled_at IS NULL AND (%s::timestamptz IS NULL OR receipt_due_at>=%s) + ORDER BY receipt_due_at''', (body.since, body.since)).fetchall() if body.early else [] return {'files': files, - 'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held}} + 'states': {str(o['id']): 'cancelled' if o['cancelled_at'] else o['state'] for o in held}, + 'receipts': [{'order': str(o['id']), 'number': o['number'], 'name': receipt.file_name(o)} for o in due]} @router.get('/api/operator/uploads/{uid}/download') diff --git a/app/core/auth.py b/app/core/auth.py index 4dea3dc..abd504e 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -137,6 +137,10 @@ CAPABILITIES = { 'authorize': {'superadmin', 'admin'}, 'users': {'superadmin', 'admin'}, 'integrations': {'superadmin'}, + # "Retirado" at the counter (Dropstar's third round, item 14): everyone + # but the seller, who only views (D-30). It includes everyone who produces, + # so an operator upload (artwork.py) takes it for its parts. + 'deliver': {'superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor'}, } # Who moves which card (Dropstar's flow, 2026-10-23, and their rules of diff --git a/app/receipt.py b/app/receipt.py new file mode 100644 index 0000000..e21485a --- /dev/null +++ b/app/receipt.py @@ -0,0 +1,137 @@ +"""The pickup receipt (Dropstar's third round, item 14, 2026-10-29). + +A PDF for the counter's 80 mm thermal roll: the order number large at the +top, the customer and their CPF or CNPJ, each product and its metres, the +amount and how it was paid, when it was issued, and blank lines for the +date of pickup and the signature. Only for orders picked up in Franca: one +sent by a carrier has none. The Kanban's folder saves it in Recibos/, and the +counter's print queue sends it to the Bematech. +""" +import io +import unicodedata +from datetime import datetime + +from .printfile import Name, PdfWriter, deflate, serialize, _HELVETICA, _HELVETICA_BOLD +from .printjobs import LOCAL, file_prefix + +MM = 72 / 25.4 +WIDTH = 80 * MM +MARGIN = 4 * MM +ROOM = WIDTH - 2 * MARGIN +FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'} +PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas', + 'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'} +METHODS = {'pix': 'Pix', 'card': 'Cartão', 'cash': 'Dinheiro', 'credit': 'Crédito do cliente'} +# Helvetica's widths for what the tables in printfile.py leave out. +EXTRA = {'$': 556, '(': 333, ')': 333, '_': 556, '#': 556, '—': 1000, '@': 1015, '&': 667, '+': 584, "'": 191} + + +def code(order): + """DTF-123: the order as the Kanban, the files and Tiny name it.""" + return file_prefix(order['number'], 0).rsplit('-item-', 1)[0] + + +def is_pickup(snapshot): + return ((snapshot or {}).get('freight') or {}).get('service') == 'pickup' + + +def money(cents): + whole, cents = divmod(int(cents), 100) + return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}' + + +def document(value): + digits = ''.join(ch for ch in str(value or '') if ch.isdigit()) + if len(digits) == 14: + return 'CNPJ', f'{digits[:2]}.{digits[2:5]}.{digits[5:8]}/{digits[8:12]}-{digits[12:]}' + if len(digits) == 11: + return 'CPF', f'{digits[:3]}.{digits[3:6]}.{digits[6:9]}-{digits[9:]}' + return 'CPF/CNPJ', str(value or '') + + +def width(text, bold=False): + """The width of `text` in Helvetica at size 1: an accented letter is as + wide as its letter.""" + table = _HELVETICA_BOLD if bold else _HELVETICA + total = 0 + for ch in text: + base = unicodedata.normalize('NFD', ch)[0] + total += table.get(ch) or table.get(base) or EXTRA.get(ch) or 600 + return total / 1000 + + +def wrap(text, size, bold=False): + """The text in lines that fit the roll, broken between words.""" + lines, line = [], '' + for word in str(text).split(): + attempt = f'{line} {word}' if line else word + if line and width(attempt, bold) * size > ROOM: + lines.append(line) + line = word + else: + line = attempt + return lines + [line] if line else lines or [''] + + +def literal(text): + raw = text.encode('cp1252', 'replace') + return b'(' + raw.replace(b'\\', b'\\\\').replace(b'(', b'\\(').replace(b')', b'\\)') + b')' + + +def lines(order, paid_with, issued): + """What the receipt says, top to bottom: (text, size, bold, space before).""" + snapshot = order['snapshot'] + customer = snapshot.get('customer') or {} + kind, number = document(customer.get('cnpj')) + name = code(order) + # The number as large as the roll takes, up to 34 pt. + big = min(34, int(ROOM / width(name, True))) + out = [('DROPSTAR · Recibo de retirada', 9, True, 0), (name, big, True, 4)] + if paid_with == 'teste': + out.append(('PEDIDO DE TESTE', 10, True, 2)) + out.append(('Cliente', 7.5, False, 10)) + out += [(part, 10, True, 1) for part in wrap(customer.get('name') or customer.get('mail') or '', 10, True)] + out += [(kind, 7.5, False, 6), (number, 10, False, 1)] + out.append(('Produto', 7.5, False, 10)) + for item in snapshot.get('items') or []: + metres = str(item.get('billed_metres') or item.get('metres') or '').replace('.', ',') + out += [(part, 9.5, False, 2) for part in wrap(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))} — {metres} m", 9.5)] + out += [('Valor', 7.5, False, 10), (money(snapshot.get('total_cents') or 0), 12, True, 1), + ('Pagamento', 7.5, False, 6), (METHODS.get(paid_with, 'Teste' if paid_with == 'teste' else paid_with or '—'), 10, False, 1), + (f"Emitido em {issued.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')}", 8.5, False, 10), + ('Retirado em ____/____/________', 10, False, 22), + ('Assinatura ______________________', 10, False, 26)] + return out + + +def render(order, paid_with, issued=None): + """The receipt's PDF bytes, 80 mm wide and as long as what it says.""" + rows = lines(order, paid_with, issued or datetime.now(LOCAL)) + height = MARGIN * 2 + sum(size * 1.2 + space for _, size, _, space in rows) + y = height - MARGIN + commands = [b'0 g\n'] + for text, size, bold, space in rows: + y -= space + size + commands.append(b'BT /%s %s Tf %s %s Td %s Tj ET\n' % (b'F1' if bold else b'F2', serialize(size), + serialize(MARGIN), serialize(y), literal(text))) + y -= size * 0.2 + out = io.BytesIO() + pdf = PdfWriter(out) + content = pdf.stream({'Filter': Name('FlateDecode')}, deflate(commands)) + pages = pdf.alloc() + fonts = {key: {'Type': Name('Font'), 'Subtype': Name('Type1'), 'BaseFont': Name(font), + 'Encoding': Name('WinAnsiEncoding')} for key, font in FONTS.items()} + box = [0, 0, WIDTH, height] + page = pdf.obj({'Type': Name('Page'), 'Parent': pages, 'MediaBox': box, 'Resources': {'Font': fonts}, + 'Contents': content}) + pdf.obj({'Type': Name('Pages'), 'Kids': [page], 'Count': 1}, pages) + root = pdf.obj({'Type': Name('Catalog'), 'Pages': pages}) + info = pdf.obj({'Title': f'Recibo {code(order)}', + 'Producer': 'DTF System'}) + pdf.finish(root, info) + return out.getvalue() + + +def file_name(order): + """Recibo-DTF-123.pdf""" + return f'Recibo-{code(order)}.pdf' diff --git a/app/schema.sql b/app/schema.sql index fa9f14b..cebb272 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -401,3 +401,16 @@ CREATE TABLE IF NOT EXISTS dtf_local.reworks ( authorized boolean, decided_by text, decided_at timestamptz, decline_reason text ); CREATE INDEX IF NOT EXISTS reworks_order ON dtf_local.reworks(order_id); + +-- The pickup receipt (Dropstar's third round, item 14, 2026-10-29): due when +-- an order to be picked up reaches Finalizado; one computer's folder claims +-- it and saves the PDF in Recibos/, where the counter's print queue sends it +-- to the Bematech. Claimed once, so it is never printed twice. +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_due_at timestamptz; +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_saved_at timestamptz; +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_saved_by text; +-- "Retirado": when, who handed it over and, optionally, a photo of the +-- signed receipt. Finalizado means ready; this means delivered. +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_at timestamptz; +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_by text; +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_photo uuid REFERENCES dtf_local.uploads(id) ON DELETE SET NULL; diff --git a/tests/users_test.py b/tests/users_test.py index 0ab144a..95ccf25 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -3,7 +3,9 @@ Run inside the API container: python -m tests.users_test """ import secrets +import time from decimal import Decimal +from urllib.request import Request, urlopen from uuid import uuid4 from psycopg.types.json import Jsonb @@ -11,7 +13,7 @@ from psycopg.types.json import Jsonb from app import machines as routing from app import payments, proof from app.core import db -from tests.smoke_test import Client +from tests.smoke_test import BASE, Client, with_host PASSWORD = 'senha-de-teste-123' @@ -39,6 +41,26 @@ def order_fixture(c, owner, mode, metres='1', printed=None): return quote, order +def raw(client, path): + """A response's bytes, for what is not JSON (the receipt's PDF).""" + with client.opener.open(Request(BASE + '/api' + path, headers=with_host()), timeout=30) as response: + return response.read() + + +def pickup_photo(client, oid, content): + """The photo of a signed receipt, sent as the counter does, until scanned clean.""" + uid = client.call(f'/operator/orders/{oid}/pickup-uploads', {'name': 'recibo.png', 'size': len(content)})['id'] + url = client.call(f'/operator/uploads/{uid}/parts/1', {})['url'] + with urlopen(Request(url, data=content, method='PUT'), timeout=30) as response: + assert response.status == 200 + client.call(f'/operator/uploads/{uid}/complete', {}) + deadline = time.monotonic() + 150 + while client.call(f'/operator/uploads/{uid}')['scan_state'] != 'clean': + assert time.monotonic() < deadline, 'photo scan did not finish' + time.sleep(0.5) + 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.""" @@ -161,17 +183,41 @@ def run(): 'password': PASSWORD}) reviewer = signed_in(emails['revisor']) me = reviewer.call('/operator/me') - assert me['can'] == ['view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me + assert me['can'] == ['deliver', 'view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me reviewer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403) assert reviewer.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'], 'reason': ''})['state'] == 'fin' + # A pickup in Finalizado has its receipt (item 14): 80 mm wide, saved + # in Recibos/ by one computer only, and printed again from the panel. + pdf = raw(su.operator_client, f'/operator/orders/{uv_o}/receipt') + assert pdf.startswith(b'%PDF') and b'/MediaBox [0 0 226.7717 ' in pdf, pdf[:200] + due = lambda: {r['order']: r['name'] for r in su.call('/operator/queue/folder', {'early': True}, operator=True)['receipts']} + number = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(uv_o))['number'] + assert due()[str(uv_o)] == f'Recibo-DTF-{number}.pdf' + su.call(f'/operator/orders/{uv_o}/receipt/claim', {}, operator=True) + su.call(f'/operator/orders/{uv_o}/receipt/claim', {}, operator=True, expected=409) + assert str(uv_o) not in due() + # Not saved after all: it goes back for another computer to take. + su.call(f'/operator/orders/{uv_o}/receipt/release', {}, operator=True) + assert str(uv_o) in due() + su.call(f'/operator/orders/{uv_o}/receipt/claim', {}, operator=True) + # "Retirado": anyone but the seller, only in Finalizado, once, with the + # photo of the signed receipt. + seller.call(f'/operator/orders/{uv_o}/picked-up', {}, expected=403) + reviewer.call(f'/operator/orders/{textil_o}/picked-up', {}, expected=409) + png = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR' + (40).to_bytes(4, 'big') + (60).to_bytes(4, 'big') + b'\x08\x06\x00\x00\x00' + b'\x00' * 4 + photo = pickup_photo(reviewer, uv_o, png) + reviewer.call(f'/operator/orders/{uv_o}/picked-up', {'photo': photo}) + reviewer.call(f'/operator/orders/{uv_o}/picked-up', {}, expected=409) + shown = next(o for o in su.call('/operator/board', operator=True)['orders'] if o['id'] == str(uv_o)) + assert (shown['picked_up_by'], shown['picked_up_photo']) == (emails['revisor'], photo) and shown['picked_up_at'], shown # The designer: every order, whatever its machine; the artwork stages only. admin.call('/operator/users', {'name': 'Arte', 'email': emails['designer'], 'role': 'designer', 'password': PASSWORD, 'machines': [uv]}) assert next(u for u in admin.call('/operator/users')['users'] if u['email'] == emails['designer'])['machines'] == [] designer = signed_in(emails['designer']) - assert set(designer.call('/operator/me')['can']) == {'view', 'produce'} + assert set(designer.call('/operator/me')['can']) == {'view', 'produce', 'deliver'} designer.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=403) assert {str(uv_o), str(textil_o)} <= {o['id'] for o in designer.call('/operator/board')['orders']} version = next(o for o in designer.call('/operator/board')['orders'] if o['id'] == str(textil_o))['version'] diff --git a/web/kanban.css b/web/kanban.css index 1739b07..1c8fdba 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -191,6 +191,8 @@ main{padding:0 24px 24px} .finalform input[type=file]::file-selector-button{height:34px;padding:0 12px;margin-right:10px;border-radius:8px;border:1px solid var(--line2);background:var(--card2);color:var(--tx);font:inherit;font-size:13.5px;font-weight:600;cursor:pointer} .finalform .slot{display:flex;flex-direction:column;gap:6px;font-size:14px;font-weight:600} .treatline{display:flex;align-items:center;gap:8px} +.pickup{display:flex;flex-direction:column;gap:10px} +.pickup .buttons[hidden]{display:none} .treatpath{flex:1;min-width:0;padding:7px 10px;border-radius:8px;background:var(--card2);font-family:var(--mono);font-size:13px;font-weight:500;color:var(--tx);word-break:break-all} .timeline{margin:0;padding:0;list-style:none;display:flex;flex-direction:column;gap:10px} .timeline li::before{content:"";width:8px;height:8px;margin-top:6px;border-radius:999px;background:var(--c,var(--muted));flex-shrink:0} diff --git a/web/kanban.js b/web/kanban.js index 3748d92..607f0c0 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -229,6 +229,8 @@ const BRAVE_FLAG='brave://flags/#file-system-access-api'; // Numbered so a folder listing shows them in the flow's order. const STAGE_FOLDERS={rec:'1. Arte recebida',tra:'2. Arte conferida',imp:'2. Arte conferida',rev:'2. Arte conferida',fin:'3. Finalizado'}; const KEEP_FINISHED_DAYS=30; +// The pickup receipts (item 14): the counter's print queue watches this one. +const RECEIPTS_FOLDER='Recibos'; const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(navigator.userAgent)?'downloads':'none', brave:!!navigator.brave,handle:null,granted:false,downloads:false,since:null, saved:new Map(),busy:false,status:'',error:'',last:null,lastSig:null}; @@ -291,7 +293,7 @@ function folderCard(){ : integration({name,state:'Desligada',tone:'off',summary:'No Firefox, baixa sozinho os arquivos que entram em Arte conferida; as três pastas pedem o Chrome ou o Edge.', actions:[act('Ligar',()=>setDownloads(true))],details:how}); }else if(!h){ - row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho os arquivos dos pedidos em três pastas: Arte recebida, Arte conferida e Finalizado.', + row=integration({name,state:'Desligada',tone:'off',summary:'Salva sozinho os arquivos dos pedidos em três pastas, Arte recebida, Arte conferida e Finalizado, e o recibo de cada retirada em Recibos.', actions:[act('Escolher pasta',chooseFolder)], details:[node('p','Escolha uma vez a pasta principal, na rede do servidor: o Kanban cria dentro dela as três pastas e move o arquivo conforme o card anda. '+ 'Os arquivos levam o número do pedido no nome. Funciona neste computador, com o Kanban aberto e um usuário que vê todos os pedidos, como o de Gestão.')]}); @@ -305,6 +307,7 @@ function folderCard(){ ['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'], node('p','Dentro de “'+h.name+'”: o arquivo do pedido chega em Arte recebida, passa para Arte conferida quando o card vai para lá '+ '(e fica lá enquanto imprime e na Revisão) e vai para Finalizado quando o pedido é finalizado, onde fica '+KEEP_FINISHED_DAYS+' dias.'), + node('p','Pedido de retirada que chega em Finalizado: o recibo para a bobina de 80 mm vai para '+RECEIPTS_FOLDER+', uma vez só, por um dos computadores com a pasta ligada.'), node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai das pastas. Arquivo trocado: a versão antiga sai. '+ 'Pedidos que já estavam imprimindo quando a pasta foi escolhida não são baixados. Se este computador ficar desligado, '+ 'ao voltar ele busca também o que passou nesse tempo, cada arquivo na pasta da etapa em que o pedido está. Deixe o Kanban aberto neste computador.')], @@ -405,7 +408,7 @@ async function syncFolder(force=false){ try{ if(stages)await makeStageFolders(); const held=stages?[...new Set([...FOLDER.saved.values()].map(r=>r.order).filter(Boolean))].slice(-1000):[]; - const {files,states}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null}); + const {files,states,receipts=[]}=await api('/queue/folder',{early:stages,held,since:stages?FOLDER.since||await folderSince():null}); const wanted=new Map(files.map(f=>[f.order+':'+f.item,f])); const where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads'; let removed=0, moved=0, saved=0; @@ -446,9 +449,22 @@ async function syncFolder(force=false){ } saved++; } + // Each pickup receipt saved once, by the computer that takes it, so the + // counter's queue never prints one twice; one this computer could not + // save goes back for another to take. Written whole, then named .pdf. + let printed=0; + for(const r of receipts){ + try{await api('/orders/'+r.order+'/receipt/claim',{});}catch(e){if(e.status===409)continue;throw e;} + try{ + const res=await fetch('/api/operator/orders/'+r.order+'/receipt'); + if(!res.ok||!res.body)throw new Error('não foi possível gerar '+r.name+' (erro '+res.status+').'); + await writeWhole(await stageDir(RECEIPTS_FOLDER),r.name,res.body);printed++; + }catch(e){await api('/orders/'+r.order+'/receipt/release',{}).catch(()=>{});throw e;} + } FOLDER.lastSig=sig;FOLDER.error=''; FOLDER.status=''; if(saved)say((stages?'Salvos ':'Baixados ')+saved+' arquivo(s) em '+where+'.'); + if(printed)say(printed+' recibo(s) de retirada salvos em '+RECEIPTS_FOLDER+'.'); if(moved)say(moved+' arquivo(s) mudaram de pasta com o pedido.'); if(removed)say(removed+' arquivo(s) de pedidos cancelados, excluídos, em correção, trocados ou finalizados há mais de '+KEEP_FINISHED_DAYS+' dias saíram das pastas.'); }catch(e){ @@ -783,6 +799,7 @@ function card(order){ ? badge('✓ Prova OK','ok','Conferida por '+order.proof_ok_by+' em '+when(order.proof_ok_at)) : badge('Prova','warn',order.snapshot.proof?'O cliente pediu uma prova antes de imprimir':'Pedido acima de 10 m: prova antes do resto')); } + if(!order.cancelled_at&&order.picked_up_at)flags.append(badge('✓ Retirado','ok','Retirado em '+when(order.picked_up_at)+' por '+order.picked_up_by)); const redo=(order.reworks||[]).filter(r=>r.authorized!==false); if(!order.cancelled_at&&redo.length)flags.append(badge('Retrabalho','bad',redo.map(r=>REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join('\n'))); // Arte tratada (Dropstar, 2026-10-27): the final is not the customer's art, someone prepared it. @@ -1066,7 +1083,40 @@ function moves(order){ reason.append(text,sendFix); reason.onsubmit=async e=>{e.preventDefault();sendFix.disabled=true;try{await move(order,'cor',text.value.trim());}catch(error){say(error.message,true);sendFix.disabled=false;}}; const contactNow=waitingContact(order)?contactNotice(order,may('produce')):null; - box.append(...(waiting?[waiting]:[]),...(contactNow?[contactNow]:[]),...(step?[step]:[]),row,...(sub.children.length?[sub]:[]),...forms.filter(f=>!f.parentNode));return box; + const pickup=order.state==='fin'&&isPickup(order)?pickupBox(order):null; + box.append(...(waiting?[waiting]:[]),...(contactNow?[contactNow]:[]),...(step?[step]:[]),row,...(pickup?[pickup]:[]), + ...(sub.children.length?[sub]:[]),...forms.filter(f=>!f.parentNode));return box; +} +// Pickup (item 14): the receipt, to print again, and "Retirado", which closes +// the cycle with who handed the order over and the photo of the signed receipt. +const isPickup=order=>order.snapshot.freight?.service==='pickup'; +function pickupBox(order){ + const box=node('div',undefined,'pickup'); + const actions=node('div',undefined,'buttons'); + const paper=button('Recibo',()=>window.open('/api/operator/orders/'+order.id+'/receipt','_blank','noopener'),'btn ghost'); + paper.title='Abrir o recibo de retirada para imprimir de novo';actions.append(paper); + if(order.picked_up_at){ + const line=node('div',undefined,'file');line.append(icon(ICON_OK),node('span','Retirado em '+when(order.picked_up_at)+' por '+order.picked_up_by,'ok')); + if(order.picked_up_photo)actions.append(downloadButton('Foto do recibo',download(order.picked_up_photo),'btn ghost small')); + box.append(line,actions);return box; + } + if(!may('deliver')){box.append(actions);return box;} + const form=node('form',undefined,'finalform');form.hidden=true; + const photo=node('input');photo.type='file';photo.accept='image/*';photo.setAttribute('aria-label','Foto do recibo assinado'); + const field=node('label',undefined,'slot');field.append('Foto do recibo assinado (opcional)',photo); + const go=node('button','Confirmar retirada','btn primary'); + const open=node('button','Retirado','btn primary');open.type='button';open.dataset.pickedUp=''; + const cancel=node('button','Cancelar','linkbtn');cancel.type='button';cancel.onclick=()=>{form.hidden=true;actions.hidden=false;}; + open.onclick=()=>{form.hidden=false;actions.hidden=true;}; + actions.prepend(open);form.append(field,go,cancel); + form.onsubmit=async e=>{e.preventDefault();go.disabled=true; + try{ + const uid=photo.files[0]?await dtfUpload(photo.files[0],{api,startPath:'/orders/'+order.id+'/pickup-uploads', + scope:'operator:pickup:'+order.id,progress:text=>say(text)}):null; + await api('/orders/'+order.id+'/picked-up',{photo:uid}); + await load();say('Pedido #'+order.number+' marcado como retirado.'); + }catch(error){say(error.message,true);go.disabled=false;}}; + box.append(actions,form);return box; } function contactNotice(order,canClear){ const box=node('div',undefined,'callout contact');