fix: the layout lines up its columns and keeps 5 mm margins (layout version 3)
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 3m59s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Has been skipped

Dropstar's item 5 (2026-10-21). The engine placed pieces on a 5 mm grid,
rounding each up: two 28,2 cm pieces needed 57,5 cm on a 57 cm film, so the
second column slid 8 cm down, rows ended 8,6 mm apart and nothing was left
at the edges. Order 1 came out 97,14 cm long.

- pieces are laid out in rows with their exact sizes: 5 mm at the top, the
  bottom and between rows; across the width 5 mm at the edges and between
  pieces, or, when that does not fit, the space left shared out equally,
  never under 1,5 mm (order 1: 2 mm each, 89,42 cm long)
- each artwork stands or lies down, whichever gives the shorter sheet
- the shape packing (pieces fitting into each other) is kept only when it
  saves at least 1 cm; otherwise the columns stay aligned
- the order records layout version 3; quotes made with version 2 still pass
- the preview says the spacing really used

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-22 16:17:21 -03:00
parent fc3c08aced
commit 9849ae5c14
10 changed files with 143 additions and 22 deletions

View File

@@ -137,8 +137,14 @@ class ProductionPlacement(StrictModel):
rotation_degrees: Literal[0, 90, 180, 270]
mirrored: bool
# The layout rule an order was packed with. 2: pieces 5 mm apart on a 5 mm grid,
# no margins. 3 (Dropstar, 2026-10-21): 5 mm margins top and bottom and between
# rows, and across the width 5 mm or the space left shared out equally.
PRODUCTION_VERSIONS = (2, 3)
class ProductionSpec(StrictModel):
version: Literal[2]
version: Literal[2, 3]
film_width_cm: Decimal
height_cm: Decimal = Field(gt=0, le=1200000)
sources: list[ProductionSource] = Field(min_length=1, max_length=20)

View File

@@ -18,6 +18,7 @@ from psycopg.types.json import Jsonb
from . import machines, mail
from .core.auth import audit
from .core.models import PRODUCTION_VERSIONS
from .printjobs import queue as queue_print_files
from .runtime import PUBLIC_ORIGIN, enqueue, upload_row
from .scanning import require_clean
@@ -39,7 +40,7 @@ def approved_quote(c, quote_id, owner=None):
raise PaymentRefused('quote was never reviewed')
if row.get('discarded_at'):
raise PaymentRefused('quote was discarded')
if any(item.get('production', {}).get('version') != 2 for item in row['approved']['items']):
if any(item.get('production', {}).get('version') not in PRODUCTION_VERSIONS for item in row['approved']['items']):
raise PaymentRefused('quote uses an obsolete production layout; request a new quote')
if row['approved_at'] < datetime.now(timezone.utc) - timedelta(hours=QUOTE_VALID_HOURS):
raise PaymentRefused('quote expired before payment')

View File

