Files
dtf-system/tests/browser_test.mjs
Cauê Faleiros 4c6e2aac4a
All checks were successful
Build and deploy / Validate source (push) Successful in 8s
Build and deploy / Integration suite on a real stack (push) Successful in 8m1s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m32s
feat: a user may have more than one profile, and may do what any of them may (Marcus, 2026-11-26)
operators.roles holds every profile, the main one first; permissions, moves,
the column order and the machine question are the sum. The operator's machine
rules apply only to the moves Operador alone allows, so an Operador who is also
Revisor releases any sheet (D-29 does not block, Marcus). Usuários gets
"Outros perfis" chips next to the main profile.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-26 10:57:20 -03:00

441 lines
35 KiB
JavaScript

// Dependency-free Chrome DevTools smoke test. Node 22+ and Chrome required.
import {spawn} from 'node:child_process';
import {mkdtemp,readFile,writeFile,mkdir} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {resolve} from 'node:path';
import assert from 'node:assert/strict';
try {
for(const line of (await readFile('.env','utf8')).split('\n')) {
if(!line.startsWith('#') && line.includes('=')) {
const i=line.indexOf('=');process.env[line.slice(0,i)]??=line.slice(i+1);
}
}
}catch(e){if(e.code!=='ENOENT')throw e;}
const profile=await mkdtemp(tmpdir()+'/dtf-browser-');
const chrome=spawn(process.env.CHROME_BIN||'/usr/bin/google-chrome-stable',[
'--headless=new','--disable-gpu','--no-first-run','--no-default-browser-check',
...(process.env.CHROME_NO_SANDBOX==='1'?['--no-sandbox']:[]),
// Production uses HTTPS; internal Compose HTTP names need a secure context
// for Web Crypto during the upload and checkout journey.
...(process.env.CHROME_TRUST_TEST_ORIGINS==='1'
? ['--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));
let stderr='';chrome.stderr.on('data',data=>stderr+=data.toString());
const clients=[];
let kanban,testMachine;
async function waitFor(fn,description,timeout=30000){const end=Date.now()+timeout;while(Date.now()<end){if(await fn())return;await pause(200);}throw new Error('Timeout: '+description);}
class Page {
constructor(ws){this.ws=ws;this.next=0;this.pending=new Map();this.errors=[];
ws.onmessage=event=>{const d=JSON.parse(event.data);if(d.id){const p=this.pending.get(d.id);if(p){this.pending.delete(d.id);d.error?p.reject(d.error):p.resolve(d.result);}}else if(d.method==='Runtime.exceptionThrown')this.errors.push(d.params.exceptionDetails);};
}
call(method,params={}){return new Promise((resolve,reject)=>{const id=++this.next;this.pending.set(id,{resolve,reject});this.ws.send(JSON.stringify({id,method,params}));});}
async eval(expression){const result=await this.call('Runtime.evaluate',{expression,awaitPromise:true,returnByValue:true});if(result.exceptionDetails)throw new Error(JSON.stringify(result.exceptionDetails));return result.result.value;}
async click(selector){await this.eval(`document.querySelector(${JSON.stringify(selector)}).click()`);}
async fill(selector,value,event='input'){await this.eval(`(()=>{const el=document.querySelector(${JSON.stringify(selector)});el.value=${JSON.stringify(value)};el.dispatchEvent(new Event(${JSON.stringify(event)},{bubbles:true}));})()`);}
async text(){return this.eval('document.body.innerText');}
async screenshot(path){const result=await this.call('Page.captureScreenshot',{format:'png',captureBeyondViewport:false});await writeFile(path,Buffer.from(result.data,'base64'));}
}
try{
let port;
await waitFor(async()=>{try{port=Number((await readFile(profile+'/DevToolsActivePort','utf8')).split('\n')[0]);return true;}catch{return false;}},'Chrome startup');
async function page(url){
const tab=await (await fetch('http://localhost:'+port+'/json/new?'+encodeURIComponent(url),{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);clients.push(p);await p.call('Runtime.enable');await p.call('Page.enable');
await p.call('Emulation.setDeviceMetricsOverride',{width:1440,height:1000,deviceScaleFactor:1,mobile:false});
await waitFor(()=>p.eval('document.readyState === "complete"'),'page load');return p;
}
const siteOrigin=process.env.SITE_BROWSER_ORIGIN||'http://localhost:'+(process.env.SITE_PORT||8080);
const kanbanOrigin=process.env.KANBAN_BROWSER_ORIGIN||'http://localhost:'+(process.env.KANBAN_PORT||8081);
const site=await page(siteOrigin);
await waitFor(()=>site.eval('typeof window.dtfCheckout === "function"'),'checkout bridge');
// Prove escaping itself, independently of the CSP's second line of defense.
await site.call('Page.setBypassCSP',{enabled:true});
await site.eval(`(()=>{window.xssProbe=0;abrir('file');return sel([new File(['test'],'<img src=x onerror=window.xssProbe=1>.cdr')]);})()`);
await pause(500);
assert.equal(await site.eval('window.xssProbe'),0);
assert.equal(await site.eval('document.querySelectorAll("#lista img[onerror]").length'),0);
assert.ok((await site.text()).includes('<img src=x onerror=window.xssProbe=1>.cdr'));
await site.eval(`(()=>{recusa([new File(['test'],'bad.<img src=x onerror=window.xssProbe=1>')]);})()`);
await pause(200);assert.equal(await site.eval('window.xssProbe'),0);
await site.call('Page.setBypassCSP',{enabled:false});
await site.call('Page.reload');
await waitFor(()=>site.eval('typeof window.dtfCheckout === "function"'),'reload after security probe');
// The check above can still pass on the page being replaced; wait for the new one's cards.
await waitFor(()=>site.eval(`!!document.querySelector('[data-modo="file"]') && document.readyState==='complete'`),'product cards after reload');
await site.click('[data-modo="file"]');
const treatmentCents = await site.eval('(async()=> (await dtfSessionReady).treatment_cents)()');
if (treatmentCents > 0) {
assert.equal(await site.eval(`!$('tratamentoBox').hidden`), true);
assert.equal(await site.eval(`$('tratamentoPreco').textContent`), 'R$ '+(treatmentCents/100).toFixed(2).replace('.',','));
}
// Each product has its own page; the home's parts are not on it.
assert.deepEqual(await site.eval(`({path:location.pathname,page:document.documentElement.dataset.rota,
cards:getComputedStyle($('cards')).display,cart:getComputedStyle($('carr')).display})`),
{path:'/arquivo-por-metro',page:'produto',cards:'none',cart:'none'});
const root=await site.call('DOM.getDocument');
const input=await site.call('DOM.querySelector',{nodeId:root.root.nodeId,selector:'#inp'});
await site.call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve('tests/fixtures/local-test.cdr')]});
await waitFor(()=>site.eval('!!document.querySelector("[data-comp]")'),'manual length field');
// On its way from the product page already, with its own row under the
// uploader (Dropstar, 2026-10-29).
await waitFor(()=>site.eval(`$('envios').textContent.includes('local-test.cdr') && !$('envios').textContent.includes('Não foi possível')`),
'the file uploads from the product page',45000);
await site.fill('[data-comp]','1.01','change');
await waitFor(()=>site.eval('!!itemAtual'),'cart calculation');
// A CDR is opened by hand: the full price, plus the per-metre charge when
// the server sets one (MANUAL_FILE_EXTRA_CENTS), shown before checkout.
const extraCents=(await site.eval('dtfSessionReady')).manual_extra_cents;
const itemCents=Math.round(1.1*(1990+extraCents));
const total=Math.round(itemCents)/100;
await waitFor(()=>site.eval(`Math.abs(itemAtual.total-${total})<0.005`),'manual-file price');
assert.equal(await site.eval(`$('carrLin').textContent.includes('Arquivo aberto na mão')`),extraCents>0);
await site.fill('#fNome','Cliente Teste');
await site.fill('#fCnpj','11222333000181');
await site.fill('#fZap','11999999999');
await site.fill('#fMail','local-browser@example.test');
// Reload only once the cart is in the browser's storage: the save waits for
// typing to stop and writes the files, so a fixed pause raced it.
await waitFor(()=>site.eval(`new Promise(done=>{const open=indexedDB.open('dtf-local-cart',1);
open.onerror=()=>done(false);
open.onsuccess=()=>{const all=open.result.transaction('cart').objectStore('cart').getAll();
all.onsuccess=()=>done(all.result.some(v=>v.items?.length===1));all.onerror=()=>done(false);};})`),'cart saved in the browser');
await site.call('Page.reload');
await waitFor(()=>site.eval('typeof pedido!=="undefined" && pedido.length===1'),'persistent cart recovery');
// Reloading a product page reopens that product; the cart is its own page.
assert.equal(await site.eval('modo'),'file');
await site.click('#cartLink');
await waitFor(()=>site.eval(`location.pathname==='/carrinho' && getComputedStyle($('carr')).display!=='none' && getComputedStyle($('foco')).display==='none'`),'cart page');
// Removing an item is one click and can be undone.
await site.click('[data-rmi="0"]');
// The empty state is painted on the next animation frame (site-steps.js).
await waitFor(()=>site.eval(`!$('carrVazio').hidden||document.documentElement.hasAttribute('data-sem-itens')`),'empty cart state');
assert.deepEqual(await site.eval(`({items:pedido.length,empty:!$('carrVazio').hidden||document.documentElement.hasAttribute('data-sem-itens'),undo:!$('desfazer').hidden})`),{items:0,empty:true,undo:true});
await site.click('#desfazerBtn');
assert.equal(await site.eval(`pedido.length===1 && Math.abs(pedido[0].total-${total})<0.005 && $("desfazer").hidden`),true);
// The items come back after a reload; the customer's details do not.
assert.deepEqual(await site.eval(`['fNome','fCnpj','fZap','fMail'].map(id=>$(id).value)`),['','','','']);
assert.equal(await site.eval('document.getElementById("bPagar").disabled'),true);
// A name is required: without it, no payment.
await site.fill('#fNome','A');
await site.fill('#fCnpj','52998224725');await site.fill('#fZap','11999999999');await site.fill('#fMail','local-browser@example.test');
assert.equal(await site.eval('clienteOk()'),false);
await site.fill('#fNome',' Maria da Silva');
assert.equal(await site.eval('cliente.name'),'Maria da Silva');
// A CPF or a CNPJ, each in its own mask; this order is a person's.
await site.fill('#fCnpj','11222333000181');
assert.equal(await site.eval(`$('fCnpj').value`),'11.222.333/0001-81');
await site.fill('#fCnpj','52998224724');
assert.equal(await site.eval(`$('fCnpj').value`),'529.982.247-24');
assert.equal(await site.eval('docOk(cliente.cnpj)'),false);
await site.fill('#fCnpj','52998224725');
assert.equal(await site.eval(`$('fCnpj').value+' '+$('fCnpj').classList.contains('bom')`),'529.982.247-25 true');
await site.fill('#fZap','11999999999');
await site.fill('#fMail','local-browser@example.test');
assert.equal(await site.eval('pedido[0].localFiles[0].name'),'local-test.cdr');
// An unchecked item stays in the cart but is not paid for now.
await site.click('[data-sel="0"]');
assert.deepEqual(await site.eval(`({marcado:pedido[0].marcado,pagar:itensAPagar().length,zero:$('carrTot').textContent.includes('0,00'),row:document.querySelector('.item').classList.contains('fora')})`),
{marcado:false,pagar:0,zero:true,row:true});
await site.click('[data-sel="0"]');
assert.equal(await site.eval('pedido[0].marcado===true && itensAPagar().length===1'),true);
assert.equal(await site.eval(`Math.abs(pedido[0].total-${total})<0.005`),true);
assert.equal(await site.eval('document.getElementById("bPagar").disabled'),false);
await site.click('#bPagar');
try{
// A cart the Site can price is approved at once: the customer pays now.
await waitFor(async()=> (await site.text()).includes('Total validado no servidor:'),'browser upload and automatic approval',45000);
// Payment is its own page: the cart form is gone and the order summary is shown.
assert.equal(await site.eval('location.pathname'),'/pagamento');
assert.equal(await site.eval('getComputedStyle(document.getElementById("carr")).display'),'none');
assert.equal(await site.eval('!document.getElementById("pagResumo").hidden && document.getElementById("pagResumo").textContent.includes("Total")'),true);
}catch(error){
console.error('Checkout status:',await site.eval('document.getElementById("checkoutStatus")?.textContent'));
throw error;
}
const qid=await site.eval('localStorage.getItem("dtf-quote")');
// The server charged what the Site showed.
assert.equal(await site.eval(`dtfApi('/quotes/'+${JSON.stringify(qid)}).then(q=>q.approved.items[0].total_cents)`),itemCents);
kanban=await page(kanbanOrigin);
await kanban.fill('#email',process.env.OPERATOR_EMAIL||'operator@example.test');
await kanban.fill('#password',process.env.OPERATOR_PASSWORD||'local-operator-only');
await kanban.eval('document.getElementById("login").requestSubmit()');
// Quotes live in their own tab; an automatic approval is listed as such.
await waitFor(()=>kanban.eval('!document.getElementById("app").hidden'),'Kanban sign-in');
// The test makes its own machine, so it runs on a fresh database and on its own.
testMachine=await kanban.eval(`api('/machines',{name:'Browser test '+Date.now(),products:['textil']}).then(r=>r.id)`);
await kanban.eval('load(true)');
await waitFor(()=>kanban.eval(`board.machines.some(m=>m.id===${JSON.stringify(testMachine)})`),'test machine on the board');
assert.equal(await kanban.eval('sessionStorage.getItem("dtf-operator")'),null);
assert.equal(await kanban.eval('document.getElementById("password").value'),'');
await kanban.click('[data-tab="site"]');
await waitFor(()=>kanban.eval('!!document.querySelector("[data-site-tab=\\"videos\\"]")'),'Site tabs in Gestão');
await kanban.click('[data-site-tab="videos"]');
await waitFor(()=>kanban.eval('document.querySelectorAll("#site-videos-list .siteVideoRow").length===6'),
'six video slots in Gestão');
assert.equal(await kanban.eval('document.querySelectorAll("#site-videos-list input[type=file]").length'),0);
await kanban.click('#site-videos-list .siteVideoRow .btn');
await waitFor(()=>kanban.eval('document.querySelectorAll(".modal input[type=file]").length===2'),'video edit dialog');
await kanban.eval('document.querySelector(".modal .dlghead .btn.sq")?.click()');
await waitFor(()=>kanban.eval('!document.querySelector(".modal")'),'video dialog closed');
await mkdir('output/local',{recursive:true});
await kanban.eval('document.getElementById("site-videos-panel").scrollIntoView()');
await kanban.screenshot('output/local/kanban-videos.png');
await kanban.click('[data-tab="quotes"]');
await waitFor(()=>kanban.eval('document.querySelectorAll("#quote-filters button").length===2'),'quote filters');
await kanban.eval('document.querySelectorAll("#quote-filters button")[1].click()');
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-quote-pick="${qid}"]')`),'approved quote listed on Kanban');
// Approved by the Site itself; the row shows the grade instead of saying so.
assert.equal(await kanban.eval(`quoteRows.find(q=>q.id==='${qid}').auto_approved && !!document.querySelector('[data-quote-pick="${qid}"] .grade')`),true);
assert.equal(await site.eval('pedido[0].production.sources[0].copies'),1);
await site.eval('pedido[0].production.sources[0].copies=2;pintaPedido()');
await waitFor(async()=> (await site.text()).includes('O carrinho mudou'),'same-price production edit invalidates quote');
await site.eval('pedido[0].production.sources[0].copies=1;pintaPedido()');
await site.fill('#fMail','changed-browser@example.test');
await waitFor(async()=> (await site.text()).includes('O carrinho mudou'),'quote invalidated by cart edit');
assert.equal(await site.eval('[...document.querySelectorAll("button")].some(x=>x.textContent==="Criar pedido de teste")'),false);
await site.fill('#fMail','local-browser@example.test');
await site.eval('window.dtfCheckout()');
await waitFor(async()=> (await site.text()).includes('Total validado no servidor:'),'approved quote displayed');
await site.eval('[...document.querySelectorAll("button")].find(x=>x.textContent==="Criar pedido de teste").click()');
// The customer is shown a confirmation, never the order's sequential number.
await waitFor(async()=> (await site.text()).includes('Pagamento confirmado'),'test payment');
assert.equal((await site.text()).includes('Pedido #'),false);
await kanban.click('#refresh');
await waitFor(()=>kanban.eval(`board.orders.some(o=>o.quote_id===${JSON.stringify(qid)})`),'paid card');
const oid=await kanban.eval(`board.orders.find(o=>o.quote_id===${JSON.stringify(qid)}).id`);
// The customer's name is on the order, and the Kanban card is titled with it.
assert.equal(await kanban.eval(`board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.customer.name`),'Maria da Silva');
assert.deepEqual(await kanban.eval(`(()=>{const spec=board.orders.find(o=>o.id===${JSON.stringify(oid)}).snapshot.items[0].production;const source=spec.sources[0];return {kind:source.kind,copies:source.copies,length:Number(source.length_cm),height:Number(spec.height_cm),placed:spec.placements.length}})()`),
{kind:'sheet',copies:1,length:101,height:101,placed:1});
// The orders' three folders, switched on in Integrações. The native picker
// cannot be driven headless: it answers with a folder in the browser's own
// storage, which has the same file API.
await kanban.click('[data-tab="integrations"]');
await waitFor(()=>kanban.eval('!!document.getElementById("folder-card")'),'folder card');
await kanban.eval(`(async()=>{const root=await navigator.storage.getDirectory();
window.picked=await root.getDirectoryHandle('fila-'+Date.now(),{create:true});
window.showDirectoryPicker=async()=>window.picked;FOLDER.mode='folder';renderIntegrations();
[...document.querySelectorAll('#folder-card button')].find(b=>b.textContent==='Escolher pasta').click();})()`);
await waitFor(()=>kanban.eval('folderActive()&&!FOLDER.busy'),'folder chosen');
// Dropstar's three folders (2026-10-26): the file arrives in Arte recebida,
// goes to Arte conferida with the card and to Finalizado at the end.
await waitFor(()=>kanban.eval(`!FOLDER.busy`),'folder idle');
const savedFiles=(sub)=>kanban.eval(`(async()=>{const dir=await window.picked.getDirectoryHandle(${JSON.stringify(sub)},{create:true});
const out=[];for await(const [name,h] of dir.entries())if(h.kind==='file')out.push(name);return out;})()`);
// Open the order's panel from its card, then click the real transition
// buttons there, including the rerender after each move.
await kanban.click('[data-tab="board"]');
assert.equal(await kanban.eval(`!!document.querySelector('[data-card="${oid}"] .card-open')`),true);
await kanban.click(`[data-card="${oid}"]`);
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move]')`),'order panel');
// The Prumo report is on the card before the designer opens the file.
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] .prumo')`),'Prumo report');
// No machine at payment (Dropstar, 2026-11-05): pulling without a session
// machine asks which machine takes the card (DTF-WEB-4). It is the machine
// this test made after sign-in.
const machineId=testMachine;
// Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão before Finalizado.
for(const [title,state] of [['Arte conferida','tra'],['Imprimindo','imp'],['Revisão','rev'],['Finalizado','fin']]){
if(state==='tra'){
// Without an approved final, the next step at the top is approving it,
// not a move the server would refuse. The CDR has no ready file, so
// the button opens the upload form there.
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-approve]')`),'approve final button');
assert.equal(await kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="tra"]')`),false);
await kanban.click(`[data-order="${oid}"] [data-approve]`);
await waitFor(()=>kanban.eval(`(()=>{const input=document.querySelector('[data-order="${oid}"] [data-final-item]');return !!input&&!input.closest('form').hidden;})()`),'final upload controls');
const doc=await kanban.call('DOM.getDocument');
const input=await kanban.call('DOM.querySelector',{nodeId:doc.root.nodeId,selector:`[data-order="${oid}"] [data-final-item]`});
await kanban.call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve('tests/fixtures/final-300.png')]});
await kanban.fill(`[data-order="${oid}"] input[placeholder="Nota da revisão"]`,'Browser test final file');
await kanban.eval(`(()=>{const check=document.querySelector('[data-order="${oid}"] [data-confirm]');check.click();check.closest('form').requestSubmit();})()`);
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').version===1`),'final file approval');
// Approved before the queue: already on this computer, in Arte recebida.
const early='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
await kanban.eval('syncFolder(true)');
await waitFor(async()=>(await savedFiles('1. Arte recebida')).some(n=>n.startsWith(early)&&!n.endsWith('.baixando')),'final file saved in Arte recebida',45000);
assert.equal((await savedFiles('2. Arte conferida')).some(n=>n.startsWith(early)),false);
}
if(state==='fin'){
// Above 1 m Finalizado needs the review photo (app/reviews.py). Take one
// with a canvas in the page and send it as the Revisor's dialog does.
const metres=await kanban.eval(`board.orders.find(o=>o.id==='${oid}').snapshot.items.reduce((t,i)=>t+Number(i.billed_metres),0)`);
if(metres>1){
await kanban.eval(`(async()=>{
const order=board.orders.find(o=>o.id==='${oid}');
const canvas=document.createElement('canvas');canvas.width=2000;canvas.height=1500;
const ctx=canvas.getContext('2d');ctx.fillStyle='#c04030';ctx.fillRect(0,0,2000,1500);
const blob=await new Promise(ok=>canvas.toBlob(ok,'image/jpeg',0.9));
const file=new File([blob],'revisao.jpg',{type:'image/jpeg'});
const uid=await dtfUpload(file,{api,startPath:'/orders/'+order.id+'/reviews/uploads',scope:'operator:review:'+order.id+':browser',progress:()=>{}});
await api('/orders/'+order.id+'/reviews',{upload_id:uid});
await load();
})()`);
await waitFor(()=>kanban.eval(`(board.orders.find(o=>o.id==='${oid}').reviews||[]).some(r=>r.kind==='photo')`),'review photo attached');
}
}
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="${state}"]')`),'move to '+title);
await kanban.click(`[data-order="${oid}"] [data-move="${state}"]`);
if(state==='imp'){
// The order has no machine and the session has none: pick it here.
await waitFor(()=>kanban.eval(`!!document.querySelector('.mchoice[data-machine="${machineId}"]')`),'machine chooser');
await kanban.click(`.mchoice[data-machine="${machineId}"]`);
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').machine?.id===${JSON.stringify(machineId)}`),'card machine chosen');
}
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='${state}'`),'transition '+state);
if(state==='tra'){
// The file opens from the card itself, without first expanding the order.
await kanban.eval('closePanel()');
await kanban.click(`[data-card="${oid}"] .card-open`);
await waitFor(()=>kanban.eval(`!!document.querySelector('.viewer[open]')`),'file viewer from the card');
assert.equal(await kanban.eval(`$('drawer').hidden`),true);
await kanban.click('.viewer .vbtn.pri');
await kanban.click(`[data-card="${oid}"]`);
// Entering the queue moves its file to Arte conferida, whole and named after the order.
const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
await waitFor(async()=>(await savedFiles('2. Arte conferida')).some(n=>n.startsWith(prefix)&&!n.endsWith('.baixando')),'final file in Arte conferida',45000);
// Other orders the earlier suites left in the queue may still be coming
// down: only once the round ends must no half-written file be left.
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder round finished',60000);
assert.equal((await savedFiles('2. Arte conferida')).some(n=>/\.(baixando|crswap)$/.test(n)),false);
// Written in the work folder and moved in whole: nothing stays there (order #30).
assert.deepEqual(await savedFiles('_tmp'),[]);
assert.equal((await savedFiles('1. Arte recebida')).some(n=>n.startsWith(prefix)),false);
// A file whose order was deleted leaves the folder.
await kanban.eval(`(async()=>{const dir=await window.picked.getDirectoryHandle('2. Arte conferida',{create:true});
const f=await dir.getFileHandle('pedido-0-item-1-excluido.png',{create:true});
const w=await f.createWritable();await w.write('x');await w.close();
FOLDER.saved.set(crypto.randomUUID(),{order:crypto.randomUUID(),item:1,name:'pedido-0-item-1-excluido.png',folder:'2. Arte conferida'});})()`);
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder idle',60000);
await kanban.eval('syncFolder(true)');
await waitFor(async()=>!(await savedFiles('2. Arte conferida')).includes('pedido-0-item-1-excluido.png'),'deleted order file removed',30000);
}
if(state==='rev'||state==='fin'){
// In Revisão the file leaves the queue for 4. Revisão; finalized, it
// goes on to 5. Finalizado (Dropstar's numbering, 2026-10-30).
const prefix='DTF-'+await kanban.eval(`board.orders.find(o=>o.id==='${oid}').number`)+'-item-1';
const [now,before]=state==='rev'?['4. Revisão','2. Arte conferida']:['5. Finalizado','4. Revisão'];
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder idle',60000);
await kanban.eval('syncFolder(true)');
await waitFor(async()=>(await savedFiles(now)).some(n=>n.startsWith(prefix)),'final file in '+now,30000);
assert.equal((await savedFiles(before)).some(n=>n.startsWith(prefix)),false);
}
if(state==='fin'){
// The folder of before the numbering goes once nothing is left in it.
const folders=()=>kanban.eval(`(async()=>{const out=[];for await(const [name,h] of window.picked.entries())if(h.kind==='directory')out.push(name);return out.sort();})()`);
await kanban.eval(`window.picked.getDirectoryHandle('3. Finalizado',{create:true})`);
await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder idle',60000);
await kanban.eval('syncFolder(true)');
await waitFor(async()=>!(await folders()).includes('3. Finalizado'),'old Finalizado folder removed',30000);
const tree=await folders();
for(const name of ['1. Arte recebida','2. Arte conferida','3. Imprimindo','4. Revisão','5. Finalizado','Recibos','Revisões'])
assert.ok(tree.includes(name),name+' missing from '+tree.join(', '));
}
}
// Undo a mistaken move from the panel: one stage back with an internal reason.
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-back="rev"]')`),'back button');
await kanban.click(`[data-order="${oid}"] [data-back="rev"]`);
await kanban.fill(`[data-order="${oid}"] form.reason input`,'Movido por engano (teste)');
await kanban.eval(`document.querySelector('[data-order="${oid}"] form.reason input').closest('form').requestSubmit()`);
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='rev'`),'undo to Revisão');
await waitFor(()=>kanban.eval(`!!document.querySelector('[data-order="${oid}"] [data-move="fin"]')`),'move to Finalizado again');
await kanban.click(`[data-order="${oid}"] [data-move="fin"]`);
await waitFor(()=>kanban.eval(`board.orders.find(o=>o.id==='${oid}').state==='fin'`),'finished again');
// Reload proves the board is persisted on the backend.
await kanban.call('Page.reload');
await waitFor(()=>kanban.eval(`typeof board!=='undefined' && !!board && board.orders.some(o=>o.id==='${oid}'&&o.state==='fin')`),'persisted board');
await mkdir('output/local',{recursive:true});
await site.eval('window.scrollTo({top:0,behavior:"instant"})');
await waitFor(()=>site.eval('window.scrollY===0'),'screenshot scroll position');
await site.screenshot('output/local/site.png');
await kanban.screenshot('output/local/kanban.png');
// Números lives in its own file now: the tab must still load after kanban.js.
await kanban.click('[data-tab="stats"]');
await waitFor(()=>kanban.eval(`document.querySelector('#stats-kpis').children.length>0
&& document.querySelector('#stats-machine-body').children.length>0`),'Números tab and machines by month');
// The stage-times dialog (D1) opens from Números and keeps its five rows.
await kanban.click('#edit-stage-limits');
await waitFor(()=>kanban.eval('!!document.querySelector(".modal.limitsDialog")'),'stage-times dialog');
assert.equal(await kanban.eval('document.querySelectorAll(".modal.limitsDialog tbody tr").length'),5);
await kanban.eval('document.querySelector(".modal .dlghead .btn.sq").click()');
await waitFor(()=>kanban.eval('!document.querySelector(".modal")'),'stage-times dialog closed');
// Cotações lives in its own file now: the list and the review panel load too.
await kanban.click('[data-tab="quotes"]');
await waitFor(()=>kanban.eval(`document.querySelector('#quote-filters').children.length>0
&& document.querySelector('#quote-list').children.length>0
&& document.querySelector('#reviews').children.length>0`),'Cotações tab and review panel');
// Usuários, machines and each machine's sheet live in their own file too.
await kanban.click('[data-tab="users"]');
await waitFor(()=>kanban.eval(`document.querySelector('#users-list').children.length>0
&& document.querySelector('#roles-matrix').children.length>0
&& document.querySelector('#machines-list').children.length>0`),'Usuários tab, people, roles and machines');
// More than one profile (Marcus, 2026-11-26): the form offers the others as chips.
await kanban.eval('userForm()');
await waitFor(()=>kanban.eval(`[...document.querySelectorAll('.fld > span')].some(s=>s.textContent==='Outros perfis')
&& document.querySelectorAll('.fopts .fopt').length>=8`),'user form with other profiles');
await kanban.eval(`document.querySelector('.fopts .fopt').click()`);
assert.equal(await kanban.eval(`document.querySelector('.fopts .fopt').getAttribute('aria-pressed')`),'true');
await kanban.eval(`[...document.querySelectorAll('.modal .dfoot button')].find(b=>b.textContent==='Cancelar').click()`);
await waitFor(()=>kanban.eval(`!document.querySelector('.modal')`),'user form closed');
// Pagamentos and Integrações live in their own file now: both lists still render.
await kanban.click('[data-tab="payments"]');
await waitFor(()=>kanban.eval(`document.querySelector('#payments').children.length>0`),'Pagamentos tab');
await kanban.click('[data-tab="integrations"]');
await waitFor(()=>kanban.eval(`document.querySelector('#integrations').children.length>0`),'Integrações tab');
// The phone board lives in its own file now: open its Mais and filters.
await kanban.call('Emulation.setDeviceMetricsOverride',{width:390,height:844,deviceScaleFactor:1,mobile:true});
await waitFor(()=>kanban.eval('PHONE.matches'),'phone board');
await kanban.click('#more-nav');
await waitFor(()=>kanban.eval('!!document.querySelector(".msheet")'),'phone menu');
await kanban.eval('document.querySelector(".mscrim").click()');
await waitFor(()=>kanban.eval('!document.querySelector(".msheet")'),'phone menu closed');
await kanban.click('#filter-open');
await waitFor(()=>kanban.eval('!!document.querySelector(".msheet")'),'phone filters');
await kanban.eval('document.querySelector(".mscrim").click()');
await waitFor(()=>kanban.eval('!document.querySelector(".msheet")'),'phone filters closed');
await kanban.call('Emulation.setDeviceMetricsOverride',{width:1440,height:1000,deviceScaleFactor:1,mobile:false});
await waitFor(()=>kanban.eval('!PHONE.matches'),'desktop board again');
// A guest sees the order paid in this browser; creating an account keeps it.
const portal=await page(siteOrigin+'/conta/pedidos?order='+oid);
await waitFor(async()=> (await portal.text()).includes('Finalizado'),'customer order tracking');
await waitFor(()=>portal.eval('document.querySelector("#order-'+oid+' .detalhe")?.hidden===false'),'order from the link opened');
await portal.click('#navEntrar');
await waitFor(()=>portal.eval('location.pathname==="/conta/entrar" && !document.getElementById("auth").hidden'),'sign-in page');
await portal.fill('#register-name','Cliente Portal');await portal.fill('#cnpj','11222333000181');await portal.fill('#phone','11999999999');
await portal.fill('#register-email','browser-'+Date.now()+'@example.test');
await portal.fill('#register-password','local-browser-password-123');
await portal.eval('document.getElementById("register").requestSubmit()');
// The account waits for the code e-mailed to the address; the local stack
// keeps it readable for this test.
await waitFor(()=>portal.eval('!document.getElementById("fCodigo").hidden'),'signup code step');
await portal.eval(`fetch('/api/account/register/dev-code?signup='+signup).then(r=>r.json()).then(({code})=>{
const field=document.getElementById('codigo');field.value=code;field.dispatchEvent(new Event('input'));})`);
await waitFor(()=>portal.eval('document.getElementById("auth").hidden && location.pathname==="/conta"'),'customer registration');
await waitFor(async()=> (await portal.text()).includes('Finalizado'),'overview shows the last order');
await portal.click('[data-view="dados"]');
await waitFor(()=>portal.eval('location.pathname==="/conta/dados" && document.getElementById("dCnpj").value==="11.222.333/0001-81"'),'account details');
await portal.screenshot('output/local/portal.png');
// A logout must clear draft file blobs and metadata, including other open Site tabs.
await portal.eval(`(async()=>{const db=await new Promise((resolve,reject)=>{const r=indexedDB.open('dtf-local-cart',1);r.onsuccess=()=>resolve(r.result);r.onerror=reject;});await new Promise((resolve,reject)=>{const tx=db.transaction('cart','readwrite');tx.objectStore('cart').put({items:[new File(['private'],'private.cdr')],expires:Date.now()+86400000},'security-fixture');tx.oncomplete=resolve;tx.onerror=reject;});db.close();})()`);
await portal.click('#logout');
await waitFor(()=>portal.eval('document.getElementById("logout")?.hidden===true'),'customer logout');
let stored;
await waitFor(async()=>{stored=await portal.eval(`(async()=>{try{const db=await new Promise((resolve,reject)=>{const r=indexedDB.open('dtf-local-cart',1);r.onupgradeneeded=()=>r.result.createObjectStore('cart');r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);});const n=await new Promise((resolve,reject)=>{const r=db.transaction('cart').objectStore('cart').count();r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);});db.close();return n;}catch{return -1;}})()`);return stored>=0;},'IndexedDB available after Clear-Site-Data');
assert.equal(stored,0);
assert.deepEqual(portal.errors,[]);
assert.deepEqual(site.errors,[]);assert.deepEqual(kanban.errors,[]);
console.log('PASS: browser Site upload → automatic approval → local paid order → all main Kanban states → reload persistence. Order '+oid);
console.log('Screenshots: output/local/site.png and output/local/kanban.png');
console.log('PASS: filename XSS escaping with CSP bypassed, no stored operator password, logout clears browser file blobs.');
}catch(error){console.error(error);if(stderr)console.error(stderr.slice(-1500));process.exitCode=1;}
finally{
if(testMachine&&kanban){
try{await kanban.eval(`api('/machines/'+${JSON.stringify(testMachine)}+'/delete',{})`);}
catch(e){console.error('Could not delete the test machine '+testMachine+':',e.message||e);}
}
for(const p of clients)p.ws.close();chrome.kill();
}