Files
dtf-system/tests/print_file_test.py
Cauê Faleiros 8b7d9f0bdb
All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 4m28s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m17s
feat: "Abrir e conferir", the print file full screen, in pieces (item 7)
The card's "Abrir e conferir" opens the order's print file full screen
(Dropstar's third round, item 7): zoom up to 100% real (one file pixel, one
screen pixel), the position in cm, the order's files one after the other
without closing, and the background behind the transparency light, dark or
checkered, remembered (Dropstar, 2026-10-30). Closed in Arte recebida, it asks
"Está OK?": the class of each item, prefilled with the measure, then
"Mover para Arte conferida" (the final approved, the class kept, the card
moved) or "Tratar a arte".

A 15 m film is loaded like a map: while the PNG is written, its strips of
512 rows go to storage at 100% and at each halving (app/printtiles.py,
originals/tiles/<upload>/), and the viewer (web/kanban-viewer.js) fetches
only those on screen. They go when their file expires. Storing a print file
that fails is now an attempt like a failed render, not a claim held for an
hour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 20:10:03 -03:00

272 lines
16 KiB
Python

"""Print files and payment issues, against a running stack.
A paid order must get a print file generated from its approved layout, which
the operator can download and approve as the final file without re-uploading
anything. Artwork the generator cannot read goes to hand preparation with a
reason, and a paid notification that did not become an order stays on the
Kanban until someone records what was done.
Run inside the API container (it needs Pillow): python -m tests.print_file_test
"""
import io
import time
from urllib.request import urlopen
from uuid import uuid4
from PIL import Image
from tests.payment_test import deliver
from tests.smoke_test import Client, approved_quote as approval, upload_bytes
PX_PER_CM = 300 / 2.54
def px(cm):
return int(round(cm * PX_PER_CM))
def download_png(client, upload_id):
link = client.call('/operator/uploads/' + str(upload_id) + '/download', operator=True)
with urlopen(link['url'], timeout=30) as response:
image = Image.open(io.BytesIO(response.read()))
assert image.format == 'PNG' and image.mode == 'RGBA', (image.format, image.mode)
return image
CUSTOMER = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'print-test@example.test'}
def artwork(kind='PNG'):
image = Image.new('RGBA', (600, 300), (0, 0, 0, 0))
for x in range(40, 560):
for y in range(40, 260):
image.putpixel((x, y), (220, 30, 60, 255))
out = io.BytesIO()
if kind == 'PDF':
image.convert('RGB').save(out, 'PDF', resolution=72)
else:
image.save(out, kind)
return out.getvalue()
def loose_item(uid, copies=2):
"""Two copies of a 20 x 10 cm artwork side by side on 57 cm film."""
placements = [{'source_index': 0, 'copy_index': i, 'x_cm': 20 * i, 'y_cm': 0,
'width_cm': 20, 'length_cm': 10, 'rotation_degrees': 0, 'mirrored': False}
for i in range(copies)]
return {'mode': 'avulsa', 'metres': '0.1', 'grade': 90, 'uploads': [uid],
'production': {'version': 2, 'film_width_cm': 57, 'height_cm': 10,
'sources': [{'upload_id': uid, 'kind': 'artwork', 'width_cm': 20,
'length_cm': 10, 'copies': copies, 'rotation_degrees': 0,
'mirrored': False, 'measurement': 'file'}],
'placements': placements},
'quality_status': 'ok', 'quality_acknowledged': False}
def approved_quote(client, item):
quote = client.call('/quotes', {'request_key': str(uuid4()), 'customer': CUSTOMER,
'items': [item], 'freight': {'service': 'pickup'}})
approved = approval(client, quote, [item])
return quote['id'], approved['total_cents']
def paid_order(client, item):
quote_id, _ = approved_quote(client, item)
return client.call('/orders/dev-paid', {'quote_id': quote_id})
def wait_print(client, oid, wanted):
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
order = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == oid)
rows = order['print_files']
if rows and rows[0]['status'] in ('ready', 'manual', 'failed'):
assert rows[0]['status'] == wanted, rows
return order, rows[0]
time.sleep(1)
raise AssertionError('Print file was not generated in time')
def run():
client = Client()
client.call('/session')
uid = upload_bytes(client, artwork(), name='LOCAL-PRINT-TEST.png')
order = paid_order(client, loose_item(uid))
order, row = wait_print(client, order['id'], 'ready')
assert row['detail']['placements'] == 2 and row['detail']['min_dpi'] == round(600 / (20 / 2.54))
# A 300 DPI PNG on a transparent background (item 13): the layout's 10 cm
# and the 1,5 cm footer band, outside the billed length.
film = download_png(client, row['upload_id'])
assert film.size == (px(57), px(10) + px(1.5)), film.size
assert [p['name'] for p in row['parts']] == ['DTF-%d-item-1.png' % order['number']], row['parts']
for copy in range(2):
assert film.getpixel((px(20 * copy + 10), px(5))) == (220, 30, 60, 255), copy
assert film.getpixel((px(50), px(5)))[3] == 0
assert row['detail']['footer'].startswith('DROPSTAR · Pedido DTF-%d · Item 1/1 · ' % order['number']), row['detail']
print('PASS: paid order generated a 57 x 10 cm PNG print file with both copies and its footer')
# Item 7: "Abrir e conferir" gets the file in pieces, the first of which is
# the top of the film, then the original.
view = client.call('/operator/orders/' + order['id'] + '/view', operator=True)['files']
assert [f['name'] for f in view] == ['DTF-%d-item-1.png' % order['number'], 'Original'], view
manifest = view[0]['manifest']
assert (manifest['width'], manifest['height']) == film.size and manifest['levels'][0]['strips'] >= 1, manifest
with urlopen(manifest['urls'][0][0], timeout=30) as response:
strip = Image.open(io.BytesIO(response.read()))
assert strip.width == film.width and strip.getpixel((px(10), px(3))) == (220, 30, 60, 255)
print('PASS: the viewer gets the print file in pieces')
# The automatic folder, downloading on arrival, gets the generated file
# before anyone approves it; at the queue only, it does not.
oid = order['id']
early = client.call('/operator/queue/folder', {'early': True, 'held': [oid]}, operator=True)
mine = [f for f in early['files'] if f['order'] == oid]
assert [(f['upload_id'], f['state']) for f in mine] == [(str(row['upload_id']), 'rec')], early['files']
assert mine[0]['name'].startswith('DTF-%d-item-1' % order['number']) and early['states'] == {oid: 'rec'}
late = client.call('/operator/queue/folder', {'early': False, 'held': []}, operator=True)
assert not [f for f in late['files'] if f['order'] == oid] and late['states'] == {}
client.call('/operator/queue/folder', {'early': True, 'held': []}, expected=401)
print('PASS: the folder gets a received order\'s generated file early, and only at the queue otherwise')
# The operator approves the generated file as the final one, with no upload,
# and the order can then enter the print queue.
result = client.call('/operator/orders/' + oid + '/final-files',
{'version': order['version'], 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],
'note': 'Generated print file checked'}, operator=True)
version = result['version']
# The file the system generated from the customer's art is not "Arte tratada".
board = client.call('/operator/board', operator=True)['orders']
assert next(o for o in board if o['id'] == oid)['treated'] is None
# Arte conferida is the print queue (2026-10-23).
client.call('/operator/orders/' + oid + '/move', {'state': 'tra', 'version': version}, operator=True)
version += 1
# Printing, the folders still get the file of an order they hold (to take
# it to Finalizado later), and no one else's.
client.call('/operator/orders/' + oid + '/move', {'state': 'imp', 'version': version}, operator=True)
version += 1
held = client.call('/operator/queue/folder', {'early': True, 'held': [oid]}, operator=True)
assert [(f['state'], f['upload_id']) for f in held['files'] if f['order'] == oid] == [('imp', str(row['upload_id']))], held
assert held['states'] == {oid: 'imp'}
others = client.call('/operator/queue/folder', {'early': True, 'held': []}, operator=True)
assert not [f for f in others['files'] if f['order'] == oid], others['files']
# A folder chosen before this order was paid catches up on it, printing or
# not, as a computer that was off does when it comes back; one chosen
# after it does not.
earlier = client.call('/operator/queue/folder', {'early': True, 'held': [], 'since': '2000-01-01T00:00:00Z'},
operator=True)
assert [(f['state'], f['upload_id']) for f in earlier['files'] if f['order'] == oid] == [('imp', str(row['upload_id']))]
later = client.call('/operator/queue/folder', {'early': True, 'held': [], 'since': '2999-01-01T00:00:00Z'},
operator=True)
assert not [f for f in later['files'] if f['order'] == oid], later['files']
# Once queued for printing, the final set can no longer change.
client.call('/operator/orders/' + oid + '/final-files',
{'version': version, 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],
'note': 'again'}, operator=True, expected=409)
print('PASS: generated file approved as final without re-uploading; order queued for printing')
# Item 10: printing, the file goes once into its machine's hot folder for
# its class; Flexi taking it is reported; leaving Imprimindo withdraws
# what Flexi did not take.
tag = uuid4().hex[:6]
machine = client.call('/operator/machines', {'name': f'Hot {tag}', 'products': ['textil']}, operator=True)['id']
try:
client.call('/operator/orders/' + oid + '/machine', {'machine_id': machine}, operator=True)
# No class measured or chosen: the part waits for one.
assert not [p for p in client.call('/operator/queue/hot', {}, operator=True)['write'] if p['order'] == oid]
client.call('/operator/orders/' + oid + '/contraction', {'item_index': 0, 'value': 'C2'}, operator=True)
hot = client.call('/operator/queue/hot', {}, operator=True)
due = [p for p in hot['write'] if p['order'] == oid]
assert hot['folder'] == '3. Imprimindo' and [(p['folder'], p['name']) for p in due] == \
[(f'Hot {tag}/C2', 'DTF-%d-item-1.png' % order['number'])], hot
# Claimed by this computer only: asked again, nobody else gets it.
assert not [p for p in client.call('/operator/queue/hot', {}, operator=True)['write'] if p['order'] == oid]
part = due[0]['id']
assert client.call(f'/operator/queue/hot/{part}', {'state': 'written'}, operator=True)['ok']
client.call('/operator/orders/' + oid + '/contraction', {'item_index': 0, 'value': 'C1'}, operator=True,
expected=409)
watch = client.call('/operator/queue/hot', {}, operator=True)['watch']
assert [p['id'] for p in watch if p['order'] == oid] == [part], watch
assert client.call(f'/operator/queue/hot/{part}', {'state': 'consumed'}, operator=True)['ok']
assert not client.call(f'/operator/queue/hot/{part}', {'state': 'consumed'}, operator=True)['ok']
board = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == oid)
assert board['hot'] == {'parts': 1, 'taken': 1, 'waiting': 0}, board['hot']
print('PASS: the printing file goes once into its machine\'s hot folder for its class')
finally:
client.call('/operator/machines/' + machine, {'name': f'Hot {tag}', 'products': ['textil'], 'active': False},
operator=True)
# A single-page PDF is drawn from its vectors at 300 DPI.
pdf_upload = upload_bytes(client, artwork('PDF'), name='LOCAL-PRINT-TEST.pdf')
pdf_order = paid_order(client, loose_item(pdf_upload))
_, pdf_row = wait_print(client, pdf_order['id'], 'ready')
assert pdf_row['detail']['vector_sources'] == 1 and pdf_row['detail']['min_dpi'] is None, pdf_row
drawn = download_png(client, pdf_row['upload_id'])
red = drawn.getpixel((px(10), px(5)))
assert red[3] == 255 and red[0] > 200 and red[1] < 60, red
print('PASS: PDF artwork drawn into the PNG print file at 300 DPI')
# A customer cannot see or reuse another order's generated file.
other = Client()
other.call('/session')
other.call('/uploads/' + str(row['upload_id']), expected=404)
# Artwork the generator cannot read goes to hand preparation, with a reason.
manual = upload_bytes(client, b'LOCAL PRINT TEST - NOT AN IMAGE', name='LOCAL-PRINT-TEST.cdr')
order = paid_order(client, loose_item(manual, copies=1))
order, row = wait_print(client, order['id'], 'manual')
assert 'não é uma imagem' in row['detail']['reason'], row
rows = client.call('/operator/orders/' + order['id'] + '/print-files', {}, operator=True)
assert rows[0]['status'] == 'pending'
wait_print(client, order['id'], 'manual')
print('PASS: unreadable artwork is routed to hand preparation and can be retried')
# A signed, paid notification for the wrong amount does not become an order;
# it waits on the Kanban until an operator records the resolution.
# Same client, so the same operator session: operator logins share a
# 10-per-15-minutes account limit with every other suite in the run.
quote_id, total = approved_quote(client, loose_item(uid, copies=1))
event_id = 'print-test-underpaid-' + uuid4().hex
outcome = deliver({'event_id': event_id, 'reference': quote_id,
'status': 'approved', 'amount_cents': total - 1})
assert outcome['outcome'].startswith('refused'), outcome
issues = client.call('/operator/payment-events?state=open&limit=100', operator=True)['issues']
issue = next(i for i in issues if i['event_id'] == event_id)
assert client.call('/operator/board', operator=True)['payment_issues_total'] >= 1
client.call('/operator/payment-events/' + issue['id'] + '/resolve', {'note': 'no'},
operator=True, expected=422)
client.call('/operator/payment-events/' + issue['id'] + '/resolve',
{'note': 'Local test: refunded the underpayment'}, operator=True)
client.call('/operator/payment-events/' + issue['id'] + '/resolve',
{'note': 'Local test: second resolution'}, operator=True, expected=404)
issues = client.call('/operator/payment-events?state=open&limit=100', operator=True)['issues']
assert not any(i['event_id'] == event_id for i in issues)
resolved_page = client.call('/operator/payment-events?state=resolved&limit=100', operator=True)
assert resolved_page['total'] >= 1
resolved = resolved_page['issues']
done = next(i for i in resolved if i['event_id'] == event_id)
assert done['resolution'] == 'Local test: refunded the underpayment' and done['resolved_by']
print('PASS: refused paid notification is listed until an operator resolves it, then kept as history')
# The send log pages by id and filters by destination, status, event and order.
page = client.call('/operator/events?limit=2', operator=True)
assert len(page['events']) == 2 and page['total'] > 2
second = client.call('/operator/events?limit=2&offset=2', operator=True)
assert all(e['id'] < page['events'][-1]['id'] for e in second['events'])
assert second['total'] == page['total']
tiny = client.call('/operator/events?provider=tiny&event=payment_approved&status=delivered&limit=100', operator=True)
assert tiny['events'] and all(e['provider'] == 'tiny' and e['payload']['event'] == 'payment_approved'
and e['delivered_at'] for e in tiny['events'])
client.call('/operator/events?provider=email', operator=True, expected=422)
client.call('/operator/events?limit=500', operator=True, expected=422)
quotes = client.call('/operator/quotes?kind=approved&limit=1&offset=0', operator=True)
assert 'total' in quotes and len(quotes['quotes']) <= 1
finished = client.call('/operator/orders/finished?limit=1', operator=True)
if finished['orders']:
last = finished['orders'][-1]
client.call('/operator/orders/finished?before_created_at=' + last['created_at'].replace('+', '%2B')
+ '&before_id=' + last['id'], operator=True)
print('PASS: send log, payment history and finished orders page and filter')
if __name__ == '__main__':
run()