@@ -26,6 +26,8 @@ from decimal import Decimal
from PIL import Image, ImageOps
from .core.models import PRODUCTION_VERSIONS
PT_PER_CM = 72 / 2.54
# Acrobat's page limit. Longer layouts scale user space with /UserUnit (PDF 1.6)
# rather than cutting the film into pages a RIP might print with gaps.
@@ -405,7 +407,7 @@ def render(item, files, out, title):
exported as PDF keeps its vectors, fonts and transparency.
"""
production = item['production']
if production.get('version') != 2:
if production.get('version') not in PRODUCTION_VERSIONS:
raise Unsupported('o item usa uma montagem antiga')
sources = []
try:

View File

@@ -19,6 +19,7 @@ from fastapi import HTTPException
from psycopg.types.json import Jsonb
from . import payments
from .core.models import PRODUCTION_VERSIONS
from .core.pricing import is_manual, manual_extra_cents, price
from .runtime import freight, upload_row
from .scanning import require_clean
@@ -42,7 +43,7 @@ def review_reason(draft):
if total > max_auto_metres():
return f'Pedido acima de {max_auto_metres():g} m'
for item in draft['items']:
if item.get('production', {}).get('version') != 2:
if item.get('production', {}).get('version') not in PRODUCTION_VERSIONS:
return 'Montagem antiga'
# The Site grades only the art it could analyse; anything else is
# priced at the full rate. A discount on it did not come from the Site.
@@ -57,7 +58,7 @@ def approve(c, row, items, reviewer):
draft = row['draft']
if row['approved']:
raise HTTPException(409, 'Esta cotação já foi aprovada e não pode mudar.')
if any(item.get('production', {}).get('version') != 2 for item in draft['items']):
if any(item.get('production', {}).get('version') not in PRODUCTION_VERSIONS for item in draft['items']):
raise HTTPException(409, 'A cotação usa uma montagem antiga: o cliente precisa montar o pedido de novo.')
if len(items) != len(draft['items']):
raise HTTPException(422, 'Confira todos os itens da cotação.')

View File

@@ -346,7 +346,10 @@ side); Números by date range, per machine (metres finished, metres per hour
in Imprimindo, last finished, now) and orders apart from passages. A machine's
metres are the film printed (item `metres`), never the billed ones, and time
two orders spent in Imprimindo together counts once; a stage's median is per
order, the sum of its passages. Waiting on
order, the sum of its passages. Layout version 3 (web/site-packing.js): rows
with exact sizes, 5 mm margins top and bottom and between rows, and across
the width 5 mm or the space left shared out equally (1,5 mm at least); the
shape packing is used only when it saves 1 cm or more. Waiting on
Dropstar: the Tiny category/seller/tag conflict, residue and opaque background
blocking, the print-file footer, the packing margins, the DTF terms, the
manual-file value, the proof print, and mirroring.

View File

@@ -188,26 +188,27 @@ try{
let layout=await packed(6);
await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.copies===6`),'per-file production record');
assert.deepEqual(await evaluate(`({version:itemAtual.production.version,source:itemAtual.production.sources[0]})`),
{version:2,source:{kind:'artwork',width_cm:20,length_cm:40,copies:6,
{version:3,source:{kind:'artwork',width_cm:20,length_cm:40,copies:6,
rotation_degrees:0,mirrored:false,measurement:'file'}});
assert.equal(await evaluate('itemAtual.production.placements.length'),6);
assert.equal(await evaluate('itemAtual.production.height_cm'),121);
// 5 mm margins top and bottom, between rows, at the edges and between pieces.
assert.equal(await evaluate('itemAtual.production.height_cm'),122);
assert.deepEqual(await evaluate('itemAtual.production.placements.map(p=>[p.source_index,p.copy_index,p.x_cm,p.y_cm])'),
[[0,0,0,0],[0,1,20.5,0],[0,2,0,40.5],[0,3,20.5,40.5],[0,4,0,81],[0,5,20.5,81]]);
assert.equal(layout.heading,'Montagem ao vivo');assert.equal(layout.height,121);
[[0,0,0.5,0.5],[0,1,21,0.5],[0,2,0.5,41],[0,3,21,41],[0,4,0.5,81.5],[0,5,21,81.5]]);
assert.equal(layout.heading,'Montagem ao vivo');assert.equal(layout.height,122);
assert.equal(layout.billed,1.3);
assert.deepEqual(layout.pos.map(p=>[p.x,p.y]),[[0,0],[20.5,0],[0,40.5],[20.5,40.5],[0,81],[20.5,81]]);
assert.deepEqual(layout.pos.map(p=>[p.x,p.y]),[[0.5,0.5],[21,0.5],[0.5,41],[21,41],[0.5,81.5],[21,81.5]]);
assert.ok(layout.pos.every(p=>p.h/p.w===2 && p.x+p.w<=57));
await screenshot('artwork-packed');
await fill('[data-cm]',15);
await waitFor(()=>evaluate('lastLayout?.altura===60.5 && metros===0.605'),'width updates without blur');
await fill('[data-q]',9);layout=await packed(9);assert.equal(layout.height,91);
await waitFor(()=>evaluate('lastLayout?.altura===61.5 && metros===0.615'),'width updates without blur');
await fill('[data-q]',9);layout=await packed(9);assert.equal(layout.height,92);
await click('[data-giro]');
await waitFor(()=>evaluate('lastLayout?.altura===23.5 && metros===0.235'),'rotation updates packing');
await waitFor(()=>evaluate('lastLayout?.altura===24.5 && metros===0.245'),'rotation updates packing');
const beforeMirror=await evaluate(`$('vArea').querySelector('canvas').toDataURL()`);
await click('[data-esp]');
await waitFor(()=>evaluate(`$('vArea').querySelector('canvas').toDataURL()!==${JSON.stringify(beforeMirror)}`),'mirror updates pixels');
assert.equal(await evaluate('metros'),0.235);
assert.equal(await evaluate('metros'),0.245);
await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.mirrored===true`),'transforms in production record');
assert.deepEqual(await evaluate(`({rotation:itemAtual.production.sources[0].rotation_degrees,copies:itemAtual.production.sources[0].copies})`),
{rotation:90,copies:9});
@@ -231,6 +232,22 @@ try{
assert.equal(await evaluate('cartPodeEnviar()'),false);
assert.equal(await evaluate(`(()=>{try{encaixar([{w:58,h:10,img:null}],57);return false}catch(error){return error instanceof RangeError}})()`),true,
'packing engine must not shrink an oversized source');
// Dropstar's order 1 (2026-10-21): six 28,2 x 29,14 cm pieces. Two fit across
// 57 cm only with 2 mm at each edge and between them: aligned columns, 5 mm
// rows and margins, 89,42 cm instead of the 97,14 cm the grid gave.
assert.deepEqual(await evaluate(`(()=>{const a={};
const r=encaixar(Array.from({length:6},(_,i)=>({w:28.2,h:29.14,img:null,a,copyIndex:i})),57);
return {altura:+r.altura.toFixed(2),folga:+r.folga.toFixed(3),
xs:[...new Set(r.pos.map(p=>+p.x.toFixed(2)))],ys:[...new Set(r.pos.map(p=>+p.y.toFixed(2)))]};})()`),
{altura:89.42,folga:0.2,xs:[0.2,28.6],ys:[0.5,30.14,59.78]});
// UV, 28,5 cm: two 14 cm pieces still share a row, 1,67 mm apart.
assert.equal(await evaluate(`(()=>{const a={};const r=encaixar([{w:14,h:10,img:null,a},{w:14,h:10,img:null,a}],28.5);
return new Set(r.pos.map(p=>p.y)).size===1 && Math.abs(r.folga-0.5/3)<1e-9})()`),true);
// A long piece stands up when that shortens the sheet: 30 x 10 cm, eight copies,
// five to a row turned instead of one to a row as sent.
assert.deepEqual(await evaluate(`(()=>{const a={};const r=encaixar(Array.from({length:8},()=>({w:30,h:10,img:null,a})),57);
return {rot:[...new Set(r.pos.map(p=>p.rot))],altura:+r.altura.toFixed(2)}})()`),
{rot:[90],altura:61.5});
await click('[data-rm]');
assert.equal(await evaluate(`artes.length===0 && itemAtual===null && !cartPodeEnviar()`),true,
'removed artwork cannot remain in the cart');

View File

@@ -31,6 +31,9 @@ class ReviewReasonTest(unittest.TestCase):
def test_old_layouts_and_switching_it_off(self):
self.assertEqual(self.reason(item(version=1)), 'Montagem antiga')
# Version 3 is the layout with margins (2026-10-21); a quote made before it still passes.
self.assertNotEqual(self.reason(item(version=3)), 'Montagem antiga')
self.assertNotEqual(self.reason(item(version=2)), 'Montagem antiga')
self.assertEqual(self.reason(item(), QUOTE_AUTO_APPROVE='false'), 'Aprovação automática desligada')

View File

@@ -133,7 +133,7 @@ function carrinho(){
fotos:(ehFolha()?folhas:artes).map(x=>x.fotoSrc||null),
ext:extDe(((ehFolha()?folhas:artes)[0]||{f:{name:''}}).f.name),
arquivos:(ehFolha()?folhas:artes).length,
production:{version:2,film_width_cm:larguraFilme(),sources,...layout},
production:{version:3,film_width_cm:larguraFilme(),sources,...layout},
qualityStatus:$('ciente').classList.contains('recusa')?'rejected':
$('ciente').classList.contains('on')?'warning':nota===0?'unverified':'ok',
qualityAcknowledged:false,

View File

@@ -89,6 +89,7 @@ const folhaTotalM=()=>folhas.reduce((t,x)=>t+(x.m||0)*(x.rep||1),0);
const PAR={file:'avulsa', avulsa:'file', uvfile:'uv', uv:'uvfile'};
let montagemCm=0; // altura da folha montada pelo motor, em cm
let montagemLayout=null; // posições aprovadas de cada cópia, em cm
let montagemFolgaCm=0.5; // a menor folga da montagem na largura
const ZOOMS=[1,1.5,2,3,4]; let zoomI=0; // ampliação da montagem ao vivo
let pedido=[]; // itens já fechados · o pagamento é um só
// A escolha de entrega vale para o pedido inteiro, não por item. No Tiny, retirada

View File

@@ -118,10 +118,94 @@ function mascara(img,w,h,rot,esp=false){
return dilatar(bruto,cw,ch,cheias);
}
// Encaixe pela forma, como o motor do servidor: mapa de ocupação real,
// máscara por arte e candidatos numa grade ao longo da largura.
// pecas em centímetros: {w,h,img}. W é a largura do filme em cm.
// Margens e folgas da folha (regra da Dropstar, 21/10/2026): 5 mm em cima,
// embaixo e entre as linhas. Na largura, 5 mm nas bordas e entre as peças como
// alvo; quando não cabem, a sobra é dividida em partes iguais, e duas peças só
// ficam lado a lado com pelo menos 1,5 mm entre elas e nas bordas.
const MARGEM_CM=0.5, FOLGA_MIN_CM=0.15;
// Pela forma, as peças se aproximam (favo de mel) e as colunas se deslocam.
// Só compensa quando a folha encurta de verdade; senão, colunas alinhadas.
const GANHO_FORMA_CM=1;
// pecas em centímetros: {w,h,img,a,travado}. W é a largura do filme em cm.
// Devolve {pos, altura, folga}: a altura já com as margens, a folga a menor
// usada na largura.
function encaixar(pecas,W){
if(pecas.some(p=>!Number.isFinite(p.w) || p.w<=0 || p.w>W))
throw new RangeError('A largura solicitada não cabe no filme.');
const linhas=encaixarEmLinhas(pecas,W);
const forma=encaixarComMargens(pecas,W);
if(forma.altura<=linhas.altura-GANHO_FORMA_CM) return forma;
// A máscara de cada peça: a área de arte que a prévia mostra como aproveitada.
const mascaras=new Map();
linhas.pos.forEach(p=>{
const k=p.ref.a||p.ref, giro=p.rot+(p.ref.a?.giro||0);
if(!mascaras.has(k)) mascaras.set(k,new Map());
const daArte=mascaras.get(k);
if(!daArte.has(p.rot)) daArte.set(p.rot,mascara(p.ref.img,p.w,p.h,giro,p.ref.a?.esp));
p.m=daArte.get(p.rot);
});
return linhas;
}
// Em linhas, com as medidas exatas: cada arte (todas as cópias juntas) fica de
// pé ou deitada, a que der a folha mais curta. Em arte retangular, girar 90° é
// o que mais economiza filme.
function encaixarEmLinhas(pecas,W){
const arteDe=p=>p.a||p;
const artes=[...new Set(pecas.map(arteDe))];
const giraveis=artes.filter(arte=>{const p=pecas.find(q=>arteDe(q)===arte);
return !p.mPronta && !p.travado && Math.abs(p.w-p.h)>1 && p.h<=W;});
const deitadas=new Set();
const montar=()=>emLinhas(pecas.map(p=>deitadas.has(arteDe(p))
? {ref:p,w:p.h,h:p.w,rot:90} : {ref:p,w:p.w,h:p.h,rot:0}),W);
const virar=arte=>deitadas.has(arte)?deitadas.delete(arte):deitadas.add(arte);
let melhor=montar();
for(let volta=0;volta<2;volta++){
let mudou=false;
for(const arte of giraveis){
virar(arte);
const teste=montar();
if(teste.altura<melhor.altura-1e-9){melhor=teste;mudou=true;}
else virar(arte);
}
if(!mudou) break;
}
return melhor;
}
// As mais altas primeiro; cada uma na primeira linha onde couber.
function emLinhas(itens,W){
const ordem=[...itens].sort((a,b)=>b.h-a.h||b.w-a.w);
const linhas=[];
for(const it of ordem){
const linha=linhas.find(l=>l.soma+it.w+(l.itens.length+2)*FOLGA_MIN_CM<=W+1e-9);
if(linha){ linha.itens.push(it); linha.soma+=it.w; }
else linhas.push({itens:[it],soma:it.w,h:it.h}); // sozinha, cabe sempre
}
const pos=[];
let y=MARGEM_CM, folgaMin=MARGEM_CM;
linhas.forEach((l,i)=>{
const folga=Math.min(MARGEM_CM,(W-l.soma)/(l.itens.length+1));
folgaMin=Math.min(folgaMin,folga);
let x=folga;
for(const it of l.itens){ pos.push({x,y,w:it.w,h:it.h,rot:it.rot,ref:it.ref}); x+=it.w+folga; }
y+=l.h+(i<linhas.length-1?MARGEM_CM:0);
});
return {pos, altura:y+MARGEM_CM, folga:folgaMin};
}
// O encaixe pela forma dentro das margens: 5 mm em cima e embaixo e, dos
// lados, 5 mm ou o que a peça mais larga deixar.
function encaixarComMargens(pecas,W){
const maior=Math.max(...pecas.map(p=>p.w));
const lado=Math.max(0,Math.min(MARGEM_CM,(W-maior)/2));
const enc=encaixarPelaForma(pecas,W-2*lado);
return {pos:enc.pos.map(p=>({...p, x:p.x+lado, y:p.y+MARGEM_CM})),
altura:enc.altura+2*MARGEM_CM, folga:lado};
}
// Encaixe pela forma: mapa de ocupação real, máscara por arte e candidatos
// numa grade de 5 mm ao longo da largura.
function encaixarPelaForma(pecas,W){
const cols=Math.ceil(W/CEL)+1; // +1 = a coluna de folga da dilatação
let linhas=0; const mapa=[];
function garantir(ate){ while(linhas<ate){ mapa.push(new Uint8Array(cols)); linhas++; } }
@@ -269,9 +353,9 @@ function desenhaMontagem(area,lista,mts,W,fora,aoTerminar){
+ (girou? ' · <b style="display:inline">'+girou+
(girou>1?' artes giradas':' arte girada')+' 90°</b> para caber melhor':'');
(fora||area).appendChild(el);
if(aoTerminar) aoTerminar({alturaCm, uso, girou,
if(aoTerminar) aoTerminar({alturaCm, uso, girou, folgaCm:enc.folga,
placements:enc.pos.map(p=>({source_index:p.ref.a.sourceIndex,
copy_index:p.ref.copyIndex,x_cm:p.x,y_cm:p.y,
copy_index:p.ref.copyIndex,x_cm:+p.x.toFixed(4),y_cm:+p.y.toFixed(4),
width_cm:+p.w.toFixed(4),length_cm:+p.h.toFixed(4),
rotation_degrees:(p.rot+(p.ref.a.giro||0))%360,
mirrored:!!p.ref.a.esp}))});
@@ -342,6 +426,7 @@ function previaAoVivo(){
$('vArea').classList.toggle('ampliado', zoomI>0);
desenhaMontagem($('vArea'), prontas, 0, W, $('vUso'), r=>{
montagemCm = r.alturaCm; // altura real da folha montada
montagemFolgaCm = r.folgaCm ?? MARGEM_CM;
montagemLayout=r.placements ? {height_cm:+r.alturaCm.toFixed(4),
placements:r.placements} : null;
$('vMt').textContent = r.alturaCm? fmtM(cobrar(r.alturaCm/100))+' m' : '—';
@@ -375,7 +460,9 @@ function previa(){
$('pSub').textContent='folha montada por nós com as artes que você enviou';
const linhas=[
['var(--verde)','✓','Largura',larguraFilme()+' cm · dentro do padrão da máquina'],
['var(--verde)','✓','Espaço entre artes','5 mm garantidos'],
['var(--verde)','✓','Espaço entre artes', montagemFolgaCm>=MARGEM_CM-1e-9
? '5 mm entre as artes e nas bordas'
: n1(montagemFolgaCm*10)+' mm · 5 mm não cabem na largura, a sobra fica dividida por igual'],
[nota>=75?'var(--verde)':'var(--laranja)', nota>=75?'✓':'!','Qualidade da folha',motivoNota()],
['var(--verde)','✓','Metragem proporcional',
'sua folha tem '+fmtM(metros)+' m e você paga '+fmtM(cob)+