Files
dtf-system/tests/kanban_test.py
Cauê Faleiros a712c69aca
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Integration suite on a real stack (push) Successful in 5m44s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m22s
fix: align proof, treatment, metrics and site videos with PDF
2026-11-06 15:27:48 -03:00

225 lines
14 KiB
Python

"""Kanban artwork pictures, quote filters and the search over orders and quotes.
Run against the local stack: python3 -m tests.kanban_test
"""
import base64
import secrets
from datetime import date, timedelta
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request
from uuid import uuid4
import httpx
import psycopg
from psycopg.types.json import Jsonb
from app.core import db
from tests.smoke_test import BASE, Client, with_host
# A 1 x 1 PNG: the endpoint reads the type from the bytes.
PNG = base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==')
def raw(client, method, path, data=None, content_type=None):
"""A request whose body is not JSON; returns (status, headers, body)."""
headers = with_host({'Content-Type': content_type} if content_type else {})
request = Request(BASE + '/api' + path, data=data, headers=headers, method=method)
try:
with client.opener.open(request, timeout=30) as response:
return response.status, response.headers, response.read()
except HTTPError as exc:
return exc.code, exc.headers, exc.read()
def session_upload(client, name):
"""A completed, clean upload owned by this client's session. The bytes are
not the subject here, so none are stored."""
sid = next(c.value for c in client.jar if c.name == 'dtf_session')
uid = uuid4()
with db.connect() as c:
owner = c.execute('SELECT owner FROM dtf_local.sessions WHERE id=%s', (sid,)).fetchone()['owner']
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,'none',true,now()+interval '1 day','clean')''', (uid, owner, name, f'originals/{uid}'))
return str(uid)
def run():
tag = secrets.token_hex(4)
mail = f'kanban-{tag}@example.test'
cnpj_digits = '11222333' + f'{int(tag, 16) % 1000000:06d}'
cnpj = f'{cnpj_digits[:2]}.{cnpj_digits[2:5]}.{cnpj_digits[5:8]}/{cnpj_digits[8:12]}-{cnpj_digits[12:]}'
customer = {'mail': mail, 'cnpj': cnpj, 'zap': '(16) 98765-' + str(4000 + int(tag[:3], 16) % 1000)}
client = Client()
client.call('/session')
uid = session_upload(client, f'kanban-{tag}.cdr')
# The customer's browser sends the picture of its own upload; nothing else.
assert raw(client, 'PUT', f'/uploads/{uid}/thumbnail', PNG, 'image/png')[0] == 200
assert raw(client, 'PUT', f'/uploads/{uid}/thumbnail', b'<svg onload=alert(1)>', 'image/png')[0] == 415
assert raw(client, 'PUT', f'/uploads/{uid}/thumbnail', PNG + b'\0' * 300_001, 'image/png')[0] == 413
stranger = Client()
stranger.call('/session')
assert raw(stranger, 'PUT', f'/uploads/{uid}/thumbnail', PNG, 'image/png')[0] == 404
# Only an operator reads it, as an image the browser may keep for a while.
assert raw(client, 'GET', f'/operator/uploads/{uid}/thumbnail')[0] == 401
client.call('/operator/board', operator=True)
status, headers, body = raw(client.operator_client, 'GET', f'/operator/uploads/{uid}/thumbnail')
assert status == 200 and body == PNG, status
assert headers['Content-Type'] == 'image/png' and 'private' in headers['Cache-Control']
assert headers['X-Content-Type-Options'] == 'nosniff'
owner = uuid4()
pending, approved, paid, order_id = uuid4(), uuid4(), uuid4(), uuid4()
item = lambda mode, warning=False: {'mode': mode, 'uploads': [uid], 'metres': '1.00', 'billed_metres': '1.00',
'grade': 100, 'quality_status': 'warning' if warning else 'ok'}
draft = lambda *items: {'customer': customer, 'items': list(items), 'freight': {'service': 'pickup'}}
try:
with db.connect() as c:
for qid, content, accepted in [(pending, draft(item('avulsa', warning=True)), None),
(approved, draft(item('uvfile')), {'items': [], 'total_cents': 6990}),
(paid, draft(item('file')), {'items': [], 'total_cents': 1490})]:
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved)
VALUES(%s,%s,%s,%s,%s,%s)''', (qid, owner, uuid4(), 'kanban-fixture', Jsonb(content),
Jsonb(accepted) if accepted else None))
number = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
VALUES(%s,%s,%s,%s,%s,'site') RETURNING number''',
(order_id, paid, owner, Jsonb({**draft(item('file')), 'total_cents': 1490}),
Jsonb({'provider': 'teste', 'id': f'kanban-{tag}'}))).fetchone()['number']
def quotes(**params):
page = client.call('/operator/quotes?' + urlencode({'q': mail, **params}), operator=True)
return page, {q['id'] for q in page['quotes']}
page, ids = quotes(kind='pending')
assert ids == {str(pending)} and page['total'] == 1, ids
assert str(uid) in page['thumbnails']
assert quotes(kind='pending', layout='avulsa', flag='ressalva')[1] == {str(pending)}
assert quotes(kind='pending', product='uv')[1] == set()
assert quotes(kind='approved', product='uv', layout='folha')[1] == {str(approved)}
assert quotes(kind='approved', layout='avulsa')[1] == set()
# CNPJ and WhatsApp match by digits, whatever the punctuation typed.
assert client.call('/operator/quotes?' + urlencode({'kind': 'approved', 'q': '11222333'}),
operator=True)['total'] >= 1
# LIKE's own wildcards are literal: "%%" is not "everything".
assert str(pending) not in {q['id'] for q in client.call(
'/operator/quotes?' + urlencode({'kind': 'pending', 'q': '%%'}), operator=True)['quotes']}
# One search: the paid order (by customer and by number) and the two unpaid quotes.
found = client.call('/operator/search?' + urlencode({'q': mail}), operator=True)
assert {o['id'] for o in found['orders']} == {str(order_id)}
assert {q['id'] for q in found['quotes']} == {str(pending), str(approved)}
assert str(uid) in found['thumbnails']
by_number = client.call('/operator/search?' + urlencode({'q': f'#{number}'}), operator=True)
assert str(order_id) in {o['id'] for o in by_number['orders']}
assert client.call('/operator/search?q=a', operator=True, expected=422)
board = client.call('/operator/board', operator=True)
assert str(uid) in board['thumbnails']
# Numbers count real paid orders only: this test order counts once it is not one.
before = client.call('/operator/stats?days=7', operator=True)
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET payment=%s WHERE id=%s",
(Jsonb({'provider': 'mercadopago', 'id': f'kanban-{tag}'}), order_id))
after = client.call('/operator/stats?days=7', operator=True)
assert len(after['daily']) == 7
assert (after['orders'], after['cents']) == (before['orders'] + 1, before['cents'] + 1490), (before, after)
assert after['daily'][-1]['orders'] == before['daily'][-1]['orders'] + 1
assert after['waiting']['rec']['orders'] == before.get('waiting', {}).get('rec', {}).get('orders', 0) + 1
# Each way in apart (D-21), all three listed even when empty.
assert [o['origin'] for o in after['origins']] == ['site', 'dropflow', 'atendimento']
site = lambda stats: next(o for o in stats['origins'] if o['origin'] == 'site')
assert (site(after)['orders'], site(after)['cents']) == (site(before)['orders'] + 1, site(before)['cents'] + 1490)
# No order without an origin, and only the three (D-21, D-35).
for origin in (None, 'whatsapp'):
try:
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
VALUES(%s,%s,%s,'{}','{}',%s)''', (uuid4(), approved, owner, origin))
except (psycopg.errors.NotNullViolation, psycopg.errors.CheckViolation):
pass
else:
raise AssertionError(f'an order with origin {origin!r} was accepted')
client.call('/operator/stats?days=3', operator=True, expected=422)
# Or two dates: the same week asked as a range gives the same numbers.
week = client.call(f"/operator/stats?start={after['start']}&end={after['end']}", operator=True)
assert (week['orders'], week['cents'], len(week['daily'])) == (after['orders'], after['cents'], 7), week
one = client.call(f"/operator/stats?start={after['end']}&end={after['end']}", operator=True)
assert len(one['daily']) == 1 and one['daily'][0] == after['daily'][-1]
client.call(f"/operator/stats?start={after['end']}&end={after['start']}", operator=True, expected=422)
client.call(f"/operator/stats?start={after['start']}", operator=True, expected=422)
client.call('/operator/stats?start=2025-01-01&end=2026-12-31', operator=True, expected=422)
assert isinstance(after['machines'], list)
# An order sent back counts once per stage; its passages are counted apart.
with db.connect() as c:
for step, (frm, to) in enumerate((('rec', 'tra'), ('tra', 'cor'), ('cor', 'tra'), ('tra', 'imp'))):
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
VALUES(%s,%s,%s,'kanban-test','',false,now()+%s*interval '1 second')''', (order_id, frm, to, step + 1))
moved = client.call('/operator/stats?days=7', operator=True)
tra_before = after['stages'].get('tra', {'orders': 0, 'passages': 0})
assert moved['stages']['tra']['orders'] == tra_before['orders'] + 1, moved['stages']
assert moved['stages']['tra']['passages'] == tra_before['passages'] + 2, moved['stages']
# Its time in a stage is the sum of its passages: on a day of its own, one
# hour in Arte conferida, a correction, and another hour there read as 2 h.
alone = (date(2001, 1, 1) + timedelta(days=int(tag, 16) % 3000)).isoformat()
with db.connect() as c:
c.execute('UPDATE dtf_local.orders SET created_at=%s::timestamptz WHERE id=%s', (f'{alone} 08:00-03', order_id))
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (order_id,))
for hour, (frm, to) in enumerate((('rec', 'tra'), ('tra', 'cor'), ('cor', 'tra'), ('tra', 'imp')), start=9):
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason,back,created_at)
VALUES(%s,%s,%s,'kanban-test','',false,%s::timestamptz)''', (order_id, frm, to, f'{alone} {hour}:00-03'))
day = client.call(f'/operator/stats?start={alone}&end={alone}', operator=True)
assert day['stages']['tra'] == {'orders': 1, 'passages': 2, 'average_hours': 2.0}, day['stages']
assert day['stages']['rec']['average_hours'] == 1.0, day['stages']
# Half an hour of it waiting for the customer does not count (D-38).
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.contact_waits(order_id, started_at, ended_at)
VALUES(%s, %s::timestamptz, %s::timestamptz)''', (order_id, f'{alone} 09:15-03', f'{alone} 09:45-03'))
day = client.call(f'/operator/stats?start={alone}&end={alone}', operator=True)
assert day['stages']['tra']['average_hours'] == 1.5, day['stages']
assert day['stages']['rec']['average_hours'] == 1.0, day['stages']
# The company's name from the registry: on the board, and found by the search.
from app import cnpj as registry
# Even after a failed try (the worker may have had no internet), a lookup stores the names.
registry.company(cnpj_digits, db.connect, transport=httpx.MockTransport(lambda request: httpx.Response(
200, json={'razao_social': f'KANBAN {tag} COMERCIO LTDA', 'nome_fantasia': f'Loja {tag}'})))
board = client.call('/operator/board', operator=True)
assert board['names'][cnpj_digits] == {'legal': f'KANBAN {tag} COMERCIO LTDA', 'trade': f'Loja {tag}'}
found = client.call('/operator/search?' + urlencode({'q': f'loja {tag}'}), operator=True)
assert str(order_id) in {o['id'] for o in found['orders']}, found
# A failed lookup is kept and not repeated within the day.
with db.connect() as c:
c.execute('DELETE FROM dtf_local.cnpj_names WHERE cnpj=%s', (cnpj_digits,))
registry.resolve(db.connect, limit=200, transport=httpx.MockTransport(lambda request: httpx.Response(503)))
with db.connect() as c:
row = c.execute('SELECT fetched_at,failed_at FROM dtf_local.cnpj_names WHERE cnpj=%s', (cnpj_digits,)).fetchone()
assert row['fetched_at'] is None and row['failed_at'] is not None
assert cnpj_digits not in registry.pending(c, 500)
Client().call('/operator/stats', expected=401)
# "Fazer backup agora": recorded for the backup service, shown as asked.
with db.connect() as c:
c.execute('DELETE FROM dtf_local.backup_requests')
Client().call('/operator/backup/run', {}, expected=401)
client.call('/operator/backup/run', {}, operator=True)
assert client.call('/operator/board', operator=True)['providers']['backup']['requested'] is True
with db.connect() as c:
c.execute('DELETE FROM dtf_local.backup_requests')
assert client.call('/operator/board', operator=True)['providers']['backup']['requested'] is False
print('PASS: artwork pictures (owner only, images only), quote filters, the order/quote search, the numbers '
'and a backup asked for now')
finally:
with db.connect() as c:
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (order_id,))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([pending, approved, paid],))
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (uid,))
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s', (uid,))
c.execute('DELETE FROM dtf_local.cnpj_names WHERE cnpj=%s', (cnpj_digits,))
if __name__ == '__main__':
run()