docs: the launch status, and the guides' screenshots made reproducible
All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 3m18s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m0s

CONTEXT.md records what is live and what is left before go-live.
docs/guias/telas holds the seed of fictional orders and the screenshot script
the guides' images came from, with the steps to take them again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-19 13:54:13 -03:00
parent b2e718449b
commit ea3c20ba1e
4 changed files with 509 additions and 0 deletions

View File

@@ -295,6 +295,23 @@ supports subsequent corrections or scoped enhancements.
## Known implementation status
### Launch status (2026-10-19)
Live on dropstardtf.com.br (Site) and kanban.dropstardtf.com.br (Kanban), with
Mercado Pago in production, Correios PAC/SEDEX and Jadlog, SMTP e-mail and the
daily R2 backup. The system sends no WhatsApp: the client's n8n does, from
Tiny's situação (middleware in the separate api-tiny-n8n project). Tiny orders
are filled in as the store's own (app/tiny.py: payment, carrier, expected
date), with Dropstar's ids where the app may not list them.
Before go-live: Dropstar's category, seller and tag for Site orders in Tiny; a
supervised test order (`python -m app.tiny_probe pedido ... --confirmar`); the
n8n "isDTFIMP" node skipping orders whose numero_ecommerce starts with "DTF-";
then TINY_STATUS_UPDATES=true and TINY_ADAPTER=tiny, a backup,
`ops.launch_reset`, a real Pix and card payment refunded, and the pilot with
5 to 10 customers. The guides' screenshots are reproducible from
docs/guias/telas/.
### Kanban automatic folder (agreed in the 2026-10-07 meeting)
The Kanban, open on the print room's computer, saves the files to a folder

View File

