"""The print room's files: queue, folders, downloads and the order viewer.""" from datetime import datetime, timedelta, timezone from typing import Literal from uuid import UUID from fastapi import APIRouter, Depends, HTTPException from pydantic import Field from ... import hotfolder, receipt from ...core import db from ...core.auth import audit, can, operator from ...core.models import StrictModel from ...printjobs import file_prefix from ...runtime import storage from ...scanning import require_clean from .common import FINAL_OK router = APIRouter() def named_files(rows): """Each file named after its order and item, so a folder of them stays readable, with a link straight to storage.""" files, names = [], set() for row in rows: prefix = file_prefix(row['number'], row['item_index']) # Generated before 2026-10-23, a file was called pedido-23-item-1. older = f"pedido-{row['number']}-item-{row['item_index'] + 1}" name = row['name'] if name.startswith(older): name = prefix + name[len(older):] # DTF-23-item-1 or, generated again, DTF-23-v2-item-1: already named. elif not name.startswith(f"DTF-{row['number']}-"): name = f"{prefix}-{name}" stem, dot, ext = name.rpartition('.') copy = 2 while name in names: name = f'{stem} ({copy}).{ext}' if dot else f'{ext} ({copy})' copy += 1 names.add(name) files.append({'order': str(row['order_id']), 'state': row['state'], 'number': row['number'], 'item': row['item_index'] + 1, 'name': name, 'upload_id': str(row['upload_id']), 'url': storage.download(row['object_key'], name)}) return files def print_ready(c, states, only=None, paid_after=None): """The file to print for each item of the orders in these stages, in queue order: the approved final, or before approval the generated print file (unless the customer has sent a correction since). `only` narrows it to these orders, `paid_after` to the orders paid since then.""" ids = None if only is None else list(only) rows = c.execute(f'''SELECT o.id AS order_id,o.state,o.number,f.item_index,f.upload_id,u.object_key,u.name, COALESCE(o.queue_key, extract(epoch FROM o.created_at)) AS position FROM dtf_local.orders o JOIN dtf_local.order_files f ON f.order_id=o.id JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.cancelled_at IS NULL AND {FINAL_OK} UNION ALL SELECT o.id,o.state,o.number,p.item_index,pp.upload_id,u.object_key,u.name, COALESCE(o.queue_key, extract(epoch FROM o.created_at)) FROM dtf_local.orders o JOIN dtf_local.print_files p ON p.order_id=o.id JOIN dtf_local.print_parts pp ON pp.order_id=p.order_id AND pp.item_index=p.item_index JOIN dtf_local.uploads u ON u.id=pp.upload_id WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.state IN ('rec','tra') AND o.cancelled_at IS NULL AND p.status='ready' AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean' AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='final' AND f.active AND f.item_index=p.item_index) AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='correction') ORDER BY position,order_id,item_index,name''', (list(states), ids, ids, paid_after, paid_after, list(states), ids, ids, paid_after, paid_after)).fetchall() return rows @router.get('/api/operator/orders/{uid}/view') def view_files(uid: UUID, user=Depends(operator)): """What "Abrir e conferir" shows (item 7): each item's generated PNG, part by part, with links to its pieces, then the customer's originals, which have only their picture.""" with db.connect() as c: order = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() if not order: raise HTTPException(404, 'Pedido não encontrado.') made = c.execute('''SELECT item_index, detail FROM dtf_local.print_files WHERE order_id=%s AND status='ready' ORDER BY item_index''', (uid,)).fetchall() parts = c.execute('''SELECT p.item_index, p.part, p.upload_id, u.name FROM dtf_local.print_parts p JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE p.order_id=%s AND u.purged_at IS NULL ORDER BY p.item_index, p.part''', (uid,)).fetchall() pictured = {str(r['upload_id']) for r in c.execute( 'SELECT upload_id FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s)', ([UUID(u) for item in order['snapshot']['items'] for u in item['uploads']],)).fetchall()} items = order['snapshot']['items'] many = len(items) > 1 files = [] for row in made: mine = [p for p in parts if p['item_index'] == row['item_index']] details = {d.get('name'): d for d in row['detail'].get('parts') or []} for part in mine: tiles = (details.get(part['name']) or {}).get('tiles') label = (f"Item {row['item_index'] + 1}" if many else 'Arquivo') + \ (f" · parte {part['part']}/{len(mine)}" if len(mine) > 1 else '') files.append({'name': part['name'], 'label': label, 'item': row['item_index'], 'manifest': tiles and {**tiles, 'urls': [ [storage.view(f"originals/tiles/{part['upload_id']}/{k}/{i}.png", 'image/png') for i in range(level['strips'])] for k, level in enumerate(tiles['levels'])]}}) for index, item in enumerate(items): for n, upload in enumerate(item['uploads']): files.append({'name': ('Original ' + str(n + 1)) if len(item['uploads']) > 1 else 'Original', 'label': (f'Item {index + 1} · ' if many else '') + 'original' + (f' {n + 1}' if len(item['uploads']) > 1 else ''), 'item': index, 'manifest': None, 'picture': f'/api/operator/uploads/{upload}/thumbnail' if upload in pictured else None}) return {'files': files} @router.get('/api/operator/orders/{uid}/folder-files') def folder_files(uid: UUID, user=Depends(can('produce'))): """What each item's file is called in the order's stage folder, as the automatic folders save it: "Tratar a arte" shows where to open it.""" with db.connect() as c: row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() if not row: raise HTTPException(404, 'Pedido não encontrado.') files = named_files(print_ready(c, (row['state'],), only=[uid])) return {'state': row['state'], 'files': [{'item': f['item'], 'name': f['name']} for f in files]} @router.get('/api/operator/queue/finals') def queue_finals(auto: bool = False, user=Depends(can('print'))): """The approved final files of every order in the print queue (Arte conferida). The browser downloads them straight from storage: a zip of multi-GB sheets would go through the server.""" with db.connect() as c: files = named_files(print_ready(c, ('tra',))) # The automatic folder asks whenever the queue changes; only a person's download is logged. if not auto: audit('queue_finals_downloaded', operator=user, files=len(files)) return {'files': files} class FolderSync(StrictModel): early: bool = False held: list[UUID] = Field(default_factory=list, max_length=1000) # When the folders were chosen: the orders paid since are fetched whatever # their stage, so what passed while the computer was off is not lost. since: datetime | None = None @router.post('/api/operator/queue/hot') def queue_hot(user=Depends(can('print'))): """For a computer with the automatic folders: the parts it should write into the machines' hot folders now, claimed for it alone; those written and not yet taken by Flexi, to see whether they still are; and those to delete, withdrawn from cards that left Imprimindo (item 10).""" with db.connect() as c: due = hotfolder.claim(c, user) keys = {str(r['upload_id']): r['object_key'] for r in c.execute( 'SELECT id AS upload_id, object_key FROM dtf_local.uploads WHERE id=ANY(%s)', ([r['upload_id'] for r in due],)).fetchall()} if due else {} watched = hotfolder.watched(c) return {'folder': hotfolder.PRINTING_FOLDER, 'write': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name'], 'url': storage.download(keys[str(r['upload_id'])], r['name'])} for r in due], 'watch': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']} for r in watched if r['state'] == 'written'], 'withdraw': [{'id': r['id'], 'order': str(r['order_id']), 'folder': r['folder'], 'name': r['name']} for r in watched if r['state'] == 'withdraw']} class HotReport(StrictModel): state: Literal['written', 'released', 'consumed', 'gone'] @router.post('/api/operator/queue/hot/{part_id}') def report_hot(part_id: int, body: HotReport, user=Depends(can('print'))): """What a computer saw of a part: written, not written, taken by Flexi, or deleted after it was withdrawn.""" with db.connect() as c: applied = hotfolder.report(c, part_id, body.state, user) if applied and body.state == 'written': audit('hot_folder_written', part=part_id, operator=user) return {'ok': applied} @router.post('/api/operator/queue/folder') def queue_folder(body: FolderSync, user=Depends(can('print'))): """What the Kanban's automatic folders should hold. `early` is Dropstar's stage folders (2026-10-26): the files of orders in Arte recebida and Arte conferida, and, for the orders the folders already hold, their files while they print, are checked in Revisão and sit in Finalizado, so one taken out of a folder can be fetched again when the order moves on. With `since`, also every order paid after the folders were chosen, whatever its stage: a computer that was off catches up on what passed meanwhile (Dropstar's rules, 2026-10-26). Without it, only the queue's (Firefox's downloads). `states` answers for the orders the folders hold files of: a stage, 'cancelled', or nothing when the order was deleted, so their files can be removed.""" with db.connect() as c: rows = print_ready(c, ('rec', 'tra') if body.early else ('tra',)) if body.early and body.held: rows += print_ready(c, ('imp', 'rev', 'fin'), only=body.held) if body.early and body.since: seen = {(r['order_id'], r['item_index'], r['upload_id']) for r in rows} rows += [r for r in print_ready(c, ('imp', 'rev', 'fin'), paid_after=body.since) if (r['order_id'], r['item_index'], r['upload_id']) not in seen] 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 [] # The review photos and videos to copy into Revisões/ (front 2). Without # `since`, the last 30 days, so a new computer catches up. since = body.since or datetime.now(timezone.utc) - timedelta(days=30) review_rows = c.execute('''SELECT r.id,r.order_id,o.number,r.upload_id,u.name FROM dtf_local.order_reviews r JOIN dtf_local.orders o ON o.id=r.order_id JOIN dtf_local.uploads u ON u.id=r.upload_id WHERE o.cancelled_at IS NULL AND r.created_at>=%s ORDER BY r.created_at,r.id''', (since,)).fetchall() return {'files': files, '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], 'reviews': [{'id': r['id'], 'order': str(r['order_id']), 'number': r['number'], 'upload_id': str(r['upload_id']), 'name': r['name']} for r in review_rows]} @router.get('/api/operator/uploads/{uid}/download') 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: raise HTTPException(404, 'Completed upload not found') if row['expires_at'] <= datetime.now(timezone.utc): raise HTTPException(410, 'Artwork retention expired') require_clean(row) 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}