Files
dtf-system/docs/guias/telas/seed.py
Cauê Faleiros c8857a5bf5
All checks were successful
Build and deploy / Validate source (push) Successful in 47s
Build and deploy / Integration suite on a real stack (push) Successful in 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m20s
feat: the team no longer gets alert e-mails; the Kanban user form drops the option
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 09:37:41 -03:00

296 lines
14 KiB
Python

"""Fictional orders for the guides' screenshots, on the LOCAL stack only.
Before: python -m ops.launch_reset --confirmar APAGAR --contas (worker), and in
the db container delete every operator but operator@example.test, the
machines, payment_events, mail_queue and cnpj_names. Then, from the repo:
docker compose -f compose.local.yaml exec -T -e SITE_BASE_URL=http://site -e SITE_HOST_HEADER=localhost -e PYTHONPATH=/app api python - < docs/guias/telas/seed.py
It makes orders #1-#11 in every Kanban stage, a quote above 50 m, a refused
payment, users and machines, and Pedro's account; see telas/README.md.
"""
import io
import math
import random
import time
from uuid import uuid4
from PIL import Image, ImageDraw
from psycopg.types.json import Jsonb
from app.core import db
from tests.smoke_test import Client, approved_quote, item_spec, upload_bytes
random.seed(7)
PALETTES = {
'aurora': [(255, 122, 89), (255, 196, 61), (61, 64, 91), (129, 178, 154)],
'ipe': [(244, 196, 48), (232, 93, 117), (45, 49, 66), (255, 255, 255)],
'mare': [(0, 119, 182), (0, 180, 216), (144, 224, 239), (3, 4, 94)],
'rocha': [(214, 40, 40), (247, 127, 0), (252, 191, 73), (0, 48, 73)],
'norte': [(46, 196, 182), (231, 29, 54), (255, 159, 28), (1, 22, 39)],
}
def check(base, weights):
rem = sum(int(n) * w for n, w in zip(base, weights)) % 11
return 0 if rem < 2 else 11 - rem
def cnpj(seed):
base = f'{seed:08d}0001'
d1 = check(base, [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2])
d2 = check(base + str(d1), [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2])
return base + f'{d1}{d2}'
def cpf(seed):
base = f'{seed:09d}'
d1 = check(base, range(10, 1, -1))
d2 = check(base + str(d1), range(11, 1, -1))
return base + f'{d1}{d2}'
def star(draw, cx, cy, r, color):
points = []
for i in range(10):
angle = math.pi / 2 + i * math.pi / 5
radius = r if i % 2 == 0 else r * 0.45
points.append((cx + radius * math.cos(angle), cy - radius * math.sin(angle)))
draw.polygon(points, fill=color)
def sticker(draw, x, y, size, palette, kind):
a, b, c, d = palette
if kind == 0:
draw.ellipse((x, y, x + size, y + size), fill=a)
draw.ellipse((x + size * .14, y + size * .14, x + size * .86, y + size * .86), fill=c)
star(draw, x + size / 2, y + size / 2, size * .28, b)
elif kind == 1:
draw.rounded_rectangle((x, y + size * .15, x + size, y + size * .85), radius=size * .18, fill=b)
for i in range(4):
draw.rectangle((x + size * (.12 + i * .2), y + size * .3, x + size * (.2 + i * .2), y + size * .7), fill=c)
elif kind == 2:
draw.polygon([(x + size / 2, y), (x + size, y + size / 2), (x + size / 2, y + size), (x, y + size / 2)], fill=d)
draw.ellipse((x + size * .3, y + size * .3, x + size * .7, y + size * .7), fill=a)
else:
draw.ellipse((x, y, x + size, y + size), fill=b)
draw.pieslice((x + size * .1, y + size * .1, x + size * .9, y + size * .9), 200, 340, fill=a)
draw.ellipse((x + size * .35, y + size * .55, x + size * .65, y + size * .85), fill=c)
def sheet(palette, width_cm, length_cm, px_per_cm=12):
"""A transparent finished sheet of stickers, as customers send."""
w, h = int(width_cm * px_per_cm), int(length_cm * px_per_cm)
image = Image.new('RGBA', (w, h), (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
size = int(9 * px_per_cm)
gap = int(1.2 * px_per_cm)
cols = max(1, (w - gap) // (size + gap))
margin = (w - cols * size - (cols - 1) * gap) // 2
y, row = gap, 0
while y + size <= h - gap:
for col in range(cols):
sticker(draw, margin + col * (size + gap), y, size, palette, (row + col) % 4)
y += size + gap
row += 1
return image
def png(image, max_side=None):
if max_side:
image = image.copy()
image.thumbnail((max_side, max_side))
out = io.BytesIO()
image.save(out, 'PNG', optimize=True)
return out.getvalue()
def put_thumbnail(client, uid, data):
from urllib.request import Request
from tests.smoke_test import BASE, with_host
request = Request(BASE + f'/api/uploads/{uid}/thumbnail', data=data, method='PUT',
headers=with_host({'Content-Type': 'image/png'}))
with client.opener.open(request, timeout=30) as response:
assert response.status == 200
def order(customer, palette, mode, metres, grade, delivery=None):
client = Client()
client.call('/session')
film = 28.5 if mode in ('uv', 'uvfile') else 57
art = sheet(PALETTES[palette], film, float(metres) * 100)
uid = upload_bytes(client, png(art), name=f'{palette}-folha.png')
put_thumbnail(client, uid, png(art, 520))
item = item_spec(mode, metres, grade, uid)
draft = {'request_key': str(uuid4()), 'items': [item], 'customer': customer,
'freight': {'service': 'pickup'}}
if delivery:
draft['freight'] = {'service': 'mock-standard', 'postal_code': delivery['postal_code']}
draft['destination'] = delivery
quote = client.call('/quotes', draft)
approved_quote(client, quote, [item])
paid = client.call('/orders/dev-paid', {'quote_id': quote['id']})
return client, paid
def board_order(client, oid):
return next(o for o in client.call('/operator/board', operator=True)['orders'] if o['id'] == oid)
def wait_print(client, oid):
deadline = time.monotonic() + 120
while time.monotonic() < deadline:
found = board_order(client, oid)
files = found.get('print_files') or []
if files and files[0]['status'] in ('ready', 'manual', 'failed'):
return found, files[0]
time.sleep(1)
raise AssertionError('no print file')
def approve_final(client, oid):
found, row = wait_print(client, oid)
return client.call(f'/operator/orders/{oid}/final-files',
{'version': found['version'], 'files': [{'item_index': 0, 'upload_id': str(row['upload_id'])}],
'note': 'Arquivo gerado conferido'}, operator=True)['version']
def move(client, oid, version, state, reason=''):
return client.call(f'/operator/orders/{oid}/move', {'state': state, 'version': version, 'reason': reason},
operator=True)['version']
def to(client, paid, stages, correction=None):
oid = paid['id']
version = paid.get('version', 0)
for stage in stages:
if stage == 'final':
version = approve_final(client, oid)
elif stage == 'cor':
version = move(client, oid, version, 'cor', correction)
else:
version = move(client, oid, version, stage)
return oid, version
AURORA = {'name': 'Juliana Martins', 'cnpj': cnpj(31920485), 'zap': '16991234567', 'mail': 'contato@estampariaaurora.com.br'}
IPE = {'name': 'Pedro Alves', 'cnpj': cnpj(27450318), 'zap': '16992345678', 'mail': 'pedidos@camisetasipe.com.br'}
MARE = {'name': 'Rafael Costa', 'cnpj': cnpj(40871236), 'zap': '16993456789', 'mail': 'studio@maremoda.com.br'}
MARIA = {'name': 'Maria Oliveira', 'cnpj': cpf(529982247), 'zap': '16994567890', 'mail': 'maria.oliveira@email.com'}
BIANCA = {'name': 'Bianca Rocha', 'cnpj': cpf(318507264), 'zap': '16995678901', 'mail': 'bianca.rocha@email.com'}
NORTE = {'name': 'Lucas Ferreira', 'cnpj': cnpj(52640197), 'zap': '16996789012', 'mail': 'compras@graficanorte.com.br'}
RIBEIRAO = {'recipient': 'Maria Oliveira', 'street': 'Rua São Sebastião', 'number': '820', 'complement': 'Sala 4',
'district': 'Centro', 'city': 'Ribeirão Preto', 'state': 'SP', 'postal_code': '14015040'}
def order300(customer, palette, metres, delivery):
client = Client()
client.call('/session')
art = sheet(PALETTES[palette], 57, float(metres) * 100, px_per_cm=118)
uid = upload_bytes(client, png(art), name='aurora-folha-300dpi.png')
put_thumbnail(client, uid, png(art, 520))
item = item_spec('file', metres, 100, uid)
draft = {'request_key': str(uuid4()), 'items': [item], 'customer': customer,
'freight': {'service': 'mock-standard', 'postal_code': delivery['postal_code']}, 'destination': delivery}
quote = client.call('/quotes', draft)
approved_quote(client, quote, [item])
return client, client.call('/orders/dev-paid', {'quote_id': quote['id']})
# Finalizado, Imprimindo, Fila, Arte conferida, Correção, Arte recebida.
client, paid = order(BIANCA, 'rocha', 'file', '1.20', 100)
to(client, paid, ['final', 'tra', 'fil', 'imp', 'fin'])
client, paid = order(AURORA, 'aurora', 'file', '2.10', 100)
to(client, paid, ['final', 'tra', 'fil', 'imp', 'fin'])
client, paid = order(MARE, 'mare', 'uvfile', '1.00', 92)
to(client, paid, ['final', 'tra', 'fil', 'imp'])
client, paid = order(IPE, 'ipe', 'file', '1.60', 100)
to(client, paid, ['final', 'tra', 'fil'])
client, paid = order(AURORA, 'aurora', 'file', '1.30', 100)
to(client, paid, ['final', 'tra', 'fil'])
client, paid = order(MARIA, 'mare', 'file', '1.40', 85, RIBEIRAO)
to(client, paid, ['tra'])
client, paid = order(IPE, 'ipe', 'file', '2.30', 78)
to(client, paid, ['cor'], 'A arte ipe-folha.png está com fundo branco. Envie com fundo transparente.')
client, paid = order(MARE, 'mare', 'uvfile', '1.10', 92)
oid, version = to(client, paid, ['cor'], 'A arte está com 96 DPI. Envie em 300 DPI para não perder nitidez.')
fixed = sheet(PALETTES['mare'], 28.5, 110)
correction = upload_bytes(client, png(fixed), name='mare-folha-300dpi.png')
put_thumbnail(client, correction, png(fixed, 520))
client.call(f'/customer/orders/{oid}/corrections',
{'version': version, 'files': [{'item_index': 0, 'upload_id': correction}],
'note': 'Mandei de novo em 300 DPI.'})
client, paid = order(AURORA, 'aurora', 'file', '1.80', 100)
wait_print(client, paid['id'])
client, paid = order(BIANCA, 'rocha', 'file', '1.00', 100)
wait_print(client, paid['id'])
client.call(f"/operator/orders/{paid['id']}/contact",
{'waiting': True, 'note': 'Confirmar se quer a arte espelhada'}, operator=True)
# A quote above 50 m waits for the team.
client = Client()
client.call('/session')
art = sheet(PALETTES['norte'], 57, 400)
uid = upload_bytes(client, png(art), name='norte-folha.png')
put_thumbnail(client, uid, png(art, 520))
item = item_spec('file', '55.00', 100, uid)
client.call('/quotes', {'request_key': str(uuid4()), 'items': [item], 'customer': NORTE,
'freight': {'service': 'pickup'}})
# A payment that could not become an order, for the Pagamentos tab.
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.payment_events(id,provider,event_id,reference,status,amount_cents,payload,
processed_at,outcome) VALUES(%s,'mercadopago',%s,%s,'approved',4590,%s,now(),%s)''',
(uuid4(), f'{random.randint(10**10, 10**11)}:approved', str(uuid4()),
Jsonb({'provider': 'mercadopago', 'status': 'approved'}),
'refused: amount 4590 does not match the quote total 5190'))
c.execute("UPDATE dtf_local.operators SET name='Equipe Compor' WHERE email='operator@example.test'")
# Order #11: a 300 DPI sheet in Arte conferida, delivered by Correios PAC,
# for the panel shots (the "approve the final file" step).
client, paid = order300(MARIA, 'aurora', '1.00', RIBEIRAO)
wait_print(client, paid['id'])
to(client, paid, ['tra'])
# The corrected order back in Arte conferida, where the correction is approved.
client = Client()
o8 = next(o for o in client.call('/operator/board', operator=True)['orders'] if o['number'] == 8)
client.call(f"/operator/orders/{o8['id']}/move", {'state': 'tra', 'version': o8['version'], 'reason': ''}, operator=True)
# Delivery orders show a real carrier, not the local simulated one.
with db.connect() as c:
c.execute("""UPDATE dtf_local.orders SET snapshot=jsonb_set(snapshot,'{freight,description}','"Correios PAC"')
WHERE jsonb_typeof(snapshot->'destination')='object'""")
# Users and machines for the Usuários tab (all fictional).
admin = Client()
textil = admin.call('/operator/machines', {'name': 'Têxtil 1', 'products': ['textil']}, operator=True)['id']
admin.call('/operator/machines', {'name': 'UV 1', 'products': ['uv']}, operator=True)
for name, email, role, machines in (
('Ana Souza', 'ana@dropstar.test', 'admin', []), ('Diego Ramos', 'diego@dropstar.test', 'gestao', []),
('Bruno Souza', 'bruno@dropstar.test', 'operador', [textil]), ('Carla Dias', 'carla@dropstar.test', 'vendedor', [])):
admin.call('/operator/users', {'name': name, 'email': email, 'role': role, 'password': 'senha-de-exemplo-123',
'machines': machines}, operator=True)
# Pedro's account (Camisetas Ipê): it brings his orders, one in correction, for Minha conta.
from tests.smoke_test import register
with db.connect() as c:
doc = c.execute("SELECT snapshot->'customer'->>'cnpj' AS d FROM dtf_local.orders WHERE number=7").fetchone()['d']
pedro = Client(); pedro.call('/session')
register(pedro, {**IPE, 'cnpj': doc}, 'senha-de-exemplo-123')
# Spread the orders over recent days, so Números and the cards look lived-in.
from datetime import datetime, timedelta, timezone
now = datetime.now(timezone.utc)
plan = {1: (timedelta(days=6), 3), 2: (timedelta(days=4), 4), 3: (timedelta(hours=7), 1), 4: (timedelta(hours=3), 1),
5: (timedelta(hours=3.5), 1), 6: (timedelta(hours=2), 1), 7: (timedelta(hours=2.5), 1), 8: (timedelta(hours=3), 1),
9: (timedelta(hours=1), 1), 10: (timedelta(minutes=40), 1), 11: (timedelta(hours=2), 1)}
with db.connect() as c:
for number, (ago, gap) in plan.items():
oid = c.execute('SELECT id FROM dtf_local.orders WHERE number=%s', (number,)).fetchone()['id']
base = last = now - ago
for i, m in enumerate(c.execute('SELECT id FROM dtf_local.movements WHERE order_id=%s ORDER BY id', (oid,)).fetchall()):
last = base + timedelta(hours=gap * (i + 1))
c.execute('UPDATE dtf_local.movements SET created_at=%s WHERE id=%s', (last, m['id']))
c.execute('UPDATE dtf_local.orders SET created_at=%s, updated_at=%s WHERE id=%s', (base, last, oid))
print('seeded for the screenshots')