Files
dtf-system/app/artwork.py
Cauê Faleiros 742ea5f5bd
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 7m54s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m27s
fix: the choice of items to reprint ends with the print, a new final or "Gerar de novo", so a later correction always goes to the machine (#105)
Kept until Finalizado, an old choice would leave out an item corrected after
it (an order back from Revisão, or a second correction). It is now cleared
when the pass to Revisão records it, when a final changes and when the files
are generated again; the next entry to the queue works it out anew. An
integration test follows the whole reprint: first print, one item corrected,
the queue, the hot folder with that item only, Revisão.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-27 14:19:37 -03:00

129 lines
7.7 KiB
Python

"""Attaching artwork to an order: the rules shared by customers and operators.
A customer submits a correction and an operator submits the final set; both go
through the same checks, so the rule about what may be attached, when, and what
it does to retention lives in one place.
"""
from datetime import datetime, timedelta, timezone
from uuid import UUID, uuid4
from fastapi import HTTPException
from .runtime import upload_row, storage
from .printpng_validate import require_final_png
from .scanning import require_clean
def generated_owner(c, order, ref, kind):
"""The owner to look a generated print file up under, or None if it is not one.
A generated file may be approved as the final for the item it was made
from, and only while that item still has its original artwork: after a
customer correction it reproduces a layout nobody wants printed.
"""
generated = c.execute('''SELECT p.item_index FROM dtf_local.print_parts p JOIN dtf_local.print_files f
ON f.order_id=p.order_id AND f.item_index=p.item_index
WHERE p.order_id=%s AND p.upload_id=%s AND f.status='ready' ''', (order['id'], ref.upload_id)).fetchone()
if not generated:
return None
if kind != 'final' or generated['item_index'] != ref.item_index:
raise HTTPException(422, 'O arquivo gerado só pode ser o final do próprio item.')
if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1",
(order['id'],)).fetchone():
raise HTTPException(409, 'O cliente enviou uma correção depois que este arquivo foi gerado. Use a correção ou envie outro arquivo.')
return c.execute('SELECT owner FROM dtf_local.uploads WHERE id=%s', (ref.upload_id,)).fetchone()['owner']
def correction_owner(c, order, ref, kind):
"""The owner of a customer correction approved as it is, or None if it is not one.
A corrected file is often ready to print: the operator approves it as the
final of the item it corrects, without downloading and sending it back.
"""
if kind != 'final':
return None
row = c.execute('''SELECT u.owner FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id
WHERE f.order_id=%s AND f.upload_id=%s AND f.kind='correction' AND f.active AND f.item_index=%s''',
(order['id'], ref.upload_id, ref.item_index)).fetchone()
return row and row['owner']
def submit_files(c, order, body, identity, kind, actor):
if order['version'] != body.version:
raise HTTPException(409, 'O pedido mudou. Atualize a página e envie de novo.')
# Arte conferida is the print queue (2026-10-23): what is in it keeps its finals.
if kind == 'final' and order['state'] not in ('rec','cor'):
raise HTTPException(409, 'O arquivo final só muda antes de Arte conferida, a fila. Volte o pedido para Arte recebida para trocar.')
if kind == 'correction' and order['state'] != 'cor':
raise HTTPException(409, 'Este pedido não está esperando correção.')
if len({f.upload_id for f in body.files}) != len(body.files):
raise HTTPException(422, 'O mesmo arquivo foi enviado duas vezes.')
count = len(order['snapshot']['items'])
if any(f.item_index >= count for f in body.files):
raise HTTPException(422, 'Item do pedido inválido.')
if kind == 'final' and {f.item_index for f in body.files} != set(range(count)):
raise HTTPException(422, 'Envie um arquivo final para cada item do pedido.')
original_ids = [UUID(uid) for item in order['snapshot']['items'] for uid in item['uploads']]
first = c.execute('SELECT min(created_at) AS first FROM dtf_local.uploads WHERE id=ANY(%s)', (original_ids,)).fetchone()['first']
expiry = first + timedelta(days=30)
if expiry <= datetime.now(timezone.utc):
raise HTTPException(410, 'Os arquivos deste pedido expiraram (30 dias).')
# A final already approved for its item may stay as it is beside a new
# one for another item: "Tratar a arte" replaces only the item treated
# (Dropstar, 2026-10-29). Something has to change, though.
current = {(row['upload_id'], row['item_index']) for row in c.execute(
"SELECT upload_id,item_index FROM dtf_local.order_files WHERE order_id=%s AND kind='final' AND active",
(order['id'],)).fetchall()} if kind == 'final' else set()
kept = {ref.upload_id for ref in body.files if (ref.upload_id, ref.item_index) in current}
if kept and len(kept) == len(body.files):
raise HTTPException(409, 'Estes já são os arquivos finais. Envie o arquivo novo.')
revived = set()
for ref in body.files:
if ref.upload_id in kept:
continue
corrected = correction_owner(c, order, ref, kind)
generated = None if corrected else generated_owner(c, order, ref, kind)
upload = upload_row(c, ref.upload_id, corrected or generated or identity, lock=True)
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, and a
# generated file or a correction that was this item's final and
# stopped counting (a step back, Correção): it is turned back on
# (Sentry DTF-WEB-10).
rows = c.execute('SELECT order_id,item_index,kind FROM dtf_local.order_files WHERE upload_id=%s'
+ (" AND kind<>'correction'" if corrected else ''), (ref.upload_id,)).fetchall()
if rows and (corrected or generated) and all(
r['order_id'] == order['id'] and r['kind'] == 'final' and r['item_index'] == ref.item_index for r in rows):
revived.add(ref.upload_id)
elif rows:
raise HTTPException(409, 'Este arquivo já está no pedido. Envie uma nova versão.')
# A new customer correction supersedes every final prepared from earlier
# artwork, including finals uploaded while this order was in correction.
if kind == 'correction':
c.execute("UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind IN ('correction','final')", (order['id'],))
else:
c.execute('UPDATE dtf_local.order_files SET active=false WHERE order_id=%s AND kind=%s', (order['id'],kind))
# A final changed: which items go to the machine again is worked out
# anew when the order enters the queue (#105).
c.execute('UPDATE dtf_local.orders SET print_items=NULL WHERE id=%s', (order['id'],))
for ref in body.files:
if ref.upload_id in kept or ref.upload_id in revived:
c.execute("UPDATE dtf_local.order_files SET active=true WHERE order_id=%s AND upload_id=%s AND kind='final'",
(order['id'], ref.upload_id))
continue
c.execute('INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by) VALUES(%s,%s,%s,%s,%s,%s,%s)',
(uuid4(),order['id'],ref.upload_id,ref.item_index,kind,body.note,actor))
# The order's window, whatever the upload's own hold was.
c.execute('UPDATE dtf_local.uploads SET expires_at=%s WHERE id=%s', (expiry,ref.upload_id))
c.execute('UPDATE dtf_local.orders SET version=version+1,updated_at=now() WHERE id=%s', (order['id'],))
if kind == 'final':
# Artwork approval, not commercial quote approval, starts original cleanup.
# An original approved as its own print file is kept as the final.
finals = [ref.upload_id for ref in body.files]
c.execute("UPDATE dtf_local.uploads SET expires_at=LEAST(expires_at,now()+interval '7 days') WHERE id=ANY(%s) AND NOT id=ANY(%s)",
(original_ids, finals))
return {'ok': True, 'version': order['version']+1, 'expires_at': expiry}