diff --git a/app/adapters.py b/app/adapters.py index 95c23c0..4770628 100644 --- a/app/adapters.py +++ b/app/adapters.py @@ -205,6 +205,8 @@ class ObjectStorage(Protocol): def store(self, key: str, path: str, content_type: str): ... def health(self): ... def discard(self, key: str, upload_id: str, complete: bool): ... + def discard_prefix(self, prefix: str): ... + def view(self, key: str, content_type: str, expires: int = 3600) -> str: ... class LocalS3Storage: def __init__(self): @@ -266,6 +268,25 @@ class LocalS3Storage: 'ResponseContentDisposition': "attachment; filename*=UTF-8''" + quote(name, safe=''), 'ResponseContentType': 'application/octet-stream'}, ExpiresIn=300) + def view(self, key, content_type, expires=3600): + """A link to show an object in the page, not download it: the Kanban's + viewer reads a film's pieces for as long as it is open (item 7).""" + return self.public.generate_presigned_url('get_object', Params={ + 'Bucket': self.bucket, 'Key': key, 'ResponseContentType': content_type}, ExpiresIn=expires) + + def discard_prefix(self, prefix): + """Delete every object under `prefix`, such as a print file's pieces.""" + token = None + while True: + page = self.client.list_objects_v2(Bucket=self.bucket, Prefix=prefix, + **({'ContinuationToken': token} if token else {})) + keys = [{'Key': item['Key']} for item in page.get('Contents', [])] + if keys: + self.client.delete_objects(Bucket=self.bucket, Delete={'Objects': keys, 'Quiet': True}) + if not page.get('IsTruncated'): + return + token = page['NextContinuationToken'] + def discard(self, key, upload_id, complete): if not complete: try: diff --git a/app/api/operator.py b/app/api/operator.py index 51d07b8..fa5a7b8 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -1399,6 +1399,47 @@ def print_ready(c, states, only=None, paid_after=None): return rows +@router.get('/api/operator/orders/{uid}/view') +def view_files(uid: UUID, user=Depends(operator)): + """What "Abrir e conferir" shows (item 7): each item's generated PNG, part + by part, with links to its pieces, then the customer's originals, which + have only their picture.""" + with db.connect() as c: + order = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() + if not order: + raise HTTPException(404, 'Pedido não encontrado.') + made = c.execute('''SELECT item_index, detail FROM dtf_local.print_files WHERE order_id=%s AND status='ready' + ORDER BY item_index''', (uid,)).fetchall() + parts = c.execute('''SELECT p.item_index, p.part, p.upload_id, u.name FROM dtf_local.print_parts p + JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE p.order_id=%s AND u.purged_at IS NULL + ORDER BY p.item_index, p.part''', (uid,)).fetchall() + pictured = {str(r['upload_id']) for r in c.execute( + 'SELECT upload_id FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s)', + ([UUID(u) for item in order['snapshot']['items'] for u in item['uploads']],)).fetchall()} + items = order['snapshot']['items'] + many = len(items) > 1 + files = [] + for row in made: + mine = [p for p in parts if p['item_index'] == row['item_index']] + details = {d.get('name'): d for d in row['detail'].get('parts') or []} + for part in mine: + tiles = (details.get(part['name']) or {}).get('tiles') + label = (f"Item {row['item_index'] + 1}" if many else 'Arquivo') + \ + (f" · parte {part['part']}/{len(mine)}" if len(mine) > 1 else '') + files.append({'name': part['name'], 'label': label, 'item': row['item_index'], + 'manifest': tiles and {**tiles, 'urls': [ + [storage.view(f"originals/tiles/{part['upload_id']}/{k}/{i}.png", 'image/png') + for i in range(level['strips'])] for k, level in enumerate(tiles['levels'])]}}) + for index, item in enumerate(items): + for n, upload in enumerate(item['uploads']): + files.append({'name': ('Original ' + str(n + 1)) if len(item['uploads']) > 1 else 'Original', + 'label': (f'Item {index + 1} · ' if many else '') + 'original' + + (f' {n + 1}' if len(item['uploads']) > 1 else ''), + 'item': index, 'manifest': None, + 'picture': f'/api/operator/uploads/{upload}/thumbnail' if upload in pictured else None}) + return {'files': files} + + @router.get('/api/operator/orders/{uid}/folder-files') def folder_files(uid: UUID, user=Depends(can('produce'))): """What each item's file is called in the order's stage folder, as the diff --git a/app/printjobs.py b/app/printjobs.py index 49e0cd5..7da457d 100644 --- a/app/printjobs.py +++ b/app/printjobs.py @@ -108,6 +108,12 @@ def render_one(storage): key = f'originals/{uid}' storage.store(key, path, 'image/png') stored.append((uid, name, os.path.getsize(path), key)) + store_tiles(storage, os.path.join(scratch, 'tiles', name), uid) + except Exception as exc: + # Storage failing is an attempt like any other, not a claim held for an hour. + logging.exception('Storing the print file failed') + finish(job, 'failed' if job['attempts'] + 1 >= MAX_ATTEMPTS else 'pending', {'error': type(exc).__name__}) + return True finally: shutil.rmtree(scratch, ignore_errors=True) for part, (uid, _, size, _) in zip(detail['parts'], stored): @@ -129,6 +135,16 @@ def render_one(storage): return True +def store_tiles(storage, folder, upload_id): + """A part's pieces for the Kanban's viewer (item 7), beside the files the + storage policy lets the service write: originals/tiles///.png.""" + if not os.path.isdir(folder): + return + for level in sorted(os.listdir(folder)): + for strip in sorted(os.listdir(os.path.join(folder, level))): + storage.store(f'originals/tiles/{upload_id}/{level}/{strip}', os.path.join(folder, level, strip), 'image/png') + + def file_prefix(number, item_index): """How an order's files are named: DTF-23-item-1, the code the Kanban copies, the footer prints and Tiny keeps (Dropstar, 2026-10-23).""" @@ -170,7 +186,7 @@ def produce(storage, job, item, uploads): storage.fetch(uploads[upload_id]['object_key'], local) files[index] = (local, uploads[upload_id]['name']) parts, detail = render(item, files, output, file_prefix(job['number'], job['item_index']), - footer=footer(job, item)) + footer=footer(job, item), tiles=True) except BaseException: shutil.rmtree(output, ignore_errors=True) raise diff --git a/app/printpng.py b/app/printpng.py index 6bd757d..2edaac3 100644 --- a/app/printpng.py +++ b/app/printpng.py @@ -36,6 +36,7 @@ from PIL import Image, ImageDraw, ImageFont, ImageOps from .core.models import PRODUCTION_VERSIONS from .printfile import (FOOTER_CM, FOOTER_LOGO, FOOTER_LOGO_CM, MAX_DECODED_PIXELS, SUPPORTED_FORMATS, Unsupported, check_layout) +from .printtiles import Pyramid DPI = 300 PX_PER_CM = DPI / 2.54 @@ -424,11 +425,13 @@ def footer_band(text, width): # ---- The file --------------------------------------------------------------- -def render(item, files, out_dir, prefix, footer=None, part_cm=None): +def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False): """Write the PNG part(s) of one approved order item into `out_dir`. - `files` maps each source index to (local path, original name). Returns - the parts, [(path, name)], and the evidence the Kanban shows. + `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///.png (app/printtiles.py). + Returns the parts, [(path, name)], and the evidence the Kanban shows. """ production = item['production'] if production.get('version') not in PRODUCTION_VERSIONS: @@ -442,13 +445,14 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None): for placement in production['placements']), key=lambda piece: piece.y) cuts = part_cuts(production, part_cm) count = len(cuts) - 1 - parts = [] + parts, manifests = [], [] for number in range(count): name = f'{prefix}.png' if count == 1 else f'{prefix}-p{number + 1}.png' path = os.path.join(out_dir, name) line = footer and (footer + (f' · Parte {number + 1}/{count}' if count > 1 else '')) with open(path, 'wb') as out: - write_part(out, pieces, px(cuts[number]), px(cuts[number + 1]), width, line) + manifests.append(write_part(out, pieces, px(cuts[number]), px(cuts[number + 1]), width, line, + tiles=os.path.join(out_dir, 'tiles', name) if tiles else None)) parts.append((path, name)) finally: for source in sources: @@ -457,7 +461,8 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None): 'film_width_cm': str(production['film_width_cm']), 'height_cm': str(production['height_cm']), 'width_px': width, - 'parts': [{'name': name, 'from_cm': str(cuts[i]), 'to_cm': str(cuts[i + 1])} + 'parts': [{'name': name, 'from_cm': str(cuts[i]), 'to_cm': str(cuts[i + 1]), + **({'tiles': manifests[i]} if manifests[i] else {})} for i, (_, name) in enumerate(parts)], 'footer': footer, 'billed_metres': str(item['billed_metres']), @@ -467,10 +472,20 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None): 'min_dpi': round(lowest) if lowest else None} -def write_part(out, pieces, top, bottom, width, footer=None): - """Rows [top, bottom) of the film, then the footer, as one PNG.""" +def write_part(out, pieces, top, bottom, width, footer=None, tiles=None): + """Rows [top, bottom) of the film, then the footer, as one PNG; with + `tiles`, a folder, also its pieces for the viewer. Returns their manifest.""" foot = footer_band(footer, width) if footer else None - writer = PngWriter(out, width, bottom - top + (foot.height if foot else 0)) + height = bottom - top + (foot.height if foot else 0) + writer = PngWriter(out, width, height) + pyramid = None + if tiles: + def emit(level, index, data): + folder = os.path.join(tiles, str(level)) + os.makedirs(folder, exist_ok=True) + with open(os.path.join(folder, f'{index}.png'), 'wb') as strip: + strip.write(data) + pyramid = Pyramid(width, height, emit) cache = {} for band_top in range(top, bottom, BAND_ROWS): band_bottom = min(bottom, band_top + BAND_ROWS) @@ -487,6 +502,8 @@ def write_part(out, pieces, top, bottom, width, footer=None): rows = rows.crop((left, 0, min(rows.width, width - piece.x), rows.height)) band.alpha_composite(rows, (max(0, piece.x), a - band_top)) writer.band(band) + if pyramid: + pyramid.band(band) # A piece the film has passed is done with: its pixels can go. for piece in pieces: if piece.y + piece.h <= band_bottom: @@ -496,4 +513,7 @@ def write_part(out, pieces, top, bottom, width, footer=None): del cache[key] if foot: writer.band(foot) + if pyramid: + pyramid.band(foot) writer.close() + return pyramid.close() if pyramid else None diff --git a/app/printtiles.py b/app/printtiles.py new file mode 100644 index 0000000..508c67e --- /dev/null +++ b/app/printtiles.py @@ -0,0 +1,102 @@ +"""The print file in pieces, for the Kanban's viewer (Dropstar's third round, item 7). + +"Abrir e conferir" shows the PNG at up to 100% (one file pixel, one screen +pixel). A 57 cm x 15 m film is 160 million pixels per 2 m: loaded whole it +freezes the designer's computer, so the viewer loads it in pieces, like a map. + +The pieces are strips of the film's whole width, STRIP_ROWS tall, at 100% +and at each halving down to a few strips for the whole film: level 0 is the +file itself, level k is 1/2^k of it. They are written while the PNG is, from +the same bands, so the file is never read back. +""" +import io +import math + +from PIL import Image + +STRIP_ROWS = 512 +# Levels stop when the whole film fits in about one screen. +SMALLEST_ROWS = 1024 + + +def levels_for(height): + """How many levels a film of `height` px gets: halving until it is short.""" + count = 1 + while math.ceil(height / 2 ** (count - 1)) > SMALLEST_ROWS and count < 12: + count += 1 + return count + + +class Pyramid: + """Fed the film's bands from the top, it hands each finished strip, as a + PNG, to `emit(level, index, png_bytes)`.""" + + def __init__(self, width, height, emit): + self.width, self.height, self.emit = width, height, emit + self.levels = levels_for(height) + self.pending = [None] * self.levels # rows of each level not yet a strip + self.count = [0] * self.levels # strips written per level + # A level's odd last row waits for its pair. + self.odd = [None] * self.levels + + def band(self, image): + self._feed(0, image) + + def _feed(self, level, image): + if level >= self.levels: + return + rows = self.pending[level] + if rows is None: + rows = image + else: + joined = Image.new('RGBA', (image.width, rows.height + image.height)) + joined.paste(rows, (0, 0)) + joined.paste(image, (0, rows.height)) + rows = joined + while rows.height >= STRIP_ROWS: + self._strip(level, rows.crop((0, 0, rows.width, STRIP_ROWS))) + rows = rows.crop((0, STRIP_ROWS, rows.width, rows.height)) if rows.height > STRIP_ROWS else None + if rows is None: + break + self.pending[level] = rows + # The next level down, from these rows, two by two. + self._halve(level, image) + + def _halve(self, level, image): + if level + 1 >= self.levels: + return + if self.odd[level] is not None: + joined = Image.new('RGBA', (image.width, image.height + 1)) + joined.paste(self.odd[level], (0, 0)) + joined.paste(image, (0, 1)) + image, self.odd[level] = joined, None + if image.height % 2: + self.odd[level] = image.crop((0, image.height - 1, image.width, image.height)) + image = image.crop((0, 0, image.width, image.height - 1)) + if image.height: + small = image.resize((max(1, math.ceil(image.width / 2)), image.height // 2), Image.BOX) + self._feed(level + 1, small) + + def _strip(self, level, image): + out = io.BytesIO() + image.save(out, 'PNG', compress_level=1) + self.emit(level, self.count[level], out.getvalue()) + self.count[level] += 1 + + def close(self): + """Flush what is left at each level, from the top level down.""" + for level in range(self.levels): + if self.odd[level] is not None and level + 1 < self.levels: + last = self.odd[level] + self.odd[level] = None + self._feed(level + 1, last.resize((max(1, math.ceil(last.width / 2)), 1), Image.BOX)) + if self.pending[level] is not None and self.pending[level].height: + self._strip(level, self.pending[level]) + self.pending[level] = None + return self.manifest() + + def manifest(self): + return {'width': self.width, 'height': self.height, 'strip_rows': STRIP_ROWS, + 'levels': [{'scale': 1 / 2 ** k, 'width': math.ceil(self.width / 2 ** k), + 'height': math.ceil(self.height / 2 ** k), 'strips': self.count[k]} + for k in range(self.levels)]} diff --git a/app/worker.py b/app/worker.py index e626946..e8698a3 100644 --- a/app/worker.py +++ b/app/worker.py @@ -39,6 +39,9 @@ def cleanup(): ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 50""").fetchall() for row in rows: storage.discard(row['object_key'],row['multipart_id'],row['complete']) + # A generated PNG's pieces for the Kanban's viewer go with it (item 7). + if row['name'].lower().endswith('.png'): + storage.discard_prefix(f"originals/tiles/{row['id']}/") c.execute('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s', (row['id'],)) c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (row['id'],)) c.execute('DELETE FROM dtf_local.sessions WHERE expires_at<=now()') diff --git a/tests/print_file_test.py b/tests/print_file_test.py index 98c91bd..00118e4 100644 --- a/tests/print_file_test.py +++ b/tests/print_file_test.py @@ -104,6 +104,17 @@ def run(): assert row['detail']['footer'].startswith('DROPSTAR · Pedido DTF-%d · Item 1/1 · ' % order['number']), row['detail'] print('PASS: paid order generated a 57 x 10 cm PNG print file with both copies and its footer') + # Item 7: "Abrir e conferir" gets the file in pieces, the first of which is + # the top of the film, then the original. + view = client.call('/operator/orders/' + order['id'] + '/view', operator=True)['files'] + assert [f['name'] for f in view] == ['DTF-%d-item-1.png' % order['number'], 'Original'], view + manifest = view[0]['manifest'] + assert (manifest['width'], manifest['height']) == film.size and manifest['levels'][0]['strips'] >= 1, manifest + with urlopen(manifest['urls'][0][0], timeout=30) as response: + strip = Image.open(io.BytesIO(response.read())) + assert strip.width == film.width and strip.getpixel((px(10), px(3))) == (220, 30, 60, 255) + print('PASS: the viewer gets the print file in pieces') + # The automatic folder, downloading on arrival, gets the generated file # before anyone approves it; at the queue only, it does not. oid = order['id'] diff --git a/tests/test_printpng.py b/tests/test_printpng.py index 66212b6..718d0cc 100644 --- a/tests/test_printpng.py +++ b/tests/test_printpng.py @@ -56,6 +56,32 @@ class PngStreamTests(unittest.TestCase): self.assertEqual(written.convert('RGBA').tobytes(), image.tobytes()) +class PyramidTests(unittest.TestCase): + def test_strips_rebuild_the_film_at_each_level(self): + from app import printtiles + image = pattern(90, 1300) + strips = {} + with mock.patch.object(printtiles, 'STRIP_ROWS', 64), mock.patch.object(printtiles, 'SMALLEST_ROWS', 200): + pyramid = printtiles.Pyramid(90, 1300, lambda level, index, data: strips.setdefault(level, []).append(data)) + for top in range(0, 1300, 100): + pyramid.band(image.crop((0, top, 90, min(1300, top + 100)))) + manifest = pyramid.close() + self.assertEqual(len(manifest['levels']), 4) # 1300, 650, 325, 163 rows + for level, info in enumerate(manifest['levels']): + pieces = [Image.open(io.BytesIO(data)) for data in strips[level]] + self.assertEqual(len(pieces), info['strips']) + self.assertEqual(sum(p.height for p in pieces), info['height'], level) + self.assertTrue(all(p.width == info['width'] for p in pieces), level) + # Level 0 is the film itself. + whole = Image.new('RGBA', (90, 1300)) + top = 0 + for data in strips[0]: + piece = Image.open(io.BytesIO(data)) + whole.paste(piece, (0, top)) + top += piece.height + self.assertEqual(whole.tobytes(), image.tobytes()) + + class PngRenderTests(unittest.TestCase): def setUp(self): self.dir = tempfile.TemporaryDirectory() @@ -120,6 +146,16 @@ class PngRenderTests(unittest.TestCase): self.assertEqual(second.convert('RGBA').getpixel((10, px(22) - px(21) + 5))[:3], RED) self.assertEqual([p['name'] for p in detail['parts']], ['DTF-7-item-1-p1.png', 'DTF-7-item-1-p2.png']) + def test_pieces_for_the_viewer_come_with_the_file(self): + art = quadrants(118, 59, alpha=True) + spec = item([placement(0, 0, 1, 0.5)], [source(1, 0.5)], 0.5) + parts, detail = render(spec, {0: (self.save(art, 'art.png'), 'art.png')}, + self.dir.name, 'DTF-7-item-1', footer='DROPSTAR · Pedido DTF-7', tiles=True) + tiles = detail['parts'][0]['tiles'] + self.assertEqual((tiles['width'], tiles['height']), Image.open(parts[0][0]).size) + first = Image.open(os.path.join(self.dir.name, 'tiles', 'DTF-7-item-1.png', '0', '0.png')) + self.assertEqual(first.crop((0, 0, 118, 59)).tobytes(), art.tobytes()) + def test_a_pdf_page_is_rendered_at_300_dpi(self): art = quadrants(118, 59) path = os.path.join(self.dir.name, 'sheet.pdf') diff --git a/web/kanban-viewer.js b/web/kanban-viewer.js new file mode 100644 index 0000000..97e5ade --- /dev/null +++ b/web/kanban-viewer.js @@ -0,0 +1,143 @@ +/* Kanban DTF — "Abrir e conferir" (Dropstar's third round, item 7). + + The print file in the browser, full screen: zoom up to 100% real (one file + pixel, one screen pixel), the position in cm, the order's files one after + the other without closing, and a background behind the transparency (light, + dark or checkered, remembered: white art vanishes on light, black on dark). + A 57 cm x 15 m film is loaded in pieces, like a map: strips of the film's + width at the zoom shown (app/printtiles.py), only those on screen. + + openViewer(files, {title, onClose}): files are [{name, label, manifest, + picture}], each with its strips' manifest (and their urls), or only a + picture when it has none. */ +(function(){ + const BG_KEY='dtf-viewer-bg'; + const BACKGROUNDS=[['light','Claro'],['dark','Escuro'],['check','Xadrez']]; + const PX_PER_CM=300/2.54; + // Decoded strips kept, the least recently drawn going first. + const KEEP=24; + const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!=null)n.textContent=text;if(cls)n.className=cls;return n;}; + const cm=px=>(px/PX_PER_CM).toFixed(1).replace('.',','); + let bg='check';try{bg=localStorage.getItem(BG_KEY)||'check';}catch(_){} + + window.openViewer=function(files,{title='',onClose}={}){ + const dlg=el('dialog',null,'viewer');dlg.setAttribute('aria-label','Abrir e conferir'); + const top=el('div',null,'vtop'), name=el('b',title,'vname'); + const tabs=el('div',null,'vtabs'), tools=el('div',null,'vtools'); + const where=el('span','','vwhere'); + const zoomOut=el('button','−','vbtn'), zoomText=el('span','','vzoom'), zoomIn=el('button','+','vbtn'); + const fit=el('button','Inteira','vbtn'), real=el('button','100%','vbtn'); + const bgBox=el('div',null,'vbg'); + const close=el('button','Fechar','vbtn pri'); + for(const b of [zoomOut,zoomIn,fit,real,close])b.type='button'; + zoomOut.setAttribute('aria-label','Diminuir');zoomIn.setAttribute('aria-label','Aumentar'); + for(const [key,label] of BACKGROUNDS){const b=el('button',label,'vbtn');b.type='button';b.dataset.bg=key; + b.onclick=()=>{bg=key;try{localStorage.setItem(BG_KEY,key);}catch(_){}paintBg();draw();};bgBox.append(b);} + tools.append(where,zoomOut,zoomText,zoomIn,fit,real,bgBox,close); + top.append(name,tabs,tools); + const stage=el('div',null,'vstage'), canvas=el('canvas'), note=el('p','','vnote'); + stage.append(canvas,note);dlg.append(top,stage);document.body.append(dlg); + + let file=null, zoom=1, x=0, y=0, cache=new Map(), loading=new Set(), picture=null, raf=0; + const paintBg=()=>{for(const b of bgBox.children)b.setAttribute('aria-pressed',String(b.dataset.bg===bg));stage.dataset.bg=bg;}; + const size=()=>file?.manifest?{w:file.manifest.width,h:file.manifest.height}:picture?{w:picture.width,h:picture.height}:{w:1,h:1}; + const fitZoom=()=>{const {w,h}=size();return Math.min(stage.clientWidth/w,stage.clientHeight/h,1);}; + const clamp=()=>{const {w,h}=size(), vw=stage.clientWidth/zoom, vh=stage.clientHeight/zoom; + x=w<=vw?(w-vw)/2:Math.max(0,Math.min(w-vw,x));y=h<=vh?(h-vh)/2:Math.max(0,Math.min(h-vh,y));}; + function setZoom(z,cx=stage.clientWidth/2,cy=stage.clientHeight/2){ + const fx=x+cx/zoom, fy=y+cy/zoom; + zoom=Math.max(Math.min(fitZoom(),0.02),Math.min(4,z)); + x=fx-cx/zoom;y=fy-cy/zoom;clamp(); + zoomText.textContent=Math.round(zoom*100)+'%';draw(); + } + // The level whose detail is at least what the zoom shows. + function level(){ + const levels=file.manifest.levels;let k=0; + while(k+1=zoom)k++; + return k; + } + async function strip(k,i){ + const key=k+':'+i; + if(cache.has(key)){const v=cache.get(key);cache.delete(key);cache.set(key,v);return v;} + if(loading.has(key))return null; + loading.add(key); + try{ + const url=file.manifest.urls[k][i]; + const res=await fetch(url,{referrerPolicy:'no-referrer'}); + if(!res.ok)throw new Error('erro '+res.status); + const bmp=await createImageBitmap(await res.blob()); + if(closed||file?.manifest?.urls[k]?.[i]!==url){bmp.close();return null;} + cache.set(key,bmp); + while(cache.size>KEEP){const [old,v]=cache.entries().next().value;v.close?.();cache.delete(old);} + draw(); + }catch(e){note.textContent='Não foi possível carregar um pedaço do arquivo ('+e.message+').';} + finally{loading.delete(key);} + return null; + } + function draw(){cancelAnimationFrame(raf);raf=requestAnimationFrame(paint);} + function paint(){ + if(closed)return; + const ratio=devicePixelRatio||1, W=stage.clientWidth, H=stage.clientHeight; + canvas.width=Math.round(W*ratio);canvas.height=Math.round(H*ratio);canvas.style.width=W+'px';canvas.style.height=H+'px'; + const g=canvas.getContext('2d');g.setTransform(ratio,0,0,ratio,0,0);g.clearRect(0,0,W,H); + g.imageSmoothingEnabled=zoom<1; + if(picture){g.drawImage(picture,-x*zoom,-y*zoom,picture.width*zoom,picture.height*zoom);return;} + if(!file?.manifest)return; + const k=level(), L=file.manifest.levels[k], s=L.scale, rows=file.manifest.strip_rows; + const first=Math.max(0,Math.floor(y*s/rows)), last=Math.min(L.strips-1,Math.floor((y+H/zoom)*s/rows)); + for(let i=first;i<=last;i++){ + let bmp=cache.get(k+':'+i); + if(!bmp){strip(k,i); + // Meanwhile, a coarser level that is already here. + for(let c=k+1;cv.close?.());cache=new Map();note.textContent=''; + for(const b of tabs.children)b.setAttribute('aria-pressed',String(b===tab)); + name.textContent=title?title+' · '+f.name:f.name; + if(!f.manifest){ + note.textContent=f.picture?'Este arquivo não tem os pedaços para 100%: veja a prévia ou baixe o arquivo.':'Este arquivo não tem prévia: baixe para conferir.'; + if(f.picture){try{const r=await fetch(f.picture);picture=await createImageBitmap(await r.blob());}catch(_){}} + } + zoom=fitZoom();x=0;y=0;clamp();zoomText.textContent=Math.round(zoom*100)+'%';draw(); + } + files.forEach((f,i)=>{const b=el('button',f.label||f.name,'vtab');b.type='button';b.onclick=()=>show(f,b);tabs.append(b);}); + tabs.hidden=files.length<2; + + // Drag to move, wheel or pinch to zoom, keys for the rest. + let drag=null; + stage.onpointerdown=e=>{drag={x:e.clientX,y:e.clientY,ox:x,oy:y};stage.setPointerCapture(e.pointerId);}; + stage.onpointermove=e=>{ + const r=stage.getBoundingClientRect(), fx=x+(e.clientX-r.left)/zoom, fy=y+(e.clientY-r.top)/zoom; + where.textContent=cm(Math.max(0,fx))+' × '+cm(Math.max(0,fy))+' cm'; + if(!drag)return;x=drag.ox-(e.clientX-drag.x)/zoom;y=drag.oy-(e.clientY-drag.y)/zoom;clamp();draw();}; + stage.onpointerup=()=>{drag=null;}; + // As on a map: the wheel zooms where the pointer is. + stage.onwheel=e=>{e.preventDefault();const r=stage.getBoundingClientRect(); + setZoom(zoom*Math.exp(-e.deltaY*(e.deltaMode?40:1)/400),e.clientX-r.left,e.clientY-r.top);}; + zoomIn.onclick=()=>setZoom(zoom*1.5);zoomOut.onclick=()=>setZoom(zoom/1.5); + fit.onclick=()=>setZoom(fitZoom());real.onclick=()=>setZoom(1); + dlg.onkeydown=e=>{if(e.key==='+'||e.key==='=')setZoom(zoom*1.5);else if(e.key==='-')setZoom(zoom/1.5); + else if(e.key==='0')setZoom(fitZoom());else if(e.key==='1')setZoom(1);}; + const resize=()=>{clamp();draw();};addEventListener('resize',resize); + // Closed by its button or Escape, and by the dialog's own close as well, + // once: some browsers never send that event. + let closed=false; + const finish=()=>{if(closed)return;closed=true;cancelAnimationFrame(raf);removeEventListener('resize',resize); + const strips=[...cache.values()];cache=new Map();strips.forEach(v=>v.close?.()); + if(dlg.open)dlg.close();dlg.remove();onClose?.();}; + close.onclick=finish; + dlg.addEventListener('cancel',e=>{e.preventDefault();finish();}); + dlg.onclose=finish; + paintBg();dlg.showModal(); + if(files.length)show(files[0],tabs.children[0]); + return {close:finish}; + }; +})(); diff --git a/web/kanban.css b/web/kanban.css index c54ba0a..e03bd8f 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -1118,3 +1118,33 @@ select.inp{appearance:none;-webkit-appearance:none;padding-right:32px;background } @keyframes pageIn{from{transform:translateX(30px);opacity:.3}} @keyframes sheetUp{from{transform:translateY(40%);opacity:.3}} + +/* "Abrir e conferir" (item 7): the print file full screen, in pieces. */ +dialog.viewer{position:fixed;inset:0;width:100vw;height:100vh;max-width:none;max-height:none;margin:0;padding:0;border:0; + background:var(--bg);color:var(--tx);display:flex;flex-direction:column} +dialog.viewer:not([open]){display:none} +dialog.viewer::backdrop{background:var(--scrim)} +.vtop{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:10px 14px;border-bottom:1px solid var(--ln);background:var(--top)} +.vname{font-size:14.5px;font-weight:700;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:32ch} +.vtabs{display:flex;gap:6px;overflow-x:auto;flex:1;min-width:0} +.vtools{display:flex;align-items:center;gap:6px;margin-left:auto;flex-wrap:wrap} +.vbtn,.vtab{height:32px;padding:0 11px;border-radius:8px;border:1px solid var(--ln2);background:var(--sf);color:var(--tx); + font-size:13px;font-weight:600;white-space:nowrap;cursor:pointer} +.vbtn.pri{background:var(--acc);border-color:var(--acc);color:var(--onacc)} +.vtab[aria-pressed="true"],.vbg .vbtn[aria-pressed="true"]{background:var(--ink);border-color:var(--ink);color:var(--onink)} +.vbg{display:flex;gap:4px} +.vzoom{min-width:48px;text-align:center;font-family:var(--code);font-size:12.5px;color:var(--tx2)} +.vwhere{min-width:120px;font-family:var(--code);font-size:12.5px;color:var(--tx2)} +.vstage{position:relative;flex:1;min-height:0;overflow:hidden;cursor:grab;touch-action:none} +.vstage:active{cursor:grabbing} +.vstage canvas{position:absolute;inset:0;display:block} +.vstage[data-bg="light"]{background:#FFFFFF} +.vstage[data-bg="dark"]{background:#0A0A0A} +.vstage[data-bg="check"]{background-color:#FFFFFF; + background-image:linear-gradient(45deg,#D9D9D9 25%,transparent 25%),linear-gradient(-45deg,#D9D9D9 25%,transparent 25%), + linear-gradient(45deg,transparent 75%,#D9D9D9 75%),linear-gradient(-45deg,transparent 75%,#D9D9D9 75%); + background-size:20px 20px;background-position:0 0,0 10px,10px -10px,-10px 0} +.vnote{position:absolute;left:50%;bottom:16px;transform:translateX(-50%);margin:0;padding:8px 12px;border-radius:9px; + background:var(--sf);border:1px solid var(--ln2);font-size:13px;color:var(--tx2);max-width:min(560px,calc(100% - 32px))} +.vnote:empty{display:none} +@media(max-width:700px){.vname{max-width:100%;flex-basis:100%}.vwhere{display:none}} diff --git a/web/kanban.html b/web/kanban.html index 8bc3cf0..4e21f74 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -175,4 +175,4 @@
- + diff --git a/web/kanban.js b/web/kanban.js index 0fac83b..c0e81d8 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -1520,6 +1520,8 @@ function nextBox(order){ if(!may('produce')){note('O Designer confere e aprova o arquivo final.');body.push(contractionList(order));} else{ const lead=st==='rec'||fixed, a=approveParts(order,lead); + // Item 7: open the file, then say whether it is OK. + if(st==='rec'){a.approve.classList.remove('pri');main.push(checkButton(order,'btn pri lg'));} if(lead){if(a.files)body.push(a.files);note(a.text);body.push(contractionList(order));main.push(a.approve,...a.extra);} else more.push(a.approve,...a.extra); } @@ -1711,6 +1713,52 @@ function finalDialog(order,ready,{replace=false}={}){ // where the folder is, to copy the whole path. const TREAT_NOTE='Arte tratada'; const FOLDER_PATH_KEY='folder-path'; +// ---- Abrir e conferir (item 7) ---------------------------------------------- + +// The print file full screen, in pieces (web/kanban-viewer.js); closed in +// Arte recebida, it asks whether the art is OK. +function checkButton(order,className='btn'){ + const b=button('Abrir e conferir',()=>openCheck(order),className);b.prepend(svgIcon(IC.eye||IC.file,'i m'));return b; +} +async function openCheck(order){ + const {files}=await api('/orders/'+order.id+'/view'); + if(!files.length){say('Ainda não há arquivo para abrir.',true);return;} + openViewer(files,{title:'#'+order.number,onClose:()=>{ + const now=board.orders.find(o=>o.id===order.id)||order; + if(now.state==='rec'&&!now.cancelled_at&&may('produce')&&mayMove('rec','tra'))isOk(now);}}); +} +// "Está OK?" (Dropstar, 2026-10-29): the class of each item, prefilled with +// the measure, and the art either goes on to Arte conferida, its final +// approved and its class kept, or is treated (item 8). +function isOk(order){ + const items=order.snapshot.items, ready=readyFinals(order); + const selects=items.map((item,index)=>{ + const select=node('select');select.required=true; + const none=node('option','Escolha');none.value='';none.disabled=true;select.append(none); + for(const c of ['C1','C2','C3']){const o=node('option',c+', '+CLASS_NOTE[c]);o.value=c;select.append(o);} + select.value=contractionOf(order,index)||'';return select;}); + const fields=selects.map((select,index)=>{const item=items[index]; + return field(items.length>1?'Item '+(index+1)+', contração':'Contração',select, + item.stroke_class?'O site mediu '+item.stroke_class+', traço de '+item.stroke_px+' px':'O site não mediu esta arte');}); + const missing=!finalDone(order)&&!ready.every(Boolean); + const treat=button('Tratar a arte',()=>{m.close();treatDialog(order);},'btn'); + const m=formDialog('Está OK?',{host:$('drawer'),fields,left:[treat],label:'Mover para Arte conferida', + text:missing?'Falta o arquivo final de um item: trate a arte e envie o arquivo preparado.' + :'A arte chegou boa? Confira a contração e mova para Arte conferida.', + onsave:async()=>{ + if(missing)throw new Error('Falta o arquivo final de um item.'); + for(const [index,select] of selects.entries()) + if(select.value!==contractionOf(order,index)) + await api('/orders/'+order.id+'/contraction',{item_index:index,value:select.value}); + if(!finalDone(order)) + await api('/orders/'+order.id+'/final-files',{version:order.version, + files:ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))),note:'Conferido em Abrir e conferir'}); + await load(); + await move(board.orders.find(o=>o.id===order.id)||order,'tra'); + say('Pedido #'+order.number+' em Arte conferida.'); + }}); + if(missing)m.box.querySelector('button.pri')?.setAttribute('disabled',''); +} function treatDialog(order){ const base=node('input');base.placeholder='Ex.: D:\\'+(FOLDER.handle?.name||'Pedidos'); const names={}; @@ -1868,6 +1916,7 @@ function itemCard(order,item,index){ } item.uploads.forEach((uid,i)=>links.append(dl_(item.uploads.length>1?'Original '+(i+1):'Arquivo original',uid))); if(spec?.placements){const m=button('Manifesto',()=>manifest(spec,contractionRecord(item,order.contraction?.[index])),'btn');m.prepend(svgIcon(IC.file,'i m'));links.append(m);} + if(row?.status==='ready')links.prepend(checkButton(order)); if(may('produce')&&!fix&&['rec','tra'].includes(order.state)&&(!row||row.status==='manual'||row.status==='failed')){ const again=button('Gerar de novo',async()=>{await api('/orders/'+order.id+'/print-files',{});await load();},'btn');again.prepend(svgIcon(IC.refresh,'i m'));links.append(again);} info.append(links);