feat: deleting an order frees its files from storage

A deleted order's files stayed in R2 until they expired on their own, up
to 30 days. Deleting now expires its finals, the customer's corrections
and the generated PDFs at once, and its originals too unless it was a
test order, whose quote can still be paid. A file another order or an
open quote still uses is kept. The worker removes them within a minute.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-08 10:25:18 -03:00
parent 3db528a373
commit 2a2a783ff7
2 changed files with 75 additions and 2 deletions

View File

@@ -439,6 +439,14 @@ def delete_order(uid: UUID, user=Depends(can('manage'))):
test = payments.is_test(row)
if not test and not row.get('cancelled_at'):
raise HTTPException(409, 'Cancele o pedido antes de excluir. Só pedidos cancelados ou de teste podem ser excluídos.')
# Its files leave storage too: the finals, corrections and generated PDFs,
# and the customer's originals unless the quote can still be paid (a test
# order's). The worker deletes them within a minute.
originals = {str(u) for item in row['snapshot'].get('items') or [] for u in item.get('uploads') or []}
produced = {str(r['upload_id']) for r in c.execute('''SELECT upload_id FROM dtf_local.order_files WHERE order_id=%s
UNION SELECT upload_id FROM dtf_local.print_files WHERE order_id=%s AND upload_id IS NOT NULL''',
(uid, uid)).fetchall()}
candidates = produced - originals if test else produced | originals
for table in ('movements', 'order_files', 'print_files'):
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (uid,))
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',))
@@ -446,11 +454,33 @@ def delete_order(uid: UUID, user=Depends(can('manage'))):
if not test:
c.execute('UPDATE dtf_local.quotes SET discarded_at=COALESCE(discarded_at,now()), discarded_by=COALESCE(discarded_by,%s) WHERE id=%s',
(user, row['quote_id']))
freed = release_files(c, candidates)
audit('order_deleted', order=row['number'], test=test, operator=user,
reason=row.get('cancel_reason') or '')
reason=row.get('cancel_reason') or '', files_released=freed)
return {'ok': True}
def release_files(c, uploads):
"""Expire these uploads now, except any another order or an open quote
still uses: a customer can buy the same file again. Returns how many."""
free = []
for upload in uploads:
used = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.print_files WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i
WHERE i->'uploads' ? %s
UNION ALL SELECT 1 FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i
WHERE q.discarded_at IS NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.orders x WHERE x.quote_id=q.id)
AND i->'uploads' ? %s
LIMIT 1''', (upload, upload, upload, upload)).fetchone()
if not used:
free.append(upload)
if free:
c.execute('''UPDATE dtf_local.uploads SET expires_at=now() WHERE id=ANY(%s::uuid[])
AND purged_at IS NULL''', (free,))
return len(free)
@router.post('/api/operator/orders/{uid}/cancel')
def cancel_order(uid: UUID, body: Resolution, user=Depends(can('manage'))):
"""A paid order leaves the board but keeps its payment and history. Nothing