fix: the server refuses stacked pieces and files laid out at other proportions, and never cuts a strip with ink
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Secret scan and release gate (push) Has been cancelled
Build and deploy / Integration suite on a real stack (push) Has been cancelled

The price came from the layout the browser sent, checked only in part:
- Pieces on top of each other passed: 100 copies stacked in one place bill
  10 cm and print over each other. The layout validator now refuses any
  overlap.
- A file laid out at proportions it does not have (a 5 m sheet sent as
  10 cm) was found only by the print file, after payment. The quote now
  checks each raster file's proportions from the bytes it already reads.
- The empty strips the Site cuts from a ready sheet were cut on its word.
  The print file now reads them: a strip with ink sends the item to hand
  preparation with the reason, instead of printing the art cut off.

Test fixtures that laid real images out at impossible proportions now keep
the image's own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-27 15:56:00 -03:00
parent 6970434e5d
commit bb6fb14b1a
11 changed files with 201 additions and 17 deletions

View File

@@ -13,7 +13,7 @@ from ..core import db
from ..core.auth import owner
from ..core.models import QuoteRequest
from .. import quote_review
from ..grade_check import Files, mismatch, resolution_issue, source_dpi
from ..grade_check import Files, mismatch, proportion_issue, resolution_issue, source_dpi
from ..runtime import freight, payment, quote_view, require_delivery_available, storage, upload_row
from ..scanning import require_clean
@@ -79,7 +79,7 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
dpis.append(dpi)
if dpis:
draft_item['source_dpi'] = round(min(dpis))
issue = resolution_issue(files, draft['items'], rows)
issue = proportion_issue(files, draft['items'], rows) or resolution_issue(files, draft['items'], rows)
if issue:
raise HTTPException(422, issue)
note = mismatch(files, draft['items'], rows) if reason is None else None

View File

@@ -291,6 +291,17 @@ class Item(StrictModel):
raise ValueError('Finished sheets must retain their original orientation')
if placed != expected:
raise ValueError('Production layout does not cover every source copy')
# No piece on top of another: stacked pieces bill less film than they
# print on, and print over each other. Swept down the film, so only
# the pieces still open at each row are compared.
boxes = sorted((p.y_cm, p.y_cm + p.length_cm, p.x_cm, p.x_cm + p.width_cm)
for p in self.production.placements)
open_boxes = []
for top, bottom, left, right in boxes:
open_boxes = [b for b in open_boxes if b[0] > top + tolerance]
if any(l < right - tolerance and left < r - tolerance for _, l, r in open_boxes):
raise ValueError('Duas peças da montagem ficaram uma sobre a outra. Monte o pedido de novo.')
open_boxes.append((bottom, left, right))
if self.quality_status == 'warning' and not self.quality_acknowledged:
raise ValueError('Resolution warning must be acknowledged')
return self

View File

@@ -227,6 +227,35 @@ def resolution_issue(files, items, rows):
return None
def proportion_issue(files, items, rows):
"""Why a cart's layout cannot be priced, or None: a raster file laid out
at proportions it does not have (a 5 m sheet sent as 10 cm, say). The
print file refuses the same thing (app/printfile.py check_layout), but
only after payment; here it is refused before. A PDF, or a file whose
size the first bytes do not tell, is left to that later check."""
from .printfile import ASPECT_TOLERANCE
for index, item in enumerate(items, 1):
for number, source in enumerate(item['production']['sources'], 1):
row = rows.get(str(source['upload_id']))
if not row or row['name'].lower().endswith('.pdf'):
continue
size = image_size(files.head(row))
if not size or not all(size):
continue
width_px, height_px = size
if source.get('rotation_degrees') in (90, 270):
width_px, height_px = height_px, width_px
# A ready sheet's empty strips were cut from its length: the file
# is the length plus both strips (app/core/models.py).
length = (float(source['length_cm']) + float(source.get('trim_top_cm') or 0)
+ float(source.get('trim_bottom_cm') or 0))
drift = abs((width_px / height_px) / (float(source['width_cm']) / length) - 1)
if drift > ASPECT_TOLERANCE:
return (f'Item {index}: o arquivo {number} foi montado com {source["width_cm"]} × '
f'{source["length_cm"]} cm, que não são as proporções dele. Monte o pedido de novo.')
return None
def mismatch(files, items, rows):
"""Why a cart's grades cannot be approved at checkout, or None."""
for item in items:

View File

