diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 55f68f0..ad66b1f 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -73,7 +73,7 @@ jobs: # one a developer exercises on localhost. - name: API and workflow regressions run: | - for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test; do + for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test stamps_test; do echo "--- $suite" $COMPOSE exec -T \ -e SITE_BASE_URL=http://site \ diff --git a/app/api/stamps.py b/app/api/stamps.py new file mode 100644 index 0000000..9a45ba2 --- /dev/null +++ b/app/api/stamps.py @@ -0,0 +1,25 @@ +"""The montador's stamp sizes (Fase 2, front 7): Gestão edits the table.""" +from fastapi import APIRouter, Depends + +from ..core import db +from ..core.auth import audit, can +from ..core.models import StampSizeTable + +router = APIRouter() + + +@router.get('/api/operator/stamp-sizes') +def stamp_sizes(user=Depends(can('assemble'))): + with db.connect() as c: + rows = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall() + return {'sizes': rows} + + +@router.post('/api/operator/stamp-sizes') +def save_stamp_sizes(body: StampSizeTable, user=Depends(can('manage'))): + with db.connect() as c: + c.execute('DELETE FROM dtf_local.stamp_sizes') + c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm,updated_by) VALUES(%s,%s,%s)', + [(row.letter, row.width_cm, user) for row in body.sizes]) + audit('stamp_sizes_changed', operator=user, sizes=len(body.sizes)) + return {'ok': True} diff --git a/app/api/users.py b/app/api/users.py index 16eb4d0..e0c3b93 100644 --- a/app/api/users.py +++ b/app/api/users.py @@ -26,7 +26,7 @@ class UserIn(StrictModel): # The profiles an administrator may give; superadmin only comes from the console. name: str = Field(min_length=1, max_length=80) email: str = Field(min_length=3, max_length=254) - role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro'] + role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao'] password: str | None = Field(default=None, min_length=8, max_length=128) active: bool = True # No longer used: an operator's machine is the one chosen after signing in diff --git a/app/app.py b/app/app.py index cbdd6cb..9e4d4df 100644 --- a/app/app.py +++ b/app/app.py @@ -13,7 +13,7 @@ from starlette.middleware.trustedhost import TrustedHostMiddleware from .core import db from .core.auth import audit, client_ip from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage -from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_videos, uploads, users +from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_videos, stamps, uploads, users @asynccontextmanager @@ -45,5 +45,5 @@ async def safe_headers(request, call_next): # Order is not significant: no two routers declare the same path. -for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, reviews, machine_log): +for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, reviews, machine_log, stamps): app.include_router(module.router) diff --git a/app/core/auth.py b/app/core/auth.py index 032b297..bf54c05 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -125,7 +125,7 @@ def login_failed(email): # backup, the Tiny log): the others see there only what is on and off. # The designer approves and refuses artwork and asks for corrections, on every # order whatever its machine. Which cards each profile moves is MOVES. -ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro') +ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao') CAPABILITIES = { 'view': set(ROLES), 'produce': {'superadmin', 'admin', 'gestao', 'designer'}, @@ -155,6 +155,9 @@ CAPABILITIES = { # The photo or video of the printed sheet in Revisão (Fase 2, front 2): who # releases to Finalizado, and Gestão, which may stand in for them. 'inspect': {'superadmin', 'admin', 'gestao', 'revisor'}, + # Montar folha (Fase 2, front 7): the new Expedição profile and the seller, + # who gets this one action although otherwise view-only (D-30). + 'assemble': {'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'}, } # Who moves which card (Dropstar's flow, 2026-10-23, and their rules of diff --git a/app/core/models.py b/app/core/models.py index b213c39..46ca822 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -444,3 +444,19 @@ class ArtworkSubmission(StrictModel): version: int = Field(ge=0, strict=True) files: list[FileReference] = Field(min_length=1, max_length=60) note: str = Field(min_length=1, max_length=1000) + +class StampSize(StrictModel): + """One row of the montador's size table (Fase 2, front 7).""" + letter: str = Field(pattern=r'^[A-Z]{1,2}$') + width_cm: Decimal = Field(gt=0, le=56, decimal_places=2) + +class StampSizeTable(StrictModel): + """The whole table, replaced in one go by Gestão.""" + sizes: list[StampSize] = Field(min_length=1, max_length=26) + + @model_validator(mode='after') + def letters_unique(self): + letters = [row.letter for row in self.sizes] + if len(letters) != len(set(letters)): + raise ValueError('Cada tamanho tem uma letra própria.') + return self diff --git a/app/schema.sql b/app/schema.sql index 7844c25..e381784 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -284,11 +284,11 @@ CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names ( -- from the console); administrators manage users and machines; gestão runs -- the business; designers approve artwork; operadores print; revisores check -- the printed sheet and are the only ones to release it to Finalizado; --- vendedores only read. +-- vendedores only read; expedição assembles sheets in the Kanban's montador. ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin'; ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role; ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role - CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro')); + CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao')); -- Print machines and which products each prints. An order gets its machine -- when someone pulls it into Imprimindo; no machine is assigned at payment. -- limit_metres remains the load shown for a machine. @@ -581,3 +581,13 @@ CREATE TABLE IF NOT EXISTS dtf_local.machine_snoozes ( snoozed_by text NOT NULL, snoozed_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(machine_id, alert, cycle_from) ); + +-- Front 7a: the stamp sizes of the Kanban's montador; Gestão edits them. +CREATE TABLE IF NOT EXISTS dtf_local.stamp_sizes ( + letter text PRIMARY KEY CHECK (letter ~ '^[A-Z]{1,2}$'), + width_cm numeric(5,2) NOT NULL CHECK (width_cm > 0 AND width_cm <= 56), + updated_by text NOT NULL DEFAULT 'sistema', + updated_at timestamptz NOT NULL DEFAULT now() +); +INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES ('A',20),('B',24),('C',27),('D',30) +ON CONFLICT (letter) DO NOTHING; diff --git a/tests/stamps_test.py b/tests/stamps_test.py new file mode 100644 index 0000000..61277ed --- /dev/null +++ b/tests/stamps_test.py @@ -0,0 +1,71 @@ +"""The montador's stamp sizes: Expedição reads them and Gestão edits them. + +Run against the local stack: python -m tests.stamps_test +""" +import secrets + +from app.core import db +from tests.smoke_test import Client + +PASSWORD = 'senha-de-teste-123' + + +def signed_in(email, password=PASSWORD): + client = Client() + client.call('/session') + client.call('/operator/login', {'email': email, 'password': password}) + return client + + +def run(): + tag = secrets.token_hex(3) + su = Client() + su.call('/session') + assert su.call('/operator/me', operator=True)['role'] == 'superadmin' + with db.connect() as c: + original = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall() + emails = {role: f'{role}-{tag}@example.test' for role in ('expedicao', 'designer', 'gestao')} + table = [(row['letter'], float(row['width_cm'])) for row in original] + try: + for role, email in emails.items(): + su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role, + 'password': PASSWORD}, operator=True) + # The new profile creates through the users API and reads the table. + shipping = signed_in(emails['expedicao']) + me = shipping.call('/operator/me') + assert me['role'] == 'expedicao' and me['can'] == ['assemble', 'view'], me + read = shipping.call('/operator/stamp-sizes')['sizes'] + assert [(row['letter'], float(row['width_cm'])) for row in read] == table, read + # The designer does not assemble: no reading the table. + designer = signed_in(emails['designer']) + designer.call('/operator/stamp-sizes', expected=403) + # Gestão replaces the whole table in one go and reads it back, by width. + manager = signed_in(emails['gestao']) + manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'D', 'width_cm': 30}, + {'letter': 'A', 'width_cm': 20}, + {'letter': 'B', 'width_cm': 24.5}]}) + read = manager.call('/operator/stamp-sizes')['sizes'] + assert [(row['letter'], float(row['width_cm'])) for row in read] == [('A', 20), ('B', 24.5), ('D', 30)], read + # A repeated letter and a width out of range are refused. + manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 20}, + {'letter': 'A', 'width_cm': 24}]}, + expected=422) + manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 0}]}, + expected=422) + manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 57}]}, + expected=422) + # Expedição only reads them; saving stays with Gestão. + shipping.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 20}]}, + expected=403) + read = manager.call('/operator/stamp-sizes')['sizes'] + assert [(row['letter'], float(row['width_cm'])) for row in read] == [('A', 20), ('B', 24.5), ('D', 30)], read + print('PASS: Expedição reads the montador size table; Gestão replaces it; invalid rows are refused') + finally: + with db.connect() as c: + c.execute('DELETE FROM dtf_local.stamp_sizes') + c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES(%s,%s)', table) + c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',)) + + +if __name__ == '__main__': + run() diff --git a/tests/test_moves.py b/tests/test_moves.py index 4762216..e0eea62 100644 --- a/tests/test_moves.py +++ b/tests/test_moves.py @@ -1,7 +1,7 @@ """Who moves which card on the Kanban: Dropstar's flow of 2026-10-23.""" import unittest -from app.core.auth import ROLES, may_move, may_reorder +from app.core.auth import CAPABILITIES, ROLES, may_move, may_reorder from app.runtime import BACK, STATES, TRANSITIONS @@ -41,6 +41,17 @@ class MovesTest(unittest.TestCase): self.assertTrue(may_move('gestao', 'fin', 'rev', back=True)) self.assertFalse(may_move('vendedor', 'tra', 'rec', back=True)) + def test_expedicao_moves_nothing(self): + # The new shipping profile assembles sheets (Fase 2, front 7) and reads + # the board; it moves no card and orders no column. + self.assertIn('expedicao', ROLES) + self.assertEqual(moves('expedicao'), set()) + self.assertEqual([s for s in STATES if may_reorder('expedicao', s)], []) + + def test_the_montador_is_open_to_exactly_five_profiles(self): + self.assertEqual(CAPABILITIES['assemble'], + {'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'}) + def test_a_column_is_ordered_by_whoever_takes_its_cards_forward(self): self.assertEqual([s for s in STATES if may_reorder('operador', s)], ['tra', 'imp']) self.assertEqual([s for s in STATES if may_reorder('designer', s)], ['rec', 'cor']) diff --git a/tests/users_test.py b/tests/users_test.py index 5ee59a6..dfc6ed2 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -174,7 +174,7 @@ def run(): seller.call(f'/operator/orders/{textil_o}/contact', {'waiting': True, 'note': 'Ligar'}, expected=403) # The seller only views the board (D-30): no order registered by hand either. # The seller only views, but answers a proof card (Dropstar, 2026-11-03). - assert seller.call('/operator/me')['can'] == ['proof', 'view'] + assert seller.call('/operator/me')['can'] == ['assemble', 'proof', 'view'] seller.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=403) # Financeiro (Dropstar, 2026-10-30): the board, Pagamentos, Números and # Cotações, and cancels an order with its reason; moves nothing. diff --git a/web/kanban-montador.js b/web/kanban-montador.js new file mode 100644 index 0000000..d8996cc --- /dev/null +++ b/web/kanban-montador.js @@ -0,0 +1,246 @@ +/* Kanban DTF: "Montar folha" (Fase 2, front 7). The stamps are the PNG files + in Estampas/ inside the folder chosen in Integrações; the sizes are the + table Gestão edits. Slice 1: the list and the estimate; Montar is slice 2. + Uses the globals of kanban.js, loaded first. */ +const MONTAR_CODE=/^[A-Za-z0-9_-]{1,40}$/; +// The Site's ruler (web/site-config.js): the same numbers, copied there too. +const MONTAR_DPI_REFUSE=96, MONTAR_DPI_WARN=200; +const MONTAR_FILM_CM=57, MONTAR_GAP_CM=0.5; +const MONTAR={sizes:[],lines:[],seq:0,preview:null,timer:null,dirty:false,token:0}; + +const montarFolderReady=()=>!!FOLDER.handle&&!!FOLDER.granted; +const montarDpi=found=>found.width/(found.widthCm/2.54); +const montarHeight=found=>found.widthCm*(found.height/found.width); +const montarSelected=()=>MONTAR.sizes.find(size=>size.letter===$('montar-size').value)||null; + +// Without the folder there is no Estampas/ to read: only the size table works. +function montarPaintFolder(){ + const ok=montarFolderReady(); + $('montar-nofolder').hidden=ok; + $('montar-setup').querySelector('.montar-add').hidden=!ok; + $('montar-preview').hidden=!ok; + $('montar-sheet').hidden=!ok; + $('montar-folder').textContent=ok?'Pasta “'+FOLDER.handle.name+'” · Estampas/':''; + if(!ok){montarDropPreview();$('montar-preview').replaceChildren();} +} +function montarFolderError(error){ + if(error&&['NotAllowedError','SecurityError'].includes(error.name)){ + say('Para ler as estampas, escolha a pasta dos pedidos em Integrações neste computador.',true); + return true; + } + return false; +} + +// -.png wins over .png; only PNG. +async function montarRead(code,size){ + const dir=await FOLDER.handle.getDirectoryHandle('Estampas',{create:true}); + for(const name of [code+'-'+size.letter+'.png',code+'.png']){ + let handle; + try{handle=await dir.getFileHandle(name);} + catch(e){if(e.name==='NotFoundError')continue;throw e;} + const file=await handle.getFile(),url=URL.createObjectURL(file); + try{const dim=await montarPicture(url);return {code,letter:size.letter,widthCm:Number(size.width_cm),file,name,url,width:dim.width,height:dim.height};} + catch(e){URL.revokeObjectURL(url);throw e;} + } + return null; +} +function montarPicture(url){ + return new Promise((ok,fail)=>{ + const img=new Image(); + img.onload=()=>ok({width:img.naturalWidth,height:img.naturalHeight}); + img.onerror=()=>fail(new Error('A estampa não pôde ser lida.')); + img.src=url; + }); +} + +function montarDropPreview(){ + if(MONTAR.preview)URL.revokeObjectURL(MONTAR.preview.url); + MONTAR.preview=null; +} +function montarPaintPreview(found){ + montarDropPreview(); + MONTAR.preview=found; + const words=node('span',undefined,'montar-stampinfo'); + words.append(node('b',found.code), + node('span',cm(found.widthCm)+' cm de largura · '+cm(montarHeight(found))+' cm de altura · '+Math.floor(montarDpi(found))+' DPI')); + const img=node('img');img.src=found.url;img.alt='Estampa '+found.code; + const wrap=node('div',undefined,'montar-stamp');wrap.append(img,words); + $('montar-preview').replaceChildren(wrap); +} +function montarPaintNotFound(){ + montarDropPreview(); + $('montar-preview').replaceChildren(node('p','Código não existe em Estampas/.','montar-missing')); +} +function montarPaintHint(){ + montarDropPreview(); + $('montar-preview').replaceChildren(node('p','Digite o código e escolha o tamanho para ver a estampa.','montar-hint')); +} + +async function montarPreview(){ + const token=++MONTAR.token; + const code=$('montar-code').value.trim(),size=montarSelected(); + if(!montarFolderReady())return; + if(!code){montarPaintHint();return;} + if(!MONTAR_CODE.test(code)||!size){montarDropPreview();$('montar-preview').replaceChildren();return;} + let found; + try{found=await montarRead(code,size);} + catch(e){if(token===MONTAR.token&&!montarFolderError(e))say(e.message,true);return;} + if(token!==MONTAR.token){if(found)URL.revokeObjectURL(found.url);return;} + if(found)montarPaintPreview(found);else montarPaintNotFound(); +} +function montarQueuePreview(){ + clearTimeout(MONTAR.timer); + MONTAR.timer=setTimeout(()=>montarPreview().catch(e=>say(e.message,true)),250); +} + +function montarEstimate(){ + if(!MONTAR.lines.length)return 0; + let total=0; + for(const line of MONTAR.lines){ + const perRow=Math.max(1,Math.floor((MONTAR_FILM_CM-MONTAR_GAP_CM)/(line.widthCm+MONTAR_GAP_CM))); + const rows=Math.ceil(line.qty/perRow); + total+=rows*(line.heightCm+MONTAR_GAP_CM); + } + return (MONTAR_GAP_CM+total)/100; +} +function montarPaintTotals(){ + $('montar-total').textContent='Estimativa: '+metres(montarEstimate()); + $('montar-count').textContent=MONTAR.lines.length?plural(MONTAR.lines.length,'estampa','estampas'):''; + $('montar-clear').disabled=!MONTAR.lines.length; +} +function montarLine(line){ + const row=node('div',undefined,'montar-line'); + const img=node('img',undefined,'montar-thumb');img.src=line.url;img.alt=''; + const words=node('span',undefined,'montar-linemeta'); + words.append(node('b',line.code),node('span',line.letter+' · '+cm(line.widthCm)+' cm')); + const qty=node('input',undefined,'montar-qty');qty.type='number';qty.min='1';qty.max='9999';qty.step='1'; + qty.value=String(line.qty);qty.setAttribute('aria-label','Quantidade de '+line.code+' '+line.letter); + qty.onchange=()=>{ + const value=Math.round(Number(qty.value)); + if(!Number.isInteger(value)||value<1||value>9999){qty.value=String(line.qty);return;} + line.qty=value;qty.value=String(value);montarPaintTotals(); + }; + const dpi=node('span',undefined,'montar-dpi'); + if(line.dpimontarRemoveLine(line))); + return row; +} +function montarPaintLines(){ + const box=$('montar-lines'); + box.replaceChildren(...(MONTAR.lines.length?MONTAR.lines.map(montarLine) + :[emptyState(IC.box,'Nenhuma estampa na folha','Digite o código, escolha o tamanho e Adicionar.')])); + montarPaintTotals(); +} +function montarRemoveLine(line){ + URL.revokeObjectURL(line.url); + MONTAR.lines=MONTAR.lines.filter(other=>other!==line); + montarPaintLines(); +} +function montarClear(){ + for(const line of MONTAR.lines)URL.revokeObjectURL(line.url); + MONTAR.lines=[]; + montarPaintLines(); +} + +async function montarAdd(){ + const code=$('montar-code').value.trim(),size=montarSelected(); + if(!MONTAR_CODE.test(code))return say('Código inválido: use letras, números, hífen ou sublinhado, até 40.',true); + if(!size)return say('Nenhum tamanho na tabela. Peça à Gestão para cadastrar.',true); + const qty=Number($('montar-qty').value); + if(!Number.isInteger(qty)||qty<1||qty>9999)return say('A quantidade vai de 1 a 9999.',true); + if(!montarFolderReady())return; + let found; + try{found=await montarRead(code,size);} + catch(e){if(!montarFolderError(e))say(e.message,true);return;} + if(!found){montarPaintNotFound();return say('Código não existe em Estampas/.',true);} + montarPaintPreview(found); + if(found.widthCm>56)return say('A estampa tem '+cm(found.widthCm)+' cm de largura: o máximo é 56 cm.',true); + const dpi=montarDpi(found); + if(dpiline.code===code&&line.letter===size.letter); + if(existing){existing.qty=Math.min(9999,existing.qty+qty);montarPaintLines();return;} + MONTAR.lines.push({id:++MONTAR.seq,code,letter:size.letter,widthCm:found.widthCm,qty, + heightCm:montarHeight(found),dpi,url:URL.createObjectURL(found.file),file:found.file}); + montarPaintLines(); +} + +function montarPaintSelect(){ + const select=$('montar-size'),current=select.value; + select.replaceChildren(...MONTAR.sizes.map(size=>{ + const option=node('option',size.letter+' · '+cm(size.width_cm)+' cm');option.value=size.letter;return option; + })); + select.disabled=!MONTAR.sizes.length; + select.value=MONTAR.sizes.some(size=>size.letter===current)?current:(MONTAR.sizes[0]?.letter||''); +} +// A row of the table: the letter and its width in centimetres. +function montarSizeRow(size){ + const row=node('div',undefined,'montar-size-row'); + const letter=node('input',undefined,'montar-letter');letter.value=size?.letter||'';letter.maxLength=2; + letter.autocomplete='off';letter.setAttribute('aria-label','Letra do tamanho'); + letter.oninput=()=>{letter.value=letter.value.toUpperCase().replace(/[^A-Z]/g,'');MONTAR.dirty=true;}; + const width=node('input',undefined,'montar-width');width.type='number';width.min='0.01';width.max='56';width.step='0.01'; + width.value=size?Number(size.width_cm):'';width.setAttribute('aria-label','Largura em centímetros'); + width.oninput=()=>{MONTAR.dirty=true;}; + const remove=iconButton(IC.close,'Remover tamanho',()=>{row.remove();MONTAR.dirty=true;}); + row.append(letter,width,remove); + return row; +} +function montarPaintSizeEditor(){ + const panel=$('montar-sizes-panel'); + if(!may('manage')){panel.hidden=true;return;} + panel.hidden=false; + const head=node('div',undefined,'montar-size-head'); + head.append(node('span','Letra'),node('span','Largura (cm)'),node('span')); + $('montar-sizes').replaceChildren(head,...MONTAR.sizes.map(montarSizeRow)); +} +async function montarSaveSizes(){ + const rows=[...$('montar-sizes').querySelectorAll('.montar-size-row')]; + const sizes=[],seen=new Set(); + for(const row of rows){ + const letter=row.querySelector('.montar-letter').value.trim().toUpperCase(); + const width=Number(row.querySelector('.montar-width').value); + if(!/^[A-Z]{1,2}$/.test(letter))return say('Cada tamanho precisa de uma letra de A a ZZ.',true); + if(seen.has(letter))return say('A letra '+letter+' aparece mais de uma vez.',true); + if(!(width>0&&width<=56))return say('A largura de '+letter+' vai de 0,01 a 56 cm.',true); + seen.add(letter);sizes.push({letter,width_cm:Number(width.toFixed(2))}); + } + if(!sizes.length)return say('A tabela precisa de pelo menos um tamanho.',true); + await api('/stamp-sizes',{sizes}); + MONTAR.dirty=false; + say('Tamanhos salvos.'); + await montarLoadSizes(true); + montarQueuePreview(); +} +async function montarLoadSizes(repaint){ + MONTAR.sizes=(await api('/stamp-sizes')).sizes||[]; + montarPaintSelect(); + if(repaint||!MONTAR.dirty)montarPaintSizeEditor(); +} +async function loadMontador(){ + montarPaintFolder(); + try{await montarLoadSizes(false);} + catch(e){say(e.message,true);return;} + if(montarFolderReady()){ + if($('montar-code').value.trim()){if(!MONTAR.preview)montarQueuePreview();} + else montarPaintHint(); + } + montarPaintLines(); +} + +$('montar-code').addEventListener('input',montarQueuePreview); +$('montar-size').addEventListener('change',()=>montarPreview().catch(e=>say(e.message,true))); +$('montar-qty').addEventListener('keydown',event=>{ + if(event.key==='Enter'){event.preventDefault();$('montar-add').click();} +}); +$('montar-add').onclick=async()=>{ + $('montar-add').disabled=true; + try{await montarAdd();}catch(e){say(e.message,true);}finally{$('montar-add').disabled=false;} +}; +$('montar-clear').onclick=()=>montarClear(); +$('montar-build').title='Em breve'; +$('montar-size-add').onclick=()=>{MONTAR.dirty=true;$('montar-sizes').append(montarSizeRow(null));}; +$('montar-size-save').onclick=async()=>{ + $('montar-size-save').disabled=true; + try{await montarSaveSizes();}catch(e){say(e.message,true);}finally{$('montar-size-save').disabled=false;} +}; diff --git a/web/kanban.css b/web/kanban.css index 366f10d..488bd6c 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -1210,3 +1210,49 @@ dialog.viewer::backdrop{background:var(--scrim)} 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}} + +/* Montador (Fase 2, front 7): the stamp by its code, the sheet's list and the + table of sizes. The lookup reads Estampas/ from the folder of Integrações. */ +#tab-montar .montar-add{display:grid;grid-template-columns:minmax(160px,1fr) minmax(130px,200px) 110px auto;gap:12px;align-items:end;padding:16px 18px 0} +#tab-montar .montar-add>.btn{height:42px} +#tab-montar .montar-preview{padding:16px 18px} +#tab-montar .montar-preview:empty{display:none} +#tab-montar .montar-stamp{display:flex;align-items:center;gap:14px;min-width:0} +#tab-montar .montar-stamp img{width:64px;height:64px;object-fit:contain;padding:4px;border-radius:9px;border:1px solid var(--ln2);background:var(--bg);flex:none} +#tab-montar .montar-stampinfo{display:flex;flex-direction:column;gap:3px;min-width:0} +#tab-montar .montar-stampinfo b{font-size:15px;font-weight:650} +#tab-montar .montar-stampinfo span{font-size:13px;color:var(--tx2)} +#tab-montar .montar-missing{margin:0;font-size:13.5px;color:var(--bad)} +#tab-montar .montar-hint{margin:0;font-size:13.5px;color:var(--tx3)} +#tab-montar .montar-total{margin-left:auto;font-size:13.5px;font-weight:650} +#tab-montar .montar-line{display:grid;grid-template-columns:56px minmax(110px,1fr) 82px auto 70px 36px;gap:12px;align-items:center;padding:10px 18px;border-bottom:1px solid var(--ln)} +#tab-montar .montar-line:last-child{border-bottom:0} +#tab-montar .montar-thumb{width:56px;height:56px;object-fit:contain;padding:4px;border-radius:9px;border:1px solid var(--ln2);background:var(--bg)} +#tab-montar .montar-linemeta{display:flex;flex-direction:column;gap:2px;min-width:0} +#tab-montar .montar-linemeta b{font-size:14px;font-weight:650} +#tab-montar .montar-linemeta span{font-size:12.5px;color:var(--tx3)} +#tab-montar .montar-qty{width:82px;height:36px;padding:0 8px;border-radius:9px;border:1px solid var(--ln2);background:var(--bg);color:var(--tx);text-align:right} +#tab-montar .montar-dpi{display:flex;justify-content:flex-end} +#tab-montar .montar-height{font-size:13px;color:var(--tx2);text-align:right;white-space:nowrap} +#tab-montar #montar-lines .emptystate{padding:28px 18px} +#tab-montar .montar-actions{display:flex;justify-content:flex-end;gap:10px;padding:12px 18px;border-top:1px solid var(--ln)} +#tab-montar .montar-sizes{display:flex;flex-direction:column;padding:8px 0} +#tab-montar .montar-size-head,#tab-montar .montar-size-row{display:grid;grid-template-columns:90px 160px 36px;gap:12px;align-items:center;padding:6px 18px} +#tab-montar .montar-size-head{font-size:12.5px;color:var(--tx3)} +#tab-montar .montar-size-row input{height:36px;padding:0 10px;border-radius:9px;border:1px solid var(--ln2);background:var(--bg);color:var(--tx)} +#tab-montar .montar-size-row input:focus{border-color:var(--acc)} +@media (max-width:700px){ + #tab-montar .montar-add{grid-template-columns:minmax(0,1fr) minmax(0,1fr);padding:14px 14px 0} + #tab-montar .montar-add>.btn{grid-column:1/-1} + #tab-montar .montar-preview{padding:14px} + #tab-montar .montar-line{grid-template-columns:48px minmax(0,1fr) auto auto;grid-template-areas:"thumb meta qty remove" "thumb meta dpi height";gap:8px 10px;padding:10px 14px} + #tab-montar .montar-thumb{grid-area:thumb;width:48px;height:48px} + #tab-montar .montar-linemeta{grid-area:meta} + #tab-montar .montar-qty{grid-area:qty} + #tab-montar .montar-dpi{grid-area:dpi} + #tab-montar .montar-height{grid-area:height} + #tab-montar .montar-line>.btn{grid-area:remove} + #tab-montar .montar-actions{flex-wrap:wrap;padding:12px 14px} + #tab-montar .montar-actions .btn{flex:1} + #tab-montar .montar-size-head,#tab-montar .montar-size-row{grid-template-columns:70px minmax(0,1fr) 36px;padding:6px 14px} +} diff --git a/web/kanban.html b/web/kanban.html index cd71fc4..bd7cde8 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -38,6 +38,7 @@ + @@ -114,6 +115,35 @@
+ @@ -188,4 +218,4 @@
- + diff --git a/web/kanban.js b/web/kanban.js index 032103a..143d701 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -44,7 +44,7 @@ let quoteQuery='', quoteProduct='', quoteLayout='', quoteFlag='', quoteTimer=nul // The signed-in operator and what their profile allows (app/core/auth.py). let ME=null; const may=cap=>!!ME?.can?.includes(cap); -const ROLE_NAMES={superadmin:'Superadmin',admin:'Administrador',gestao:'Gestão',designer:'Designer',operador:'Operador',revisor:'Revisor',vendedor:'Vendedor',financeiro:'Financeiro'}; +const ROLE_NAMES={superadmin:'Superadmin',admin:'Administrador',gestao:'Gestão',designer:'Designer',operador:'Operador',revisor:'Revisor',vendedor:'Vendedor',financeiro:'Financeiro',expedicao:'Expedição'}; // Which moves this profile makes, and which columns' order it sets: the // server's own list (app/core/auth.py MOVES), never worked out here. const mayMove=(from,to)=>!!ME?.moves?.some(([a,b])=>a===from&&b===to); @@ -59,7 +59,7 @@ const mayAct=order=>ME?.role!=='operador'||order.state==='tra'||isMine(order); // Vendedor and Financeiro consult Cotações and Números without acting there. const consults=()=>['vendedor','financeiro'].includes(ME?.role); const TAB_NEEDS={quotes:o=>may('manage')||consults(),payments:()=>may('payments'), - stats:()=>may('manage')||consults(),integrations:()=>may('manage')||may('print'),users:()=>may('users')}; + stats:()=>may('manage')||consults(),integrations:()=>may('manage')||may('print'),users:()=>may('users'),montar:()=>may('assemble')}; function applyRole(){ for(const b of document.querySelectorAll('[data-tab]')){const need=TAB_NEEDS[b.dataset.tab];b.hidden=!!need&&!need();} if(TAB_NEEDS[tab]&&!TAB_NEEDS[tab]())showTab('board'); @@ -654,14 +654,14 @@ async function load(quiet=false){ } } // The page's name in the top bar; Produção also says what is open. -const PAGE_TITLES={board:'Produção',quotes:'Cotações',payments:'Pagamentos',stats:'Números',integrations:'Integrações',users:'Usuários'}; +const PAGE_TITLES={board:'Produção',quotes:'Cotações',payments:'Pagamentos',stats:'Números',integrations:'Integrações',users:'Usuários',montar:'Montar folha'}; function showTab(name){ tab=name;$('tab-quotes').classList.remove('reviewing'); for(const b of document.querySelectorAll('[data-tab]'))b.setAttribute('aria-selected',String(b.dataset.tab===name)); $('page-title').textContent=PAGE_TITLES[name];$('board-summary').hidden=name!=='board';$('filter-open').hidden=name!=='board'; $('more-nav').classList.toggle('on',['integrations','users'].includes(name)); - for(const id of ['board','quotes','payments','stats','integrations','users'])$('tab-'+id).hidden=name!==id; - const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:eventsIfAllowed,users:loadUsers}; + for(const id of ['board','quotes','payments','stats','integrations','users','montar'])$('tab-'+id).hidden=name!==id; + const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:eventsIfAllowed,users:loadUsers,montar:loadMontador}; if(board&&lists[name])lists[name]().catch(e=>say(e.message,true)); } function render(){ @@ -674,7 +674,7 @@ function render(){ tinyHeader();renderBoard();renderIntegrations(); $('badge-more').textContent=$('badge-integrations').textContent; // Lists live on their own pages of the API; refresh the one being looked at. - const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:eventsIfAllowed,users:loadUsers}; + const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:eventsIfAllowed,users:loadUsers,montar:loadMontador}; if(lists[tab])lists[tab]().catch(e=>say(e.message,true)); if(openOrder){const order=board.orders.find(o=>o.id===openOrder);if(order)renderPanel(order);else closePanel();} } @@ -2556,7 +2556,8 @@ const PRODUCT_LABEL={textil:'Têxtil',uv:'UV'}; const ROLE_HINTS={superadmin:'Tudo, e o suporte do sistema.',admin:'Tudo, inclusive usuários e máquinas.', gestao:'Tudo menos usuários; no quadro só puxa para trás, com motivo.',designer:'Aprova e recusa o arquivo final e pede correção.', operador:'Escolhe a máquina ao entrar, puxa da fila, imprime e passa para a Revisão.',revisor:'Confere a folha impressa e libera para Finalizado.', - vendedor:'Só consulta.',financeiro:'Pagamentos, Números e Cotações; cancela pedido com motivo.'}; + vendedor:'Só consulta.',financeiro:'Pagamentos, Números e Cotações; cancela pedido com motivo.', + expedicao:'Monta folhas no Kanban; só consulta o resto.'}; // Who is on the system: used it in the last 15 minutes, signed in before, // never, or switched off. const PRESENCE={on:'Ativo agora: usou o sistema nos últimos 15 minutos',away:'Inativo',never:'Nunca entrou',off:'Desativado: não entra no sistema'}; @@ -2567,11 +2568,11 @@ function avatar(u,className='ava'){ p.title=PRESENCE[presence(u)];a.append(p);return a; } // "O que cada perfil faz": Y does it, V only looks; the server's rules (app/core/auth.py). -const ROLE_COLUMNS=['admin','gestao','designer','operador','revisor','vendedor','financeiro']; -const ROLE_MATRIX=[['Aprovar o arquivo final','YYYNNNN'],['Pedir correção','YYYNNNN'],['Puxar da fila e imprimir','YNNYNNN'], - ['Lançar na ficha da máquina','YYNYNNN'],['Liberar para Finalizado','YNNNYNN'],['Foto da revisão','YYNNYNN'],['Voltar uma etapa, com motivo','YYYYYNN'],['Marcar retirado','YYYYYNN'], - ['Cotações e Números','YYNNNVV'],['Pagamentos','YYNNNNV'],['Pedido pago fora do site','YYNNNNN'],['Prova OK ou reprovada','YYNNNYN'],['Cancelar pedido','YYNNNNY'], - ['Abrir retrabalho','NYNNNNN'],['Autorizar retrabalho','YNNNNNN'],['Usuários e máquinas','YNNNNNN']]; +const ROLE_COLUMNS=['admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao']; +const ROLE_MATRIX=[['Aprovar o arquivo final','YYYNNNNN'],['Pedir correção','YYYNNNNN'],['Puxar da fila e imprimir','YNNYNNNN'], + ['Lançar na ficha da máquina','YYNYNNNN'],['Liberar para Finalizado','YNNNYNNN'],['Foto da revisão','YYNNYNNN'],['Voltar uma etapa, com motivo','YYYYYNNN'],['Marcar retirado','YYYYYNNN'], + ['Cotações e Números','YYNNNVVN'],['Pagamentos','YYNNNNVN'],['Pedido pago fora do site','YYNNNNNN'],['Prova OK ou reprovada','YYNNNYNN'],['Cancelar pedido','YYNNNNYN'], + ['Abrir retrabalho','NYNNNNNN'],['Autorizar retrabalho','YNNNNNNN'],['Usuários e máquinas','YNNNNNNN'],['Montar folha','YYNNNYNY']]; let usersData=null; async function loadUsers(){ usersData=await api('/users'); @@ -2644,7 +2645,7 @@ function userForm(u){ const editing=!!u; const name=node('input');name.required=true;name.maxLength=80;name.value=u?.name||'';name.placeholder='Nome e sobrenome'; const email=node('input');email.type='email';email.required=true;email.value=u?.email||'';email.placeholder='nome@dropstar.com.br'; - const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','designer','operador','revisor','vendedor','financeiro']; + const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao']; const role=choice(roles.map(r=>({value:r,label:ROLE_NAMES[r],hint:ROLE_HINTS[r]})),u?.role||'operador', {label:'Perfil',disabled:u?.role==='superadmin'||u?.email===ME.email}); const roleField=node('div',undefined,'fld');roleField.append(node('span','Perfil'),role,role.hint);