diff --git a/app/api/stamps.py b/app/api/stamps.py index b5914f6..a43b962 100644 --- a/app/api/stamps.py +++ b/app/api/stamps.py @@ -120,6 +120,8 @@ def montador_order(body: MontadorOrder, request: Request, user=Depends(can('asse kinds = set().union(*(MONTADOR_KINDS.get(r, set()) for r in roles_of(request.state.operator))) if body.kind not in kinds: raise HTTPException(403, 'Seu perfil não permite este tipo de pedido.') + if body.batch and body.kind != 'interno': + raise HTTPException(422, 'A lista colada vira sempre pedido Interno.') with db.connect() as c: if body.kind == 'interno': customer = internal_customer(c) @@ -148,7 +150,8 @@ def montador_order(body: MontadorOrder, request: Request, user=Depends(can('asse # The order's kind and the clothing order it travels with, on the # card and in Tiny's internal note. approved = {**approved, 'kind': body.kind, - **({'with_order': body.with_order} if body.with_order else {})} + **({'with_order': body.with_order} if body.with_order else {}), + **({'batch': body.batch.model_dump()} if body.batch else {})} # A Venda's seller in Tiny is who assembled it, when their user # names one (Marcus, 2026-11-17, app/tiny.py order_payload). if body.kind == 'venda': diff --git a/app/core/models.py b/app/core/models.py index 9c159f6..5d0c91b 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -405,6 +405,15 @@ class QuoteRequest(StrictModel): raise ValueError('The delivery address CEP must be the CEP freight was quoted for') return self +class SkippedLine(StrictModel): + line: int = Field(ge=1, le=10000, strict=True) + text: str = Field(max_length=200) + reason: str = Field(max_length=200) + +class MontadorBatch(StrictModel): + lines: int = Field(ge=0, le=1000, strict=True) + skipped: list[SkippedLine] = Field(default_factory=list, max_length=1000) + class MontadorOrder(StrictModel): """What the montador sends (fronts 7a.3 and 7a.4): Interno or Venda, loose artwork only; the server prices and approves it as a quote. An Interno @@ -421,6 +430,8 @@ class MontadorOrder(StrictModel): # A Venda with "Envio": the chosen freight service and the full address. freight: Freight | None = None destination: Destination | None = None + # The pasted list this order came from: the valid lines and the skipped ones. + batch: MontadorBatch | None = None @model_validator(mode='after') def order_kind(self): diff --git a/app/prumo.py b/app/prumo.py index 658abe7..87a97d1 100644 --- a/app/prumo.py +++ b/app/prumo.py @@ -59,6 +59,15 @@ def report(order, uploads): lines = [] if snapshot.get('proof_of'): lines.append(f'Prova do pedido #{snapshot["proof_of"]}') + batch = snapshot.get('batch') or {} + if batch: + skipped = batch.get('skipped') or [] + summary = f'Lista colada: {batch.get("lines", 0)} linhas montadas' + if skipped: + summary += f', {len(skipped)} puladas' + lines.append(summary) + for row in skipped: + lines.append(f'Linha {row.get("line")} pulada ({row.get("reason")}): {row.get("text")}') multi = len(items) > 1 for index, item in enumerate(items): lead = f'Item {index + 1}: ' if multi else '' diff --git a/tests/stamps_test.py b/tests/stamps_test.py index dc6c85d..9d25026 100644 --- a/tests/stamps_test.py +++ b/tests/stamps_test.py @@ -146,7 +146,9 @@ def run(): # Interno is refused while Gestão has not completed the customer. stamp = upload_stamp(shipping) - interno = {'kind': 'interno', 'items': [montador_item(stamp)]} + batch = {'lines': 2, 'skipped': [ + {'line': 5, 'text': 'NX.999 Z 1 REF', 'reason': 'tamanho não existe na tabela'}]} + interno = {'kind': 'interno', 'items': [montador_item(stamp)], 'batch': batch} refused = shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno}, expected=409) assert refused['detail'] == INTERNAL_MISSING, refused @@ -164,6 +166,7 @@ def run(): assert order_interno['state'] == 'rec' and order_interno['origin'] == 'dropflow', order_interno assert order_interno['snapshot']['kind'] == 'interno', order_interno['snapshot'].get('kind') assert order_interno['snapshot']['customer']['cnpj'] == '11222333000181', order_interno['snapshot'] + assert order_interno['snapshot']['batch'] == batch, order_interno['snapshot'].get('batch') payment = order_interno['payment'] assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'interno', 'paid'), payment with db.connect() as c: @@ -213,6 +216,12 @@ def run(): designer.call('/operator/montador/orders', {'request_key': str(uuid4()), **venda}, expected=403) shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'interno', 'items': [montador_item(stamp, 'file')]}, expected=422) + # A pasted list only becomes an Interno order. + refused = seller.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'venda', + 'customer': venda_customer, + 'items': [montador_item(venda_stamp)], + 'batch': batch}, expected=422) + assert refused['detail'] == 'A lista colada vira sempre pedido Interno.', refused # Venda with Envio: the Site's freight, re-quoted by the server. destination = {'recipient': 'Maria Souza', 'street': 'Rua das Flores', 'number': '100', diff --git a/tests/test_prumo.py b/tests/test_prumo.py index a45f4fc..5293749 100644 --- a/tests/test_prumo.py +++ b/tests/test_prumo.py @@ -37,6 +37,29 @@ class PrumoReportTests(unittest.TestCase): self.assertIn('Prumo levou 41 s', text) self.assertNotIn('Prumo levou 341 s', text) + def test_pasted_list_says_how_many_lines_were_mounted(self): + order = self.order() + order['snapshot']['batch'] = {'lines': 3, 'skipped': []} + lines = report(order, {'u1': {'name': 'arte.pdf'}}) + text = '\n'.join(lines) + self.assertIn('Lista colada: 3 linhas montadas', text) + self.assertNotIn('puladas', text) + # Before the item lines: the designer reads the list first. + self.assertLess(text.index('Lista colada'), text.index('Formato detectado')) + + def test_pasted_list_lists_the_skipped_lines(self): + order = self.order() + order['snapshot']['batch'] = {'lines': 2, 'skipped': [ + {'line': 4, 'text': 'NX.999 Z 1 REF', 'reason': 'tamanho não existe na tabela'}, + {'line': 7, 'text': 'NX.226 C 0', 'reason': 'quantidade de 1 a 9999'}]} + lines = report(order, {'u1': {'name': 'arte.pdf'}}) + text = '\n'.join(lines) + self.assertIn('Lista colada: 2 linhas montadas, 2 puladas', text) + self.assertIn('Linha 4 pulada (tamanho não existe na tabela): NX.999 Z 1 REF', text) + self.assertIn('Linha 7 pulada (quantidade de 1 a 9999): NX.226 C 0', text) + self.assertLess(text.index('Lista colada'), text.index('Linha 4 pulada')) + self.assertLess(text.index('Linha 7 pulada'), text.index('Formato detectado')) + def test_saved_png_size_says_whether_the_customer_kept_it(self): order = self.order() item = order['snapshot']['items'][0] diff --git a/web/kanban-montador.js b/web/kanban-montador.js index 51c9c6e..04accbb 100644 --- a/web/kanban-montador.js +++ b/web/kanban-montador.js @@ -14,7 +14,7 @@ const MONTAR_GEAR='M128 80a48 48 0 1 0 48 48a48.05 48.05 0 0 0-48-48m0 80a32 32 const MONTAR={sizes:[],lines:[],seq:0,preview:null,timer:null,dirty:false,token:0, layout:null,layoutTimer:null,layoutToken:0,layoutPending:false,creating:false,requestKey:null, kind:null,internal:null,internalDirty:false,brands:new Map(),contactToken:0,contactTimer:null, - freights:null,freight:null,catalog:null}; + freights:null,freight:null,catalog:null,batch:null}; const montarFolderReady=()=>!!FOLDER.handle&&!!FOLDER.granted; const montarDpi=found=>found.width/(found.widthCm/2.54); @@ -433,7 +433,7 @@ async function montarLayout(token){ say('A estampa não pôde ser lida.',true);return; } const cargas=lines.flatMap((line,sourceIndex)=>Array.from({length:line.qty},(_,copyIndex)=>({ - a:{sourceIndex,giro:0,esp:false},img:line.img,copyIndex,w:line.widthCm,h:line.heightCm,travado:false}))); + a:{sourceIndex,giro:0,esp:false},img:line.ref?null:line.img,copyIndex,w:line.widthCm,h:line.heightCm,travado:false}))); let enc; try{enc=encaixar(cargas,MONTAR_FILM_CM);} catch(e){ @@ -523,7 +523,7 @@ function montarItem(sources){ const cargas=[]; sources.forEach((source,sourceIndex)=>{ for(let copyIndex=0;copyIndexsize.letter===wanted)||null; +} +function montarParseList(text){ + const rows=[]; + const lines=String(text||'').split(/\r?\n/); + for(let index=0;index4){row.error='mais de 4 campos';rows.push(row);continue;} + if(parts.length<3){row.error='faltam campos';rows.push(row);continue;} + row.code=parts[0];row.letter=parts[1];row.ref=parts[3]||''; + if(!MONTAR_CODE.test(row.code)){row.error='código inválido';rows.push(row);continue;} + const size=montarListSize(row.letter); + if(!size){row.error='tamanho não existe na tabela';rows.push(row);continue;} + row.letter=size.letter; + const quantity=Number(parts[2]); + if(!Number.isInteger(quantity)||quantity<1||quantity>9999){ + row.error='quantidade de 1 a 9999';rows.push(row);continue; + } + row.qty=quantity; + if(row.ref.length>30){row.error='referência com mais de 30 caracteres';rows.push(row);continue;} + rows.push(row); + } + return rows; +} +async function montarListCheck(rows){ + const cache=new Map(); + for(const row of rows){ + if(row.error)continue; + const size=montarListSize(row.letter); + if(!size){row.error='tamanho não existe na tabela';continue;} + const key=row.code+'\u0000'+size.letter; + let found; + if(cache.has(key))found=cache.get(key); + else{ + try{found=await montarRead(row.code,size);} + catch(e){if(!montarFolderError(e))say(e.message,true);return null;} + cache.set(key,found); + } + if(!found){row.error='código não existe em Estampas/';continue;} + if(found.widthCm>56){row.error='estampa com mais de 56 cm';continue;} + if(montarDpi(found){ + const source=montarStampImage(found.url); + source.loading.then(image=>{ + if(!image)return fail(new Error('A estampa não pôde ser lida.')); + const pxCm=found.width/found.widthCm; + const gap=Math.round(0.1*pxCm),cap=Math.round(0.3*pxCm),bottom=Math.round(0.5*pxCm); + const font=0.3*pxCm/0.72; + const canvas=document.createElement('canvas'),ctx=canvas.getContext('2d'); + ctx.font='bold '+font+'px Arial, sans-serif'; + const textWidth=Math.ceil(ctx.measureText(row.ref).width); + canvas.width=Math.max(1,Math.max(found.width,textWidth)); + canvas.height=Math.max(1,found.height+gap+cap+bottom); + ctx.font='bold '+font+'px Arial, sans-serif'; + ctx.textBaseline='alphabetic';ctx.fillStyle='#000'; + ctx.drawImage(image,0,0,found.width,found.height); + ctx.fillText(row.ref,0,found.height+gap+cap); + canvas.toBlob(blob=>{ + if(!blob)return fail(new Error('A referência não pôde ser gerada.')); + const file=new File([blob],montarListFile(row),{type:'image/png'}); + const url=URL.createObjectURL(file),picture=montarStampImage(url); + ok({file,url,img:picture.img,loading:picture.loading, + widthCm:canvas.width/pxCm,heightCm:canvas.height/pxCm}); + },'image/png'); + },fail); + }); +} +async function montarListBuild(valid,skipped){ + montarSetKind('interno'); + const used=new Set(); + try{ + for(const row of valid){ + const found=row.found; + used.add(found); + const existing=MONTAR.lines.find(line=>line.code===row.code&&line.letter===row.letter&& + (line.ref||'')===row.ref); + if(existing){existing.qty=Math.min(9999,existing.qty+row.qty);continue;} + if(row.ref){ + const composed=await montarComposeRef(found,row); + MONTAR.lines.push({id:++MONTAR.seq,code:row.code,letter:row.letter,widthCm:composed.widthCm, + qty:row.qty,heightCm:composed.heightCm,dpi:montarDpi(found),url:composed.url, + img:composed.img,loading:composed.loading,file:composed.file,ref:row.ref}); + }else{ + const url=URL.createObjectURL(found.file),picture=montarStampImage(url); + MONTAR.lines.push({id:++MONTAR.seq,code:row.code,letter:row.letter,widthCm:found.widthCm, + qty:row.qty,heightCm:montarHeight(found),dpi:montarDpi(found),url, + img:picture.img,loading:picture.loading,file:found.file,ref:''}); + } + } + }finally{ + for(const found of used)URL.revokeObjectURL(found.url); + } + MONTAR.batch={lines:valid.length,skipped}; + montarChanged(); +} +function montarListErrors(valid,skipped){ + const box=node('div',undefined,'montar-list-errors'); + box.append(...skipped.map(row=>node('p','Linha '+row.line+': '+row.text+' · '+row.reason))); + const all=!valid.length; + const label=all?'Fechar':(skipped.length===1?'Montar sem essa linha':'Montar sem essas '+skipped.length+' linhas'); + const dialog=formDialog('Linhas com erro',{ + text:all?'Nenhuma linha será montada.':'As linhas abaixo serão puladas.', + fields:[box],label, + onsave:async()=>{ + if(all)return; + await montarListBuild(valid,skipped); + } + }); + if(all){ + const cancel=dialog.box.querySelector('.dfoot .btn.ghost.right'); + if(cancel)cancel.remove(); + } +} +function montarOpenPaste(){ + if(!montarKindNames().includes('interno')) + return say('Seu perfil não monta lista colada: ela vira pedido Interno.',true); + if(!montarFolderReady())return; + const text=node('textarea',undefined,'montar-list-text'); + text.id='montar-list-text';text.rows=12;text.spellcheck=false;text.placeholder='NX.226 C 2 ML-4471'; + formDialog('Colar lista',{ + text:'Uma linha por item: código tamanho quantidade referência. Ex.: NX.226 C 2 ML-4471', + fields:[field('Lista',text)],label:'Conferir lista',width:640, + onsave:async()=>{ + const rows=montarParseList(text.value); + if(rows.length>500){say('A lista tem mais de 500 linhas.',true);return false;} + if(!rows.length){say('A lista está vazia.',true);return false;} + const checked=await montarListCheck(rows); + if(!checked)return false; + const valid=checked.filter(row=>!row.error); + const skipped=checked.filter(row=>row.error) + .map(row=>({line:row.line,text:row.text,reason:row.error})); + if(skipped.length){montarListErrors(valid,skipped);return;} + await montarListBuild(valid,skipped); + } + }); +} + function montarPaintSelect(){ const select=$('montar-size'),current=select.value; select.replaceChildren(...MONTAR.sizes.map(size=>{ @@ -855,6 +1009,7 @@ $('montar-add').onclick=async()=>{ $('montar-add').disabled=true; try{await montarAdd();}catch(e){say(e.message,true);}finally{$('montar-add').disabled=false;} }; +$('montar-paste').onclick=()=>montarOpenPaste(); $('montar-clear').onclick=()=>montarClear(); $('montar-build').onclick=()=>montarCreate(); for(const id of MONTAR_CUSTOMER)$(id).addEventListener('input',()=>{MONTAR.requestKey=null;montarPaintCustomer();montarPaintActions();}); diff --git a/web/kanban.css b/web/kanban.css index a77fe0f..15e6fb1 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -1666,3 +1666,12 @@ dialog.viewer::backdrop{background:var(--scrim)} .montar-size-row{height:44px} .montar-ajustes-dlg{max-height:92vh} } + +.montar-list-actions{display:flex;align-items:center;gap:8px} +.montar-list-actions>.btn{height:42px;white-space:nowrap} +.montar-list-text{min-height:210px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px;line-height:1.5} +.montar-list-errors{display:flex;flex-direction:column;gap:6px;max-height:320px;overflow:auto;padding:10px 12px;border-radius:10px;background:var(--sf2)} +.montar-list-errors p{margin:0;font-size:13px;color:var(--tx2);word-break:break-word} +@media (max-width:700px){ + .montar-list-actions{grid-column:1/-1;justify-content:flex-start} +} diff --git a/web/kanban.html b/web/kanban.html index dfb6434..4c307ff 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -131,7 +131,10 @@ - +
+ + +