@@ -48,6 +48,8 @@ PART_CM = Decimal(os.environ.get('PRINT_PART_CM', '1000'))
# A cut through artwork only when no gap between pieces is this close to the limit.
CUT_SEARCH_CM = Decimal('200')
BAND_ROWS = 512
# A pixel above this alpha takes ink (web/site-sheet.js ALFA_TINTA).
INK_ALPHA = 10
# Above this a source is read band by band instead of decoded whole.
STREAM_ABOVE_PIXELS = 40_000_000
FOOTER_TEXT_CM = 1.1
@@ -268,9 +270,44 @@ class Source:
top, bottom = round(height * top_cm / full_cm), round(height * bottom_cm / full_cm)
if top + bottom >= height:
raise Unsupported(f'"{self.name}": o corte das faixas vazias tiraria o arquivo inteiro')
self._require_clear(top, bottom)
self.cut = (top, bottom)
self.size = (width, height - top - bottom)
def _require_clear(self, top, bottom):
"""The strips the Site measured as empty must be: cut on a measure the
file does not bear out, artwork would leave the print unseen. A pixel
takes ink above INK_ALPHA, as the Site counts it. Not clear, or too
big to read here: the item goes to hand preparation, with the reason."""
width, height = self.size
where = lambda first: 'do começo' if first else 'do fim'
def check(band, offset):
for start, stop, first in ((0, top, True), (height - bottom, height, False)):
a, b = max(start, offset), min(stop, offset + band.height)
if a < b and rgba(band.crop((0, a - offset, band.width, b - offset))).getchannel('A').getextrema()[1] > INK_ALPHA:
raise Unsupported(f'"{self.name}": a faixa que o site cortou {where(first)} do arquivo tem arte. '
'Confira o arquivo e prepare a folha à mão')
if self.streamable:
reader = PngRows(self.path)
try:
done = 0
# Read in order to the end of the bottom strip (or of the top one).
while done < (height if bottom else top):
band = reader.band(BAND_ROWS)
if done < top or done + band.height > height - bottom:
check(band, done)
done += band.height
finally:
reader.close()
return
if width * height > MAX_DECODED_PIXELS:
raise Unsupported(f'"{self.name}" é grande demais para conferir as faixas cortadas; prepare a folha à mão')
with Image.open(self.path) as image:
image = ImageOps.exif_transpose(image) if self.orientation != 1 else image
check(image, 0)
def decoded(self, width, height):
"""The whole file at (width, height) px, upright, RGBA."""
if self.pdf:

View File

@@ -38,11 +38,11 @@ def run():
upload_id = None
try:
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-COUPON-{tag}.png')
sheet = {**item_spec('uvfile', '1', 0, upload_id),
sheet = {**item_spec('uvfile', '1', 0, upload_id, aspect=2),
'quality_status': 'warning', 'quality_acknowledged': True}
# The sheet is the customer's own file, not one someone opens by hand.
sheet['production']['sources'][0]['measurement'] = 'file'
art = {**item_spec('uv', '1', 0, upload_id),
art = {**item_spec('uv', '1', 0, upload_id, aspect=2),
'quality_status': 'warning', 'quality_acknowledged': True}
items = [sheet, art]

View File

@@ -44,7 +44,7 @@ def run():
assert rules['treatment_offered'] is True, rules
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-GRADE-{tag}.png')
item = {**item_spec('uv', '1', 50, upload_id),
item = {**item_spec('uv', '1', 50, upload_id, aspect=2),
'quality_status': 'warning', 'quality_acknowledged': True}
refused = client.call('/quotes', quote_body(item, False, mail), expected=422)

View File

@@ -40,12 +40,13 @@ def quote(client, item, mail, expected=200):
def arts_item(upload_id, arts):
"""One loose-art item with `arts` sources of 10 x 10 cm, one metre long."""
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 10,
"""One loose-art item with `arts` sources of 10 x 5 cm (artwork() is 2:1),
one every 10 cm."""
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 5,
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
'measurement': 'customer'} for _ in range(arts)]
placements = [{'source_index': index, 'copy_index': 0, 'x_cm': 0, 'y_cm': index * 10,
'width_cm': 10, 'length_cm': 10, 'rotation_degrees': 0, 'mirrored': False}
'width_cm': 10, 'length_cm': 5, 'rotation_degrees': 0, 'mirrored': False}
for index in range(arts)]
return {'mode': 'avulsa', 'metres': '1', 'grade': 90, 'uploads': [upload_id] * arts,
'production': {'version': 3, 'film_width_cm': 57, 'height_cm': arts * 10,
@@ -76,7 +77,7 @@ def run():
assert premium_entry['title'] == 'Têxtil Premium · 8 passadas', premium_entry
assert client.call('/session')['products'][PREMIUM]['enabled'] is False
premium_item = {**item_spec(PREMIUM, '1', 0, upload_bytes(
client, premium_sheet(), name='LOCAL-SITE-PREMIUM.png')),
client, premium_sheet(), name='LOCAL-SITE-PREMIUM.png'), aspect=3),
'quality_status': 'warning', 'quality_acknowledged': True}
refused = quote(client, premium_item, mail, expected=422)
assert refused['detail'] == 'Este produto não está à venda agora.', refused
@@ -188,7 +189,7 @@ def run():
manager.call(f'/operator/site/products/{UV}', {'enabled': True})
uid = upload_bytes(client, artwork(), name='LOCAL-SITE-ADMIN.png')
item = {**item_spec('uv', '1', 0, uid), 'quality_status': 'warning', 'quality_acknowledged': True}
item = {**item_spec('uv', '1', 0, uid, aspect=2), 'quality_status': 'warning', 'quality_acknowledged': True}
before = client.call('/session')['products'][UV]['unit_cents']
# Switched off: the Site sees it off and the server refuses a new quote.

