fix: the proof crops the finest stroke and closes the contact wait (0.1)

The browser records where the thinnest stroke sits in the assembled film;
the proof takes a 15 cm window around it instead of always the top. A free
proof no longer fails the layout's billed-metres check, and answering the
proof card clears "Aguardando contato" and ends its timer.
This commit is contained in:
Cauê Faleiros
2026-11-06 11:02:39 -03:00
parent d69e326125
commit 392e7da85b
12 changed files with 163 additions and 17 deletions

View File

@@ -825,6 +825,12 @@ def proof_answer(uid: UUID, body: ProofAnswer, user=Depends(can('proof'))):
version=version+1, updated_at=now() WHERE id=%s''', (parent['id'],))
c.execute('''INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
VALUES(%s,%s,'rec',%s,%s)''', (parent['id'], parent['state'], user, label))
# The proof answer is the contact with the customer: the old
# "Aguardando contato" mark has done its job either way (0.1).
c.execute('''UPDATE dtf_local.orders SET contact_since=NULL, contact_by=NULL, contact_note=NULL
WHERE id=%s''', (parent['id'],))
c.execute('UPDATE dtf_local.contact_waits SET ended_at=now() WHERE order_id=%s AND ended_at IS NULL',
(parent['id'],))
audit('order_proof_answered', order=parent['number'], result=body.result, operator=user)
return {'ok': True}

View File

@@ -190,6 +190,9 @@ class Item(StrictModel):
# A sheet with fine lines and solid areas (item 16): the customer kept the
# measure (protect the fine lines) or chose to protect the solid areas (C3).
stroke_choice: Literal['measured', 'client_c3'] | None = None
# Where the thinnest stroke sits in the assembled film, from 0 (top) to 1
# (bottom): the proof card crops a 15 cm window around it (Dropstar, 05/11).
proof_y_fraction: Decimal | None = Field(default=None, ge=0, le=1)
split: Split | None = None
@model_validator(mode='after')

View File

@@ -380,13 +380,14 @@ def open_source(path, name):
return SourceImage(path, name)
def check_layout(item, sizes, vector=()):
def check_layout(item, sizes, vector=(), proof=False):
"""Refuse a layout the file cannot reproduce faithfully. Returns the lowest
DPI of the raster sources (vector pages have none)."""
DPI of the raster sources (vector pages have none). A proof is free of
charge, so its zero billed metres must not reject the item's full sheet."""
production = item['production']
height = Decimal(str(production['height_cm']))
billed = Decimal(str(item['billed_metres'])) * 100
if height > billed + HEIGHT_TOLERANCE_CM:
if not proof and height > billed + HEIGHT_TOLERANCE_CM:
raise Unsupported(f'a montagem tem {height} cm, mas só {billed} cm foram cobrados')
lowest = None
for placement in production['placements']:

View File

@@ -254,7 +254,8 @@ def produce(storage, job, item, uploads):
prefix = (f'DTF-{job["number"]}-prova-{item.get("stroke_class") or "C3"}' if proof_of
else file_prefix(job['number'], job['item_index']))
parts, detail = render(item, files, output, prefix, footer=footer(job, item), tiles=True,
limit_cm=PROOF_SHEET_CM if proof_of else None)
limit_cm=PROOF_SHEET_CM if proof_of else None,
proof_fraction=item.get('proof_y_fraction') if proof_of else None)
except BaseException:
shutil.rmtree(output, ignore_errors=True)
raise

View File

@@ -395,6 +395,21 @@ def part_cuts(production, part_cm=None):
return cuts
def proof_cut(height_cm, limit_cm, fraction=None):
"""A proof's window, in cm from the film's top: `limit_cm` centred on the
thinnest stroke (fraction 0 at the top, 1 at the bottom), clamped inside
the film. Without a measured fraction it starts at the top, as before."""
height = Decimal(str(height_cm))
if height <= 0:
return [Decimal(0), Decimal(0)]
span = min(height, Decimal(str(limit_cm)))
if fraction is None:
return [Decimal(0), span]
center = min(Decimal(1), max(Decimal(0), Decimal(str(fraction)))) * height
start = min(height - span, max(Decimal(0), center - span / 2))
return [start, start + span]
def _font(size):
return ImageFont.load_default(size=size)
@@ -425,12 +440,14 @@ def footer_band(text, width):
# ---- The file ---------------------------------------------------------------
def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False, limit_cm=None):
def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False, limit_cm=None,
proof_fraction=None):
"""Write the PNG part(s) of one approved order item into `out_dir`.
`files` maps each source index to (local path, original name). With
`tiles`, each part's pieces for the Kanban's viewer go in
out_dir/tiles/<part name>/<level>/<index>.png (app/printtiles.py).
A proof (`limit_cm`) is a free 15 cm window around `proof_fraction`.
Returns the parts, [(path, name)], and the evidence the Kanban shows.
"""
production = item['production']
@@ -439,12 +456,13 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False,
sources = [Source(*files[index]) for index in range(len(production['sources']))]
try:
vector = {index for index, source in enumerate(sources) if source.pdf}
lowest = check_layout(item, [source.size for source in sources], vector)
lowest = check_layout(item, [source.size for source in sources], vector, proof=bool(limit_cm))
width = px(production['film_width_cm'])
pieces = sorted((Piece(placement, sources[placement['source_index']])
for placement in production['placements']), key=lambda piece: piece.y)
# A proof sheet is the film's first `limit_cm` (app/proof.py).
cuts = ([Decimal(0), min(Decimal(str(production['height_cm'])), Decimal(str(limit_cm)))] if limit_cm
# A proof sheet is a 15 cm window around the finest stroke; a normal
# file is cut into parts (app/proof.py, item 0.1).
cuts = (proof_cut(production['height_cm'], limit_cm, proof_fraction) if limit_cm
else part_cuts(production, part_cm))
count = len(cuts) - 1
parts, manifests = [], []

View File

@@ -85,6 +85,8 @@ def approve(c, row, items, reviewer):
**({'stroke_choice': original['stroke_choice']} if original.get('stroke_choice') else {}),
**({'stroke_choice_at': original['stroke_choice_at']}
if original.get('stroke_choice_at') else {}),
**({'proof_y_fraction': original['proof_y_fraction']}
if original.get('proof_y_fraction') is not None else {}),
**({'split': original['split']} if original.get('split') else {})})
bill_splits(priced)
metres = sum(Decimal(i['billed_metres']) for i in priced)

View File

@@ -141,9 +141,10 @@ def run():
client.call('/operator/orders/' + oid + '/move', {'state': 'tra', 'version': version}, operator=True)
version += 1
# Printing, the folders still get the file of an order they hold (to take
# it to Finalizado later), and no one else's.
machine = client.call('/operator/machines', {'name': 'Print test '+uuid4().hex[:6],
'products': ['textil']}, operator=True)['id']
# it to Finalizado later), and no one else's. The pull chooses the machine.
tag = uuid4().hex[:6]
machine = client.call('/operator/machines', {'name': f'Hot {tag}', 'products': ['textil']},
operator=True)['id']
client.call('/operator/orders/' + oid + '/move', {'state': 'imp', 'version': version,
'machine_id': machine}, operator=True)
version += 1
@@ -170,10 +171,7 @@ def run():
# Item 10: printing, the file goes once into its machine's hot folder for
# its class; Flexi taking it is reported; leaving Imprimindo withdraws
# what Flexi did not take.
tag = uuid4().hex[:6]
machine = client.call('/operator/machines', {'name': f'Hot {tag}', 'products': ['textil']}, operator=True)['id']
try:
client.call('/operator/orders/' + oid + '/machine', {'machine_id': machine}, operator=True)
# No class measured or chosen: the part waits for one.
assert not [p for p in client.call('/operator/queue/hot', {}, operator=True)['write'] if p['order'] == oid]
client.call('/operator/orders/' + oid + '/contraction', {'item_index': 0, 'value': 'C2'}, operator=True)
@@ -215,6 +213,7 @@ def run():
unread = upload_bytes(client, b'LOCAL PRINT TEST - NOT AN IMAGE', name='LOCAL-PROOF-TEST.cdr')
long = loose_item(unread, copies=1)
long['metres'] = '10.5'
long['proof_y_fraction'] = '0.8'
long['production'] = {**long['production'], 'height_cm': 1050,
'placements': [{**long['production']['placements'][0], 'y_cm': 1040}]}
parent = paid_order(client, long)
@@ -223,6 +222,13 @@ def run():
card = next(o for o in board if o['id'] == mine['proof_card']['id'])
assert card['proof_parent']['number'] == parent['number'] and card['state'] == 'rec', card
assert card['snapshot']['proof_of'] == parent['number'] and card['payment'] == {'provider': 'prova'}
assert float(card['snapshot']['items'][0]['proof_y_fraction']) == 0.8, card['snapshot']['items'][0]
# The proof answer is the customer contact: the old "Aguardando contato"
# mark must not survive it (item 0.1).
with db.connect() as c:
c.execute("""UPDATE dtf_local.orders SET contact_since=now(), contact_by='Site',
contact_note='Prova pedida no site' WHERE id=%s""", (parent['id'],))
c.execute('INSERT INTO dtf_local.contact_waits(order_id,started_at) VALUES(%s,now())', (parent['id'],))
with db.connect() as c:
assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key LIKE %s', (card['id'] + '%',)).fetchone()
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s", (card['id'],))
@@ -249,6 +255,10 @@ def run():
mine = next(o for o in board if o['id'] == parent['id'])
assert mine['state'] == 'rec' and mine['proof_card']['proof_result'] == 'rejected', mine['proof_card']
assert mine['proof_card']['proof_reason'] == 'Cor do fundo errada'
assert not mine.get('contact_since'), mine
with db.connect() as c:
assert c.execute('SELECT ended_at FROM dtf_local.contact_waits WHERE order_id=%s',
(parent['id'],)).fetchone()['ended_at']
assert not [o for o in board if o['id'] == card['id']], 'an answered proof card leaves the board'
# Rejection releases the parent for corrected artwork, until a new proof card is opened.
final = upload_bytes(client, artwork(), name='LOCAL-PROOF-FINAL.png', order_id=parent['id'])

26
tests/test_proof_cut.py Normal file
View File

@@ -0,0 +1,26 @@
"""The proof window: 15 cm around the finest stroke, never outside the film."""
import unittest
from decimal import Decimal
from app.printpng import proof_cut
class ProofCutTests(unittest.TestCase):
def test_centres_the_window_on_the_finest_stroke(self):
self.assertEqual(proof_cut(100, 15, 0.5), [Decimal('42.5'), Decimal('57.5')])
self.assertEqual(proof_cut(100, 15, 0.8), [Decimal('72.5'), Decimal('87.5')])
def test_clamps_at_both_ends(self):
self.assertEqual(proof_cut(100, 15, 0), [Decimal(0), Decimal(15)])
self.assertEqual(proof_cut(100, 15, 1), [Decimal(85), Decimal(100)])
def test_a_short_film_is_the_whole_proof(self):
self.assertEqual(proof_cut(10, 15, 0.5), [Decimal(0), Decimal(10)])
self.assertEqual(proof_cut(10, 15, None), [Decimal(0), Decimal(10)])
def test_without_a_measure_the_old_top_window_remains(self):
self.assertEqual(proof_cut(100, 15, None), [Decimal(0), Decimal(15)])
if __name__ == '__main__':
unittest.main()

View File

@@ -0,0 +1,66 @@
"""A free proof is a 15 cm window around the measured fine stroke, not the top."""
import io
import tempfile
import unittest
from pathlib import Path
from PIL import Image, ImageDraw
from app.printpng import render
PX_CM = 300 / 2.54
def item(height_cm=30, fraction='0.75'):
return {
'mode': 'file', 'metres': '10.5', 'billed_metres': '0',
'production': {
'version': 3, 'film_width_cm': 20, 'height_cm': height_cm,
'sources': [{'upload_id': '00000000-0000-0000-0000-000000000001',
'kind': 'sheet', 'width_cm': 20, 'length_cm': height_cm,
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
'measurement': 'file'}],
'placements': [{'source_index': 0, 'copy_index': 0, 'x_cm': 0, 'y_cm': 0,
'width_cm': 20, 'length_cm': height_cm,
'rotation_degrees': 0, 'mirrored': False}],
},
'proof_parent_item_index': 0, 'proof_y_fraction': fraction,
}
class ProofRenderTests(unittest.TestCase):
def _sheet(self, folder):
height = round(30 * PX_CM)
width = round(20 * PX_CM)
image = Image.new('RGBA', (width, height), (220, 30, 60, 255))
ImageDraw.Draw(image).rectangle((0, height // 2, width - 1, height - 1),
fill=(30, 60, 220, 255))
path = Path(folder) / 'sheet.png'
image.save(path, 'PNG', dpi=(300, 300))
return str(path)
def test_the_window_follows_the_finest_stroke(self):
with tempfile.TemporaryDirectory() as source, tempfile.TemporaryDirectory() as out:
sheet = self._sheet(source)
parts, detail = render(item(), {0: (sheet, 'sheet.png')}, out, 'proof',
limit_cm=15, proof_fraction='0.75')
self.assertEqual(len(parts), 1)
self.assertEqual(detail['parts'][0]['from_cm'], '15')
with Image.open(parts[0][0]) as proof:
self.assertEqual(proof.width, round(20 * PX_CM))
self.assertLessEqual(abs(proof.height - round(15 * PX_CM)), 1)
# The bottom half is blue: the window covered 15 to 30 cm.
self.assertEqual(proof.getpixel((proof.width // 2, round(5 * PX_CM))), (30, 60, 220, 255))
def test_the_top_is_still_the_default_without_a_measure(self):
with tempfile.TemporaryDirectory() as source, tempfile.TemporaryDirectory() as out:
sheet = self._sheet(source)
parts, detail = render(item(fraction=None), {0: (sheet, 'sheet.png')}, out, 'proof',
limit_cm=15)
self.assertEqual(detail['parts'][0]['from_cm'], '0')
with Image.open(parts[0][0]) as proof:
self.assertEqual(proof.getpixel((proof.width // 2, round(5 * PX_CM))), (220, 30, 60, 255))
if __name__ == '__main__':
unittest.main()

View File

@@ -359,6 +359,7 @@
residue_accepted:item.residueAccepted||0,
...(item.strokeClass?{stroke_px:item.strokePx,stroke_class:item.strokeClass}:{}),
...(item.strokeChoice?{stroke_choice:item.strokeChoice}:{}),
...(item.proofYFraction!=null?{proof_y_fraction:item.proofYFraction}:{}),
...(item.split?{split:item.split}:{})});
}
const service = entrega.tipo==='retira' ? 'pickup' : entrega.servico;

View File

@@ -123,7 +123,7 @@ function carrinho(){
localFiles:f.artes.map(x=>x.f), fotos:f.artes.map(x=>x.fotoSrc||null),
metros:+(f.layout.height_cm/100).toFixed(4),
production:{version:3,film_width_cm:larguraFilme(),sources:f.artes.map(fonteDaArte),...f.layout},
residueAccepted:residuosDasArtes(f.artes), ...tracoDoItem(f.artes)}));
residueAccepted:residuosDasArtes(f.artes), ...tracoDoItem(f.artes,f.layout)}));
layout=null;
}else{
if(!montagemLayout) return;

View File

@@ -46,7 +46,18 @@ function perguntaMista(){
// O traço mais fino do item (item 9, Dropstar 30/10/2026): o menor entre as
// folhas que o navegador mediu. Não aparece para o cliente; vai para a sala,
// que confere a classe de contração ao aprovar o arquivo final.
function tracoDoItem(lista){
// Onde o traço mais fino cai no filme montado (0 no topo, 1 no fim): a prova
// de 15 cm é recortada em volta dele, não no começo da folha (item 0.1).
function fracaoNoFilme(layout,sourceIndex,fraction){
if(!layout || !(layout.height_cm>0)) return fraction||0;
const placement=(layout.placements||[]).find(p=>p.source_index===sourceIndex);
if(!placement) return fraction||0;
const y=placement.rotation_degrees%180===90
? placement.y_cm+placement.length_cm/2
: placement.y_cm+(fraction||0)*placement.length_cm;
return Math.max(0,Math.min(1,y/layout.height_cm));
}
function tracoDoItem(lista,layout){
const arquivos=lista||(ehFolha()?folhas:artes);
const medidas=arquivos.map((x,index)=>({index,traco:lista?tracoDaArte(x):tracoDoArquivo(x)})).filter(x=>x.traco);
if(!medidas.length) return {strokePx:null, strokeClass:null, strokeChoice:null};
@@ -54,7 +65,8 @@ function tracoDoItem(lista){
// Avisado do item 16, o cliente quis imprimir assim: fica a medida, C1.
const avisado=arquivos.some(x=>x.mistaVista && mista(lista?tracoDaArte(x):tracoDoArquivo(x)));
return {strokePx:fino.traco.px, strokeClass:fino.traco.classe, strokeChoice:avisado?'measured':null,
proofSourceIndex:fino.index, proofYFraction:fino.traco.proofYFraction||0};
proofSourceIndex:fino.index,
proofYFraction:fracaoNoFilme(lista?layout:montagemLayout,fino.index,fino.traco.proofYFraction||0)};
}
// Avalia sozinho conforme o cliente sobe e preenche. Devolve o que ainda falta,
// para a fila dizer em texto em vez de travar num botão.