diff --git a/app/api/operator.py b/app/api/operator.py index ff9b49d..57d4ede 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -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 diff --git a/tests/order_actions_test.py b/tests/order_actions_test.py index 2285add..027bd85 100644 --- a/tests/order_actions_test.py +++ b/tests/order_actions_test.py @@ -84,7 +84,50 @@ def run(): assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (paid_order,)).fetchone() assert c.execute('SELECT discarded_at FROM dtf_local.quotes WHERE id=%s', (paid_quote,)).fetchone()['discarded_at'] assert str(paid_quote) not in listed() - print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel, then delete') + + # Deleting frees the order's files from storage, but not a file another order uses, + # nor a test order's originals, whose quote can still be paid. + files = {name: uuid4() for name in ('original', 'shared', 'final', 'pdf', 'test_original', 'test_final')} + other_order, other_quote, gone_quote, gone_order, test2_quote, test2_order = (uuid4() for _ in range(6)) + with db.connect() as c: + for name, fid in files.items(): + c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete, + expires_at,scan_state) VALUES(%s,%s,%s,1,%s,'m',true,now()+interval '20 days','clean')''', + (fid, owner, name + '.png', f'test/{fid}')) + def place(quote, order, uploads, provider, cancelled): + content = {'customer': {'mail': mail}, 'items': [{'mode': 'file', 'uploads': [str(u) for u in uploads]}], + 'total_cents': 1490} + c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) + VALUES(%s,%s,%s,'actions-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb(content), Jsonb(content))) + c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,cancelled_at,cancelled_by,cancel_reason) + VALUES(%s,%s,%s,%s,%s,%s,%s,%s)''', (order, quote, owner, Jsonb(content), Jsonb({'provider': provider, 'id': '1'}), + 'now()' if cancelled else None, 'x' if cancelled else None, + 'teste' if cancelled else None)) + place(gone_quote, gone_order, [files['original'], files['shared']], 'mercadopago', True) + place(other_quote, other_order, [files['shared']], 'mercadopago', False) + place(test2_quote, test2_order, [files['test_original']], 'teste', False) + for order, fid in ((gone_order, files['final']), (test2_order, files['test_final'])): + 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','ok','t')''', (uuid4(), order, fid)) + c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index,status,upload_id) + VALUES(%s,%s,0,'ready',%s)''', (uuid4(), gone_order, files['pdf'])) + try: + client.call(f'/operator/orders/{gone_order}/delete', {}, operator=True) + client.call(f'/operator/orders/{test2_order}/delete', {}, operator=True) + with db.connect() as c: + expired = {name for name, fid in files.items() if c.execute( + 'SELECT expires_at<=now() AS e FROM dtf_local.uploads WHERE id=%s', (fid,)).fetchone()['e']} + assert expired == {'original', 'final', 'pdf', 'test_final'}, expired + finally: + with db.connect() as c: + for order in (gone_order, other_order, test2_order): + c.execute('DELETE FROM dtf_local.order_files WHERE order_id=%s', (order,)) + c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (order,)) + c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,)) + c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([gone_quote, other_quote, test2_quote],)) + c.execute('DELETE FROM dtf_local.uploads WHERE id=ANY(%s)', (list(files.values()),)) + print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel, then delete ' + 'and free their files') finally: with db.connect() as c: for oid in filter(None, (test_order, paid_order, newer_order)):