@@ -0,0 +1,27 @@
# Screenshots for the guides
The images in `operador/img/` and `site/img/` come from the local stack seeded
with fictional customers. To take them again:
1. Start the local stack with the CI settings (`docs/LOCAL_SETUP.md`), clear it as
`seed.py` says, and run `seed.py` in the api container.
2. Start a container from the browser-tests image on the stack's network and
give it internet too, so Google Fonts load (the stack's network is internal):
```bash
docker run -d --name dtf-shots --network dtf-sistema_local \
-v "$PWD/docs/guias/telas:/g" -v /tmp/telas:/shots -e CHROME_BIN=/usr/bin/chromium \
dtf-sistema-browser-tests sleep 1800
docker network connect bridge dtf-shots
docker exec dtf-shots node /g/shots.mjs kanban
docker exec dtf-shots node /g/shots.mjs site
```
`site` also needs `/g/email-pedido.html`, the order e-mail rendered with
`app.mail_html.order_paid`.
3. Copy what changed from `/tmp/telas` into the `img/` folders (the print queue
column is cropped to 444x700 px), print with `../imprimir.sh` and check every
page: a page is fixed at A4 and cuts what does not fit.
Integrações is shown in its production state with fictional values set in the
page (shots.mjs), since the local stack has no Tiny or Mercado Pago.

295
docs/guias/telas/seed.py Normal file
View File

@@ -0,0 +1,295 @@
"""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, alerts in (
('Ana Souza', 'ana@dropstar.test', 'admin', [], True), ('Diego Ramos', 'diego@dropstar.test', 'gestao', [], True),
('Bruno Souza', 'bruno@dropstar.test', 'operador', [textil], False), ('Carla Dias', 'carla@dropstar.test', 'vendedor', [], False)):
admin.call('/operator/users', {'name': name, 'email': email, 'role': role, 'password': 'senha-de-exemplo-123',
'machines': machines, 'alerts': alerts}, 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')

170
docs/guias/telas/shots.mjs Normal file
View File

@@ -0,0 +1,170 @@
// Screenshots for the guides, from the local stack seeded with fictional
// orders (seed.py). Runs in the browser-tests image: node shots.mjs <which>.
import {spawn} from 'node:child_process';
import {mkdtemp,readFile,writeFile,mkdir} from 'node:fs/promises';
import {tmpdir} from 'node:os';
const OUT='/shots';
const which=process.argv[2]||'kanban';
const profile=await mkdtemp(tmpdir()+'/dtf-shots-');
const chrome=spawn(process.env.CHROME_BIN||'/usr/bin/chromium',[
'--headless=new','--lang=pt-BR','--disable-gpu','--no-first-run','--no-sandbox','--hide-scrollbars','--font-render-hinting=none',
'--unsafely-treat-insecure-origin-as-secure=http://site,http://kanban',
'--remote-debugging-port=0','--user-data-dir='+profile,'about:blank'],{stdio:['ignore','ignore','pipe']});
const pause=ms=>new Promise(r=>setTimeout(r,ms));
async function waitFor(fn,what,timeout=30000){const end=Date.now()+timeout;while(Date.now()<end){try{if(await fn())return;}catch{}await pause(200);}throw new Error('Timeout: '+what);}
class Page{
constructor(ws){this.ws=ws;this.n=0;this.p=new Map();ws.onmessage=e=>{const d=JSON.parse(e.data);if(d.id&&this.p.has(d.id)){const x=this.p.get(d.id);this.p.delete(d.id);d.error?x.j(d.error):x.r(d.result);}};}
call(m,params={}){return new Promise((r,j)=>{const id=++this.n;this.p.set(id,{r,j});this.ws.send(JSON.stringify({id,method:m,params}));});}
async eval(e){const res=await this.call('Runtime.evaluate',{expression:e,awaitPromise:true,returnByValue:true});if(res.exceptionDetails)throw new Error(JSON.stringify(res.exceptionDetails).slice(0,400));return res.result.value;}
async size(w,h){await this.call('Emulation.setDeviceMetricsOverride',{width:w,height:h,deviceScaleFactor:2,mobile:false});await pause(300);}
async rect(selector,pad=0){return this.eval(`(()=>{const el=${selector.startsWith('(')?selector:`document.querySelector(${JSON.stringify(selector)})`};
const r=el.getBoundingClientRect();return {x:Math.max(0,r.left-${pad})+scrollX,y:Math.max(0,r.top-${pad})+scrollY,width:r.width+2*${pad},height:r.height+2*${pad}};})()`);}
async shot(name,clip){
const res=await this.call('Page.captureScreenshot',{format:'png',captureBeyondViewport:true,...(clip?{clip:{...clip,scale:1}}:{})});
await writeFile(`${OUT}/${name}.png`,Buffer.from(res.data,'base64'));console.log('shot',name,clip?Math.round(clip.width)+'x'+Math.round(clip.height):'page');
}
async el(name,selector,pad=0){await pause(250);await this.shot(name,await this.rect(selector,pad));}
}
let port;
await waitFor(async()=>{port=Number((await readFile(profile+'/DevToolsActivePort','utf8')).split('\n')[0]);return port;},'chrome');
async function open(url,w=1440,h=1000){
const tab=await (await fetch(`http://localhost:${port}/json/new?about:blank`,{method:'PUT'})).json();
const ws=new WebSocket(tab.webSocketDebuggerUrl);await new Promise((r,j)=>{ws.onopen=r;ws.onerror=j;});
const p=new Page(ws);await p.call('Runtime.enable');await p.call('Page.enable');await p.size(w,h);
await p.call('Emulation.setLocaleOverride',{locale:'pt-BR'}).catch(()=>{});
await p.call('Network.enable').catch(()=>{});await p.call('Network.setUserAgentOverride',{userAgent:'Mozilla/5.0 Chrome/130 Safari/537.36',acceptLanguage:'pt-BR'}).catch(()=>{});
await p.call('Page.navigate',{url});await waitFor(()=>p.eval('document.readyState==="complete"'),'load '+url);await pause(800);return p;
}
await mkdir(OUT,{recursive:true});
try{
if(which==='kanban'){
const k=await open('http://kanban/',1440,1000);
await waitFor(()=>k.eval('!document.getElementById("login").hidden'),'login form');
await k.el('login','#login',24);
await k.eval(`(()=>{email.value=${JSON.stringify(process.env.OPERATOR_EMAIL||'operator@example.test')};password.value=${JSON.stringify(process.env.OPERATOR_PASSWORD||'local-operator-only')};
document.getElementById('login').requestSubmit();})()`);
await waitFor(()=>k.eval('typeof board!=="undefined"&&!!board&&board.orders.length>0'),'board');
// No refresh while shooting: the timer would repaint over the shots.
// No refresh while shooting: the timer would repaint over the shots.
await k.eval(`(()=>{window.load=async()=>{};})()`);
await pause(1500);
await k.shot('quadro',{x:0,y:0,width:1440,height:700});
const id=n=>`board.orders.find(o=>o.number===${n}).id`;
// The print queue column, top part.
await k.el('fila','(document.querySelector(\'section.col[data-state="fil"]\'))',0).catch(e=>console.log('fila',e.message));
// Panel of an order waiting for its final file.
await k.size(1440,1900);
await k.eval(`document.querySelector('[data-card="'+${id(11)}+'"]').click()`);
await waitFor(()=>k.eval(`!!document.querySelector('[data-order="'+${id(11)}+'"]')`),'panel');await pause(1200);
await k.shot('painel',{...(await k.rect('#panel')),height:900});
await k.el('arquivo-final','#panel .nextstep.lead',0);
await k.eval(`document.querySelector('#panel .more').click()`);await pause(300);
await k.shot('menu',{...(await k.rect('#panel')),height:520});
await k.eval(`document.body.click()`);
// An order in correction, and one whose correction came back.
for(const [n,name] of [[7,'correcao'],[8,'correcao-recebida'],[10,'contato']]){
await k.eval(`closePanel&&closePanel()`).catch(()=>{});await pause(300);
await k.eval(`document.querySelector('[data-card="'+${id(n)}+'"]').click()`);
await waitFor(()=>k.eval(`!!document.querySelector('[data-order="'+${id(n)}+'"]')`),'panel '+n);await pause(1200);
if(name==='correcao-recebida')await k.el(name,'#panel .nextstep.lead',0);
else if(name==='contato')await k.el(name,'#panel .callout.contact',0);
else await k.shot(name,{...(await k.rect('#panel')),height:350});
}
await k.eval(`closePanel&&closePanel()`).catch(()=>{});
await k.size(1440,1000);
// Quotes, payments, numbers.
await k.eval(`document.querySelector('[data-tab="quotes"]').click()`);await pause(1500);
await k.eval(`document.querySelector('#quote-list button, #quote-list [data-quote], #quote-list li')?.click()`).catch(()=>{});await pause(1500);
await k.shot('cotacoes',{x:0,y:0,width:1440,height:1000});
await k.eval(`document.querySelector('[data-tab="payments"]').click()`);await pause(1500);
await k.shot('pagamentos',{x:0,y:0,width:1440,height:300});
await k.eval(`document.querySelector('[data-tab="stats"]').click()`);await pause(2000);
await k.shot('numeros',{x:0,y:0,width:1440,height:900});
// Users and the edit dialog.
await k.eval(`document.querySelector('[data-tab="users"]').click()`);await pause(1500);
await k.el('usuarios','#tab-users',0);
await k.eval(`[...document.querySelectorAll('#users-list tr')].find(tr=>tr.textContent.includes('Bruno')).querySelector('button').click()`);await pause(600);
await k.el('usuario-editar','.modal-box',0);
await k.eval(`document.querySelector('.modal').remove()`);
// Integrações as in production, with fictional values; the folder as on the print room's computer.
await k.eval(`document.querySelector('[data-tab="integrations"]').click()`);await pause(1200);
await k.eval(`(()=>{window.syncFolder=async()=>{};window.load=async()=>{};
const now=new Date(),at=h=>new Date(now-h*3600e3).toISOString();
board.tiny={configured:true,connected:true,connected_by:'tiny@dropstar.test',orders_enabled:true,offline:true,connected_at:at(72),renewed_at:at(2)};
board.providers={...board.providers,payment:'mercadopago',
freight:{services:{jadlog:'Jadlog',pac:'Correios PAC',sedex:'Correios SEDEX'},box_cm:['63','15.5','15.5'],production_days:1,
base_kg:'0.3',per_metre_kg:'0.075',cubage_kg_m3:'300',cubed_kg:'4.541',metres_per_box:'60'},
mail:{adapter:'smtp',alerts:2,pending:0,last_sent:at(1),from:'nao-responda@dropstardtf.com.br'},
backup:{last_ok:new Date(now.getFullYear(),now.getMonth(),now.getDate(),3,0).toISOString(),bytes:418000,failed:null,requested:false}};
FOLDER.mode='folder';FOLDER.handle={name:'FlexiPRINT'};FOLDER.granted=true;FOLDER.when='rec';FOLDER.error='';FOLDER.status='';
FOLDER.saved=new Map(Array.from({length:12},(_,i)=>['u'+i,{place:'queue'}]));FOLDER.last=new Date(now-25*60e3);
renderIntegrations();})()`);
await pause(600);
await k.el('integracoes','#integrations',0);
await k.eval(`document.querySelector('#folder-card .integ-more').click()`);await pause(400);
await k.el('pasta','#folder-card',0);
await k.eval(`(()=>{FOLDER.granted=false;OPEN_INTEG.clear();paintFolder();})()`);await pause(400);
await k.el('pasta-liberar','#folder-card',0);
await k.el('aba-aviso','[data-tab="integrations"]',10);
}
if(which==='site'){
// Minha conta: the overview, and an order waiting for a correction.
if(process.argv[3]!=='cart'){const c=await open('http://site/conta/entrar',1440,1000);
await waitFor(()=>c.eval('!!document.getElementById("login")'),'portal');
await c.eval(`(()=>{document.getElementById('email').value='pedidos@camisetasipe.com.br';
document.getElementById('password').value='senha-de-exemplo-123';document.getElementById('login').requestSubmit();})()`);
await pause(2500);
await c.call('Page.navigate',{url:'http://site/conta'});await pause(2500);
await c.eval(`(()=>{for(const el of document.querySelectorAll('body *'))if(el.children.length===0&&el.textContent.includes('Ambiente de desenvolvimento local'))el.closest('div,p,section').style.display='none';window.scrollTo(0,0);})()`);await pause(400);
await c.shot('conta',{x:0,y:0,width:1440,height:540});
const seven=await c.eval(`fetch('/api/customer/orders?page=1&size=10').then(r=>r.json()).then(d=>(d.items.find(i=>i.number===7)||d.items.find(i=>i.state==='cor')).id)`);
await c.call('Page.navigate',{url:'http://site/conta/pedidos?order='+seven});await pause(2500);
await c.eval(`(()=>{for(const el of document.querySelectorAll('body *'))if(el.children.length===0&&el.textContent.includes('Ambiente de desenvolvimento local'))el.closest('div,p,section').style.display='none';window.scrollTo(0,0);})()`);await pause(400);
await c.shot('pedido-correcao',{x:0,y:0,width:1440,height:960});}
// The cart: artworks added for real, then the customer's details and the delivery options.
const s=await open('http://site/',1440,1000);
await waitFor(()=>s.eval(`typeof window.dtfCheckout==="function"&&!!document.querySelector('[data-modo="avulsa"]')`),'site');
await s.eval(`document.querySelector('[data-modo="avulsa"]').click()`);await pause(800);
await s.eval(`(async()=>{
const make=async(name,w,h,draw)=>{const c=document.createElement('canvas');c.width=w;c.height=h;const x=c.getContext('2d');draw(x,w,h);
return new File([await new Promise(r=>c.toBlob(r,'image/png'))],name,{type:'image/png'});};
const files=[await make('logo-frente.png',2362,1417,(x,w,h)=>{x.fillStyle='#F26B1D';x.beginPath();x.roundRect(0,0,w,h,120);x.fill();
x.fillStyle='#FFD23F';x.beginPath();x.arc(w*.24,h/2,h*.32,0,7);x.fill();x.fillStyle='#fff';x.font='bold '+(h*.26)+'px sans-serif';x.fillText('AURORA',w*.44,h*.6);}),
await make('escudo.png',1181,1181,(x,w,h)=>{x.fillStyle='#1B998B';x.beginPath();x.arc(w/2,h/2,w/2,0,7);x.fill();x.fillStyle='#fff';
x.font='bold '+(h*.2)+'px sans-serif';x.textAlign='center';x.fillText('ESCUDO',w/2,h*.57);}),
await make('patrocinio.png',2835,472,(x,w,h)=>{x.fillStyle='#E84855';x.fillRect(0,0,w,h);x.fillStyle='#fff';x.font='bold '+(h*.5)+'px sans-serif';
x.textAlign='center';x.fillText('PATROCÍNIO',w/2,h*.68);})];
const dt=new DataTransfer();files.forEach(f=>dt.items.add(f));
const inp=document.getElementById('inp');inp.files=dt.files;inp.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await waitFor(()=>s.eval('artes.length===3&&artes.every(a=>a.src)'),'artworks measured',30000);
for(const [i,cm,q] of [[0,20,4],[1,10,8],[2,24,3]]){
await s.eval(`(()=>{const set=(sel,v)=>{const el=document.querySelectorAll(sel)[${i}];el.value=v;el.dispatchEvent(new Event('change',{bubbles:true}));};
set('[data-cm]',${cm});set('[data-q]',${q});})()`);await pause(500);
}
await pause(1200);
await s.eval(`(()=>{const c=document.getElementById('cienteOk');if(c&&!c.checked){c.checked=true;c.dispatchEvent(new Event('change',{bubbles:true}));}})()`);
await waitFor(()=>s.eval('!!itemAtual&&itemPodeEnviar(itemAtual)'),'item ready for the cart',60000);
await s.eval(`document.getElementById('bAdd').click()`);
await waitFor(()=>s.eval('location.pathname==="/carrinho"'),'cart page',20000);
await waitFor(()=>s.eval(`document.getElementById('carr').innerText.includes('Arquivos enviados')&&!document.getElementById('carr').innerText.includes('verificando')`),'uploads done',180000);
await s.eval(`(()=>{const g=id=>document.getElementById(id);const fill=(id,v)=>{const el=g(id);el.value=v;el.dispatchEvent(new Event('input',{bubbles:true}));};
fill('fNome','Juliana Martins');fill('fCnpj','31920485000165');fill('fZap','16991234567');fill('fMail','contato@estampariaaurora.com.br');
entrega.tipo='frete';entrega.cep='14015040';g('cepIn').value='14015-040';
entrega.opcoes=[{service:'pac',description:'Correios PAC',days:7,total_cents:2183},{service:'jadlog',description:'Jadlog',days:5,total_cents:2690},
{service:'sedex',description:'Correios SEDEX',days:3,total_cents:4417}];
entrega.servico='pac';entrega.valor=21.83;entrega.dias=7;entrega.cotado=true;
entrega.end={nome:'Juliana Martins',rua:'Rua São Sebastião',num:'820',comp:'Sala 4',bairro:'Centro',cidade:'Ribeirão Preto',uf:'SP'};
for(const [id,k] of [['eNome','nome'],['eRua','rua'],['eNum','num'],['eComp','comp'],['eBairro','bairro'],['eCidade','cidade'],['eUf','uf']])g(id).value=entrega.end[k];
pintaFretes();pintaEntrega();if(typeof pintaPedido==='function')pintaPedido();window.scrollTo(0,0);})()`);
await pause(800);
const h=await s.eval(`Math.ceil(document.getElementById('fretes').getBoundingClientRect().bottom+28)`);
await s.shot('carrinho',{x:0,y:0,width:1440,height:h});
// The order confirmation e-mail, as the customer's mail app shows it.
const m=await open('file:///g/email-pedido.html',720,1000);
const mh=await m.eval('Math.ceil(document.body.scrollHeight)');
await m.shot('email-pedido',{x:0,y:0,width:720,height:mh});
}
}catch(e){console.error(e);process.exitCode=1;}
finally{chrome.kill();}