"""Discarding an unpaid quote, deleting a test order, marking an order as waiting for contact, cancelling a paid one. Run inside the API container: python -m tests.order_actions_test """ from urllib.parse import urlencode from uuid import uuid4 from psycopg.types.json import Jsonb from app import payments from app.core import db from tests.smoke_test import Client def run(): client = Client() owner = uuid4() mail = f'actions-{uuid4().hex[:8]}@example.test' approved = {'customer': {'mail': mail}, 'items': [], 'total_cents': 1490} discard, test_quote, paid_quote, paid_order = uuid4(), uuid4(), uuid4(), uuid4() newer_quote, newer_order = uuid4(), uuid4() test_order = None try: with db.connect() as c: for qid in (discard, test_quote, paid_quote, newer_quote): 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())''', (qid, owner, uuid4(), Jsonb({'customer': {'mail': mail}, 'items': []}), Jsonb(approved))) c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)''', (paid_order, paid_quote, owner, Jsonb(approved), Jsonb({'provider': 'mercadopago', 'id': '1'}))) listed = lambda: {q['id'] for q in client.call('/operator/quotes?' + urlencode({'kind': 'approved', 'q': mail}), operator=True)['quotes']} assert {str(discard), str(test_quote)} <= listed() # Discarded: gone from the list, and no payment can make it an order. client.call(f'/operator/quotes/{discard}/discard', {}, operator=True) assert str(discard) not in listed() with db.connect() as c: try: payments.approved_quote(c, discard) raise AssertionError('a discarded quote was payable') except payments.PaymentRefused as refusal: assert str(refusal) == 'quote was discarded' client.call(f'/operator/quotes/{paid_quote}/discard', {}, operator=True, expected=409) # A test order is deleted, and its quote is unpaid again. test_order = client.call(f'/operator/quotes/{test_quote}/test-order', {}, operator=True)['id'] assert str(test_quote) not in listed() client.call(f'/operator/orders/{test_order}/delete', {}, operator=True) with db.connect() as c: assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (test_order,)).fetchone() test_order = None assert str(test_quote) in listed() # "Aguardando contato": a mark with what to agree, on the board until cleared. client.call(f'/operator/orders/{paid_order}/contact', {'waiting': True, 'note': ' '}, operator=True, expected=422) client.call(f'/operator/orders/{paid_order}/contact', {'waiting': True, 'note': 'Confirmar a cor do fundo'}, operator=True) marked = {o['id']: o for o in client.call('/operator/board', operator=True)['orders']}[str(paid_order)] assert marked['contact_note'] == 'Confirmar a cor do fundo' and marked['contact_since'], marked assert marked['contact_by'] and marked['state'] == 'rec' client.call(f'/operator/orders/{paid_order}/contact', {'waiting': False}, operator=True) cleared = {o['id']: o for o in client.call('/operator/board', operator=True)['orders']}[str(paid_order)] assert cleared['contact_since'] is None and cleared['contact_note'] is None # A paid order is cancelled with a reason, kept, and can no longer move. # A paid order in progress is not deleted: it is cancelled first. client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True, expected=409) client.call(f'/operator/orders/{paid_order}/cancel', {'note': 'x'}, operator=True, expected=422) client.call(f'/operator/orders/{paid_order}/cancel', {'note': 'Cliente desistiu'}, operator=True) board = client.call('/operator/board', operator=True) order = next(o for o in board['orders'] if o['id'] == str(paid_order)) assert order['cancelled_at'] and order['cancel_reason'] == 'Cliente desistiu' client.call(f'/operator/orders/{paid_order}/move', {'state': 'tra', 'version': order['version'], 'reason': ''}, operator=True, expected=409) client.call(f'/operator/orders/{paid_order}/cancel', {'note': 'de novo'}, operator=True, expected=404) # Dragged within its column: first paid first, unless moved; moving on resets it. with db.connect() as c: c.execute("UPDATE dtf_local.orders SET created_at=now()-interval '1 hour' WHERE id=%s", (paid_order,)) c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,created_at) VALUES(%s,%s,%s,%s,%s,now())''', (newer_order, newer_quote, owner, Jsonb(approved), Jsonb({'provider': 'teste', 'id': 't'}))) client.call(f'/operator/orders/{newer_order}/queue', {'before': str(paid_order)}, operator=True) with db.connect() as c: keys = {str(r['id']): r['k'] for r in c.execute( 'SELECT id, COALESCE(queue_key, extract(epoch FROM created_at)) AS k FROM dtf_local.orders WHERE id=ANY(%s)', ([paid_order, newer_order],)).fetchall()} assert keys[str(newer_order)] < keys[str(paid_order)], keys client.call(f'/operator/orders/{newer_order}/queue', {}, operator=True, expected=422) # Cancelled, it can be deleted; its quote is discarded, not unpaid again. client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True) with db.connect() as c: 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() # 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)): for table in ('movements', 'order_files', 'print_files'): c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (oid,)) c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{oid}:%',)) c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,)) c.execute('DELETE FROM dtf_local.orders WHERE quote_id=ANY(%s)', ([discard, test_quote, paid_quote, newer_quote],)) c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([discard, test_quote, paid_quote, newer_quote],)) if __name__ == '__main__': run()