View File

@@ -140,11 +140,15 @@ def review_photo(client, order_id):
wait_scan(client,uid,operator=True)
return client.call('/operator/orders/'+order_id+'/reviews',{'upload_id':uid},operator=True)
def item_spec(mode, metres, grade, uid):
def item_spec(mode, metres, grade, uid, aspect=None):
"""One file across the film, `metres` long. `aspect` (width / length) for
a real image: the piece then keeps the file's proportions, as the server
checks, inside the same billed length."""
film_width=27 if mode in ('uvfile','uv') else 57
length_cm=float(metres)*100
height_cm=float(metres)*100
length_cm=round(film_width/aspect,4) if aspect else height_cm
return {'mode':mode,'metres':str(metres),'grade':grade,'uploads':[uid],
'production':{'version':2,'film_width_cm':film_width,'height_cm':length_cm,
'production':{'version':2,'film_width_cm':film_width,'height_cm':height_cm,
'sources':[{'upload_id':uid,
'kind':'sheet' if mode in ('file','uvfile','premium') else 'artwork',
'width_cm':film_width,'length_cm':length_cm,'copies':1,
@@ -249,10 +253,11 @@ def run():
# A cart the Site priced is approved at once and can be paid straight away,
# at the server's own prices; no operator can then change it.
# The server works the grade out from the file: this PNG is 6059 px across
# 57 cm, 270 DPI, which is grade 100 under the 200 DPI clean threshold.
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
# 57 cm, 270 DPI, which is grade 100 under the 200 DPI clean threshold;
# 29232 px long, the 275 cm it is laid out at (the server checks it).
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(29232).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
graded=upload_bytes(client,png,name='arte-270dpi.png')
low_png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(3366).to_bytes(4,'big')+(2000).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
low_png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(3366).to_bytes(4,'big')+(16240).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
low=upload_bytes(client,low_png,name='arte-150dpi.png')
small={**draft,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,graded)]}
auto=client.call('/quotes',small)
@@ -283,7 +288,11 @@ def run():
assert mixed_item['stroke_choice']=='client_c3', mixed_item
# Loose art split by stroke (item 17): each sheet is an item, and the pair
# has one 1 m minimum, on its first sheet.
part=lambda metres,n,mode='avulsa':{**item_spec(mode,metres,90,graded),'split':{'group':'f0','part':n,'of':2}}
# Each sheet's own file, 6059 px across 57 cm, as long as the sheet.
header=lambda rows:b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+rows.to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
sheet_files={'0.3':upload_bytes(client,header(3189),name='folha-30.png'),
'0.15':upload_bytes(client,header(1594),name='folha-15.png')}
part=lambda metres,n,mode='avulsa':{**item_spec(mode,metres,90,sheet_files[metres]),'split':{'group':'f0','part':n,'of':2}}
split={**small,'request_key':str(uuid4()),'items':[part('0.3',1),part('0.15',2)]}
client.call('/quotes',{**split,'items':split['items'][:1]},expected=422)
client.call('/quotes',{**split,'items':[part('0.3',1),part('0.15',1)]},expected=422)

View File

@@ -158,5 +158,33 @@ class GradeCheckTests(unittest.TestCase):
self.assertIn('confirme a ressalva', issue(199.4))
class ProportionTests(unittest.TestCase):
"""A file laid out at proportions it does not have is refused before
payment, not found at print time (a 5 m sheet sent as 10 cm)."""
def cart(self, length, rotation=0, top=0, bottom=0, name='sheet.png'):
source = {'upload_id': name, 'kind': 'sheet', 'width_cm': 57, 'length_cm': length,
'rotation_degrees': rotation, 'trim_top_cm': top, 'trim_bottom_cm': bottom}
return [{'production': {'sources': [source]}}], {name: {'name': name}}
def test_the_files_own_proportions_pass(self):
files = FakeFiles({'sheet.png': encoded('PNG', (570, 1000)), 'turned.png': encoded('PNG', (1000, 570))})
for args in ((100,), (90, 0, 4, 6)):
items, rows = self.cart(*args)
self.assertIsNone(grade_check.proportion_issue(files, items, rows), args)
items, rows = self.cart(100, 90, name='turned.png')
self.assertIsNone(grade_check.proportion_issue(files, items, rows))
def test_other_proportions_are_refused(self):
files = FakeFiles({'sheet.png': encoded('PNG', (570, 50000))})
items, rows = self.cart(10)
self.assertIn('não são as proporções', grade_check.proportion_issue(files, items, rows))
def test_a_pdf_is_left_to_the_print_file(self):
files = FakeFiles({})
items, rows = self.cart(10, name='sheet.pdf')
self.assertIsNone(grade_check.proportion_issue(files, items, rows))
if __name__ == '__main__':
unittest.main()

View File

@@ -39,6 +39,36 @@ class SheetGapTests(unittest.TestCase):
self.assertEqual(str(caught.exception), SHEET_GAP_CHANGED)
def loose(xs_ys):
upload = str(uuid4())
placements = [{'source_index': 0, 'copy_index': i, 'x_cm': x, 'y_cm': y, 'width_cm': 20, 'length_cm': 10,
'rotation_degrees': 0, 'mirrored': False} for i, (x, y) in enumerate(xs_ys)]
height = max(y for _, y in xs_ys) + 10
return {'mode': 'avulsa', 'metres': str(height / 100), 'grade': 100, 'uploads': [upload],
'quality_status': 'ok', 'quality_acknowledged': False,
'production': {'version': 3, 'film_width_cm': 57, 'height_cm': height,
'sources': [{'upload_id': upload, 'kind': 'artwork', 'width_cm': 20, 'length_cm': 10,
'copies': len(xs_ys), 'measurement': 'file'}],
'placements': placements}}
class OverlapTests(unittest.TestCase):
"""Pieces stacked on each other bill less film than they print on: the
server refuses them, whatever the browser sent."""
def test_pieces_apart_or_touching_pass(self):
Item.model_validate(loose([(0, 0), (20.5, 0), (0, 10.5), (20.5, 10.5)]))
Item.model_validate(loose([(0, 0), (20, 0), (0, 10)]))
def test_pieces_on_each_other_are_refused(self):
for layout in ([(0, 0), (0, 0)], [(0, 0), (10, 5)], [(0, 0), (19.9, 9.9)],
[(0, 0)] * 100):
with self.assertRaises(ValueError) as caught:
Item.model_validate(loose(layout))
self.assertIn('uma sobre a outra', str(caught.exception))
with self.assertRaises(ValueError):
sheet(gap=-5)
class ClosePiecesTests(unittest.TestCase):
"""The Site's count of pieces under 5 mm travels with the item to the
Kanban card (Marcus, 2026-11-26, #81)."""

View File

@@ -46,5 +46,44 @@ class SheetTrimTests(unittest.TestCase):
Item.model_validate(sheet_item(top=-1))
class CutStripsAreEmptyTests(unittest.TestCase):
"""The print file cuts the strips only when they hold no ink: on a measure
the file does not bear out, artwork would leave the print unseen."""
def source(self, ink_row=None, alpha=255, fmt='PNG'):
import os
import tempfile
from PIL import Image
from app.printpng import Source
folder = tempfile.mkdtemp()
image = Image.new('RGBA', (60, 1200), (0, 0, 0, 0))
image.paste((200, 30, 30, 255), (0, 300, 60, 900)) # the art, rows 300-899
if ink_row is not None:
image.putpixel((30, ink_row), (0, 0, 0, alpha))
path = os.path.join(folder, 'folha.' + fmt.lower())
image.save(path, fmt)
return Source(path, 'folha.' + fmt.lower())
# 1200 rows for 120 cm: 20 cm (200 rows) cut at each end.
spec = {'length_cm': 80, 'trim_top_cm': 20, 'trim_bottom_cm': 20}
def test_clear_strips_are_cut(self):
for fmt in ('PNG', 'TIFF'):
source = self.source(fmt=fmt)
source.trim(self.spec)
self.assertEqual(source.cut, (200, 200), fmt)
# A residue the Site does not count as ink does not hold the cut either.
self.source(ink_row=50, alpha=10, fmt=fmt).trim(self.spec)
def test_ink_in_a_cut_strip_goes_to_hand_preparation(self):
from app.printfile import Unsupported
for fmt in ('PNG', 'TIFF'):
for row, where in ((150, 'do começo'), (1100, 'do fim')):
with self.assertRaises(Unsupported) as caught:
self.source(ink_row=row, fmt=fmt).trim(self.spec)
self.assertIn(where, str(caught.exception), (fmt, row))
if __name__ == '__main__':
unittest.main()