diff --git a/app/api/operator.py b/app/api/operator.py index 0ead2f2..1990534 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -3,6 +3,7 @@ import hashlib import os import re import secrets +from decimal import Decimal from datetime import date, datetime, timedelta, timezone from typing import Literal from uuid import UUID @@ -224,6 +225,11 @@ def with_print_files(c, orders): treated = c.execute(f'''SELECT f.order_id,f.item_index,f.created_by FROM dtf_local.order_files f JOIN dtf_local.orders o ON o.id=f.order_id WHERE f.order_id=ANY(%s) AND f.active AND {TREATED} ORDER BY f.item_index''', (ids,)).fetchall() + # Each order's reworks (D-02 to D-04), with the names of who opened, + # decided and printed. + reworks = c.execute(f'''SELECT r.*, {person('r.opened_by')} AS opened_name, {person('r.decided_by')} AS decided_name, + {person('r.printed_by')} AS printed_name FROM dtf_local.reworks r WHERE r.order_id=ANY(%s) ORDER BY r.id''', + (ids,)).fetchall() # Why each order was last sent to correction, for the notice to the customer. reasons = {row['order_id']: row['reason'] for row in c.execute('''SELECT DISTINCT ON (order_id) order_id,reason FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()} @@ -235,9 +241,15 @@ def with_print_files(c, orders): order['treated'] = {'items': [row['item_index'] for row in mine], 'by': mine[0]['created_by']} if mine else None order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')} for row in fixes if row['order_id'] == order['id']] + order['reworks'] = [row for row in reworks if row['order_id'] == order['id']] return assign_machines(c, orders) +def person(column): + """SQL: the team member's name for the e-mail in `column`, or the e-mail.""" + return f'COALESCE((SELECT op.name FROM dtf_local.operators op WHERE op.email={column}), {column})' + + def cursor_pair(first, second): if (first is None) != (second is None): raise HTTPException(422, 'Both cursor fields are required') @@ -456,6 +468,67 @@ def register_order(uid: UUID, body: PaidOutside, user=Depends(can('enter'))): return order +# Rework (Dropstar's rules D-02 to D-04): four causes of the house, each with a +# goal of 0,4% of the film printed (1,6% in all), and the customer's approved +# bad art, recorded apart and outside the goal (D-04). +HOUSE_CAUSES = ('impressao', 'perfil_cor', 'tratamento', 'pedido') +CUSTOMER_CAUSE = 'arte_cliente' +REWORK_GOAL_PERCENT = Decimal('0.4') + + +class ReworkOpen(StrictModel): + cause: Literal[HOUSE_CAUSES + (CUSTOMER_CAUSE,)] + metres: Decimal = Field(gt=0, le=1000) + note: str = Field(default='', max_length=1000) + + +class ReworkDecision(StrictModel): + authorized: bool + reason: str = Field(default='', max_length=1000) + + +@router.post('/api/operator/orders/{uid}/reworks') +def open_rework(uid: UUID, body: ReworkOpen, user=Depends(can('rework'))): + """Coordination opens a rework with its cause (D-02). There is no way to + change the cause afterwards (D-03).""" + with db.connect() as c: + order = c.execute('SELECT id,number,cancelled_at FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone() + if not order: + raise HTTPException(404, 'Pedido não encontrado.') + if order['cancelled_at']: + raise HTTPException(409, 'Pedido cancelado não abre retrabalho.') + # Who printed the sheet: who last sent it to Revisão. + printed = c.execute('''SELECT operator FROM dtf_local.movements WHERE order_id=%s AND to_state='rev' + AND NOT back ORDER BY id DESC LIMIT 1''', (uid,)).fetchone() + row = c.execute('''INSERT INTO dtf_local.reworks(order_id,cause,metres,note,printed_by,opened_by) + VALUES(%s,%s,%s,%s,%s,%s) RETURNING *''', + (uid, body.cause, body.metres, body.note.strip(), printed['operator'] if printed else None, + user)).fetchone() + audit('rework_opened', order=order['number'], cause=body.cause, operator=user) + return row + + +@router.post('/api/operator/reworks/{rid}/decision') +def decide_rework(rid: int, body: ReworkDecision, user=Depends(can('authorize'))): + """An Administrador authorizes a rework, and only then it counts, or + declines it with a reason (D-02). Never one they opened themselves.""" + reason = body.reason.strip() + if not body.authorized and len(reason) < 3: + raise HTTPException(422, 'Diga por que o retrabalho não foi autorizado.') + with db.connect() as c: + row = c.execute('SELECT * FROM dtf_local.reworks WHERE id=%s FOR UPDATE', (rid,)).fetchone() + if not row: + raise HTTPException(404, 'Retrabalho não encontrado.') + if row['decided_at']: + raise HTTPException(409, 'Este retrabalho já foi decidido.') + if row['opened_by'] == user: + raise HTTPException(409, 'Quem abriu o retrabalho não pode autorizá-lo.') + row = c.execute('''UPDATE dtf_local.reworks SET authorized=%s, decided_by=%s, decided_at=now(), decline_reason=%s + WHERE id=%s RETURNING *''', (body.authorized, user, None if body.authorized else reason, rid)).fetchone() + audit('rework_decided', rework=rid, authorized=body.authorized, operator=user) + return row + + @router.post('/api/operator/quotes/{uid}/discard') def discard_quote(uid: UUID, user=Depends(can('manage'))): """An unpaid quote leaves the Kanban and can no longer be paid. Its files @@ -902,6 +975,21 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start o.created_at))) / 3600 AS oldest_hours FROM dtf_local.orders o WHERE {REAL_ORDER} AND o.state<>'fin' GROUP BY o.state''').fetchall() printed = machine_output(c, start, end) + # Rework of the period (D-02 to D-04): the authorized ones, by the day + # they were opened, over the film the machines printed in it. + not_test = "COALESCE(o.payment->>'provider','') <> 'teste'" + opened = "(r.opened_at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s" + redone = {row['cause']: row for row in c.execute(f'''SELECT r.cause, sum(r.metres) AS metres, + count(DISTINCT r.order_id) AS orders FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id + WHERE r.authorized AND {not_test} AND {opened} GROUP BY r.cause''', period).fetchall()} + # The house's rework enters the pay of who printed it (D-02). + by_printer = c.execute(f'''SELECT COALESCE({person('r.printed_by')}, 'Sem registro') AS who, + sum(r.metres) AS metres FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id + WHERE r.authorized AND r.cause<>%s AND {not_test} AND {opened} GROUP BY 1 ORDER BY 2 DESC''', + (CUSTOMER_CAUSE,) + period).fetchall() + undecided = c.execute(f'''SELECT r.id, r.order_id, o.number, r.cause, r.metres, r.opened_at, + {person('r.opened_by')} AS opened_name FROM dtf_local.reworks r JOIN dtf_local.orders o ON o.id=r.order_id + WHERE r.decided_at IS NULL AND {not_test} ORDER BY r.opened_at''').fetchall() # Arte tratada, for the designer's productivity: orders of the period # whose final someone prepared, by who approved it (any version). treated = c.execute(f'''SELECT COALESCE(op.name, f.created_by) AS who, count(DISTINCT f.order_id) AS orders @@ -942,7 +1030,29 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start 'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'], 'median_hours': hours(row['median_hours'])} for row in stages}, 'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting}, - 'machines': printed} + 'machines': printed, 'rework': rework_figures(printed, redone, by_printer, undecided)} + + +def rework_figures(printed, redone, by_printer, undecided): + """Números' rework: per cause, the metres redone over the film printed, + against the goal; the house's total against four times it.""" + film = Decimal(str(sum(m['metres'] for m in printed))) + share = lambda metres: float(round(100 * metres / film, 2)) if film else None + causes = [] + for cause in HOUSE_CAUSES + (CUSTOMER_CAUSE,): + row = redone.get(cause) + metres = Decimal(row['metres']) if row else Decimal(0) + causes.append({'cause': cause, 'metres': float(metres), 'orders': row['orders'] if row else 0, + 'percent': share(metres)}) + house = sum(Decimal(str(c['metres'])) for c in causes if c['cause'] != CUSTOMER_CAUSE) + return {'film_metres': float(film), 'goal_percent': float(REWORK_GOAL_PERCENT), + 'house': {'metres': float(house), 'percent': share(house), + 'goal_percent': float(REWORK_GOAL_PERCENT * len(HOUSE_CAUSES))}, + 'causes': causes, + 'by_printer': [{'who': row['who'], 'metres': float(row['metres'])} for row in by_printer], + 'pending': [{'id': row['id'], 'order_id': str(row['order_id']), 'number': row['number'], + 'cause': row['cause'], 'metres': float(row['metres']), 'opened_at': row['opened_at'].isoformat(), + 'opened_by': row['opened_name']} for row in undecided]} def machine_output(c, start, end): diff --git a/app/core/auth.py b/app/core/auth.py index 75fe677..ac490fa 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -129,7 +129,12 @@ CAPABILITIES = { 'print': {'superadmin', 'admin', 'gestao', 'operador'}, 'manage': {'superadmin', 'admin', 'gestao'}, # Registering an order paid outside the system, from its Site quote (D-35). - 'enter': {'superadmin', 'admin', 'gestao', 'vendedor'}, + # Not the seller: Vendedor only views the board (D-30). + 'enter': {'superadmin', 'admin', 'gestao'}, + # Rework (D-02): coordination opens it with its cause, an Administrador + # (Thales or Alexandre) authorizes it. + 'rework': {'superadmin', 'gestao'}, + 'authorize': {'superadmin', 'admin'}, 'users': {'superadmin', 'admin'}, 'integrations': {'superadmin'}, } diff --git a/app/schema.sql b/app/schema.sql index 1e37f1f..fa9f14b 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -383,3 +383,21 @@ UPDATE dtf_local.orders SET origin='site' WHERE origin IS NULL; ALTER TABLE dtf_local.orders ALTER COLUMN origin SET NOT NULL; ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check; ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento')); + +-- Rework (Dropstar's rules D-02 to D-04, 2026-10-26; the user's answers of +-- 2026-10-27). Gestão opens it with its cause, and the cause never changes +-- after (D-03); an Administrador authorizes or declines it, never one they +-- opened, and only an authorized rework counts. Bad art the customer approved +-- is recorded apart, outside the goal (D-04). printed_by is who sent the +-- sheet to Revisão, as the rework enters the printer's pay. +CREATE TABLE IF NOT EXISTS dtf_local.reworks ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE, + cause text NOT NULL CHECK (cause IN ('impressao','perfil_cor','tratamento','pedido','arte_cliente')), + metres numeric NOT NULL CHECK (metres > 0), + note text NOT NULL DEFAULT '', + printed_by text, + opened_by text NOT NULL, opened_at timestamptz NOT NULL DEFAULT now(), + authorized boolean, decided_by text, decided_at timestamptz, decline_reason text +); +CREATE INDEX IF NOT EXISTS reworks_order ON dtf_local.reworks(order_id); diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 7d9f568..041bd37 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -477,23 +477,33 @@ Still to do (2026-10-26): payment step, and in the Kanban's Cotações, on the approved quote, picks the origin and how it was paid (Pix, cartão, dinheiro, crédito do cliente), neither preselected, with an optional note. The price is the quote's, the - Site's table price. Allowed to Administrador, Gestão and Vendedor (the - "enter" capability). The order's payment is `{'provider': 'manual', + Site's table price. Allowed to Administrador and Gestão (the "enter" + capability); not Vendedor, who only views the board (D-30). The order's payment is `{'provider': 'manual', 'method', 'note', 'operator'}`; it counts in Números like any paid order and the customer gets the usual paid e-mail. An Atendimento (or Site) order goes to Tiny like a Site one, its internal note saying "pago fora do site" and how, Pix and card naming Tiny's forma de recebimento. A Dropflow order stays out of Tiny, its status updates and cancelling included (payments.in_tiny), until Dropstar names that channel's revenue category. +- Rework register (Dropstar's rules D-02 to D-04; the user's answers of + 2026-10-27), dtf_local.reworks. Gestão opens it from the order panel's menu + ("Abrir retrabalho") with its cause, the metres redone (the order's printed + metres to start) and a note: falha de impressão, perfil de cor, erro de + tratamento, erro de pedido, or arte aprovada pelo cliente (outside the + goal, D-04). The cause never changes after (D-03: there is no route for it). + An Administrador authorizes it or declines it with a reason, never one they + opened; the reprint is never held up, and only an authorized rework counts. + Who printed it (who last sent the order to Revisão) is kept, as the house's + rework enters the printer's pay. Números, "Retrabalho": per cause, the + metres redone over the film printed in the period (Por máquina), by the day + the rework was opened, against 0,4% per cause and 1,6% for the house; the + house's by who printed it; and the ones waiting for authorization. A card + with a rework carries a "Retrabalho" badge. - Still open from the internal rules (docs received 2026-10-26): customer credit as a payment the system keeps track of (today "crédito do cliente" - is only how a registered order was paid), the Tiny revenue category for Dropflow orders (not DTF SITE; its name and - the origin value must be the same word, the document says), and the rework - register (D-02 to D-04: four causes, falha de impressão, perfil de cor, - erro de tratamento and erro de pedido; opened and classified by Mayana, - authorized by Thales or Alexandre, locked once opened; bad art the customer - approved does not count; goal 0,4% per cause, 1,6% in all). - Done 2026-10-27: the folders catch up on what passed while the Kanban + is only how a registered order was paid), and the Tiny revenue category + for Dropflow orders (not DTF SITE; its name and the origin value must be + the same word, the document says). Done 2026-10-27: the folders catch up on what passed while the Kanban computer was off, time in "Aguardando contato" no longer counts in Números' time figures (D-38; each wait is kept in dtf_local.contact_waits, from mark to clear), and a file's type comes from its first bytes (D-13, see the diff --git a/tests/users_test.py b/tests/users_test.py index 72db0a1..c7e0294 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -152,10 +152,9 @@ def run(): seller.call(f'/operator/quotes/{uv_q}/discard', {}, expected=403) seller.call(f'/operator/orders/{textil_o}/machine', {'machine_id': None}, expected=403) seller.call(f'/operator/orders/{textil_o}/contact', {'waiting': True, 'note': 'Ligar'}, expected=403) - # The seller registers orders paid outside (D-35); this quote already has - # its order, so the answer is 409, past the permission. - assert seller.call('/operator/me')['can'] == ['enter', 'view'] - seller.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=409) + # The seller only views the board (D-30): no order registered by hand either. + assert seller.call('/operator/me')['can'] == ['view'] + seller.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=403) # Only the Revisor releases to Finalizado: not even the administrator. admin.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'], 'reason': ''}, expected=403) @@ -333,6 +332,54 @@ def run(): board = {o['id']: o for o in su.call('/operator/board', operator=True)['orders']} back = board[str(textil_o)]['machine'] assert back and back['id'] != uv and not back['chosen'] + # Rework (D-02 to D-04): Gestão opens it with its cause, an Administrador + # authorizes it, never their own, and only then it counts in Números. + emails['gestao'] = f'gestao-{tag}@example.test' + admin.call('/operator/users', {'name': 'Mayana', 'email': emails['gestao'], 'role': 'gestao', 'password': PASSWORD}) + coord = signed_in(emails['gestao']) + with db.connect() as c: + c.execute('UPDATE dtf_local.orders SET payment=%s WHERE id=%s', + (Jsonb({'provider': 'mercadopago', 'id': f'rework-{tag}'}), uv_o)) + figures = lambda: admin.call('/operator/stats?days=7')['rework'] + cause = lambda figures, name: next(r for r in figures['causes'] if r['cause'] == name)['metres'] + before = figures() + coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'outra', 'metres': '1'}, expected=422) + coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'impressao', 'metres': '0'}, expected=422) + admin.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'impressao', 'metres': '1'}, expected=403) + signed_in(emails['vendedor'], 'outra-senha-de-teste').call(f'/operator/orders/{uv_o}/reworks', + {'cause': 'impressao', 'metres': '1'}, expected=403) + redo = coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'impressao', 'metres': '0.5', 'note': 'Falhou'}) + # Who printed it: the operator who sent it to Revisão, for their pay. + assert redo['printed_by'] == emails['operador'] and redo['authorized'] is None, redo + shown = next(o for o in admin.call('/operator/board')['orders'] if o['id'] == str(uv_o))['reworks'] + # Names where the account exists; the operator's was deleted above, so their e-mail. + assert [(r['cause'], r['opened_name'], r['printed_name']) for r in shown] == [ + ('impressao', 'Mayana', emails['operador'])], shown + # Undecided, it does not count; it waits in Números. + waiting = figures() + assert cause(waiting, 'impressao') == cause(before, 'impressao') + assert redo['id'] in [p['id'] for p in waiting['pending']] + coord.call(f"/operator/reworks/{redo['id']}/decision", {'authorized': True}, expected=403) + admin.call(f"/operator/reworks/{redo['id']}/decision", {'authorized': False}, expected=422) + admin.call(f"/operator/reworks/{redo['id']}/decision", {'authorized': True}) + admin.call(f"/operator/reworks/{redo['id']}/decision", {'authorized': True}, expected=409) + after = figures() + assert cause(after, 'impressao') == cause(before, 'impressao') + 0.5 + assert after['house']['metres'] == before['house']['metres'] + 0.5 and after['house']['goal_percent'] == 1.6 + # The customer's approved bad art counts apart, outside the house (D-04). + art = coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'arte_cliente', 'metres': '2'}) + admin.call(f"/operator/reworks/{art['id']}/decision", {'authorized': True}) + last = figures() + assert cause(last, 'arte_cliente') == cause(after, 'arte_cliente') + 2 + assert last['house']['metres'] == after['house']['metres'] + # Declined, with its reason; and nobody decides a rework they opened. + wrong = coord.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'pedido', 'metres': '1'}) + declined = admin.call(f"/operator/reworks/{wrong['id']}/decision", {'authorized': False, 'reason': 'Não houve reimpressão'}) + assert declined['authorized'] is False and declined['decline_reason'] == 'Não houve reimpressão' + assert cause(figures(), 'pedido') == cause(last, 'pedido') + own = su.call(f'/operator/orders/{uv_o}/reworks', {'cause': 'pedido', 'metres': '1'}, operator=True) + su.call(f"/operator/reworks/{own['id']}/decision", {'authorized': True}, operator=True, expected=409) + print('PASS: profiles limit actions, admins manage users but not the superadmin or themselves, ' 'machines take orders by load and limit, keep a choice, and limit what their operators see') finally: diff --git a/web/kanban.css b/web/kanban.css index 9fde6f9..8ba8c1a 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -268,6 +268,9 @@ main{padding:0 24px 24px} .kpi b{font-size:24px;font-weight:700;letter-spacing:-.01em;font-variant-numeric:proportional-nums} .kpi small{font-size:13px;color:var(--faint)} .statbox{padding:16px 18px;border:1px solid var(--line2);border-radius:12px;background:var(--card)} +.statbox .stats-sub{margin:18px 0 6px;font-size:14px;font-weight:700;color:var(--tx2)} +.plainlist{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:2px;font-size:13.5px;color:var(--muted)} +.plainlist .linkbtn{padding:2px 0;color:var(--tx)} .chart{position:relative} .chart svg{display:block;width:100%;height:auto} .chart .grid{stroke:var(--line);stroke-width:1} diff --git a/web/kanban.html b/web/kanban.html index 6f7043d..6825796 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -94,6 +94,13 @@ Metros por hora: sobre o tempo em Imprimindo; pedidos imprimindo juntos na mesma máquina contam esse tempo uma vez.

MáquinaImpressoMetros por horaÚltimo finalizadoAgora
+

Retrabalho

+

Metros refeitos sobre o filme impresso no período (Por máquina), só os retrabalhos autorizados, pela data em que foram abertos. Meta de 0,4% por causa, 1,6% no total da casa; arte ruim aprovada pelo cliente fica fora da meta.

+
CausaRefeitoDo impressoMeta
+

Da casa, por quem imprimiu

+
Quem imprimiuRefeito
+

Aguardando autorização

+

Por origem

Por onde o pedido entrou: o Site, os lotes do Dropflow ou a equipe, em Atendimento. O tempo vai do pagamento ao Finalizado, sem o tempo em Aguardando contato.

OrigemPedidosMetrosRecebidoDo pagamento ao Finalizado
@@ -110,7 +117,7 @@

Quem entra no Kanban e o que cada perfil pode fazer. Administrador: tudo, inclusive esta página. Gestão: tudo, menos usuários; no quadro só puxa para trás, com motivo (Correção ou voltar uma etapa). Designer: vê todos os pedidos, aprova e recusa o arquivo final, pede correção. Operador: ligado a uma máquina, vê só os pedidos dela; imprime e passa para a Revisão. Revisor: confere a folha impressa e libera; é o único que manda para Finalizado. - Vendedor: consulta e registra pedidos pagos fora do site, em Cotações.

+ Vendedor: só consulta. Retrabalho: a Gestão abre, com a causa; o Administrador autoriza.

NomePerfilMáquinasÚltimo acesso

Máquinas

Cada pedido vai para a máquina do produto com menos metros em aberto, dentro do limite. No pedido dá para trocar.

diff --git a/web/kanban.js b/web/kanban.js index 69e664c..9509aeb 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -758,6 +758,8 @@ function card(order){ ? badge('✓ Prova OK','ok','Conferida por '+order.proof_ok_by+' em '+when(order.proof_ok_at)) : badge('Prova','warn',order.snapshot.proof?'O cliente pediu uma prova antes de imprimir':'Pedido acima de 10 m: prova antes do resto')); } + const redo=(order.reworks||[]).filter(r=>r.authorized!==false); + if(!order.cancelled_at&&redo.length)flags.append(badge('Retrabalho','bad',redo.map(r=>REWORK_CAUSES[r.cause]+' · '+metres(r.metres)+(r.authorized?'':' · aguardando autorização')).join('\n'))); // Arte tratada (Dropstar, 2026-10-27): the final is not the customer's art, someone prepared it. if(!order.cancelled_at&&order.treated)flags.append(badge('Arte tratada','info',TREATED_NOTE+' Aprovado por '+order.treated.by+'.')); c.append(artBox(s.items,'card-art'),top,buyerBlock(s,'cust'),meta,place(s.destination)); @@ -886,7 +888,7 @@ function renderPanel(order){ items.append(itemsList); const finals=node('section',undefined,'finals');finals.append(node('p','Arquivos finais','eyebrow'),node('p','Carregando…','faint')); const history=node('section');history.append(node('p','Histórico','eyebrow'),node('p','Carregando…','faint')); - body.append(facts,items,finals,history); + body.append(facts,items,finals,...(order.reworks?.length?[reworkSection(order)]:[]),history); panel.replaceChildren(head,body); api('/orders/'+order.id+'/files').then(rows=>{if(token===openToken)finalsSection(order,rows,finals);}).catch(e=>say(e.message,true)); @@ -1007,6 +1009,7 @@ function moves(order){ await api('/orders/'+order.id+'/delete',{});closePanel();say('Pedido de teste #'+order.number+' excluído.');await load(); },'menuitem bad')); }else{ + if(may('rework'))menu.append(button('Abrir retrabalho',()=>{menu.hidden=true;reworkForm(order);},'menuitem')); const b=node('button','Cancelar pedido','menuitem bad');b.type='button'; b.onclick=()=>{menu.hidden=true;toggle(cancelForm);};menu.append(b); const why=node('input');why.placeholder='Motivo do cancelamento';why.setAttribute('aria-label','Motivo do cancelamento');why.required=true;why.minLength=3;why.maxLength=1000; @@ -1203,6 +1206,48 @@ function finalsSection(order,revisions,section){ open.style.alignSelf='flex-start';open.onclick=()=>{form.hidden=!form.hidden;if(!form.hidden)form.querySelector('input:not([hidden])')?.focus();}; section.append(open,form); } +// Rework (Dropstar's rules D-02 to D-04). Gestão opens it with its cause, +// which never changes after; an Administrador authorizes or declines it, +// never one they opened. Bad art the customer approved is outside the goal. +const REWORK_CAUSES={impressao:'Falha de impressão',perfil_cor:'Perfil de cor',tratamento:'Erro de tratamento', + pedido:'Erro de pedido',arte_cliente:'Arte aprovada pelo cliente'}; +const REWORK_OUTSIDE='arte_cliente'; +function reworkForm(order){ + const cause=node('select');cause.required=true; + const none=node('option','Escolha a causa');none.value='';cause.append(none); + for(const [value,text] of Object.entries(REWORK_CAUSES)){const o=node('option',text+(value===REWORK_OUTSIDE?' (fora da meta)':''));o.value=value;cause.append(o);} + const size=node('input');size.type='number';size.required=true;size.min='0.01';size.max='1000';size.step='0.01'; + size.value=order.snapshot.items.reduce((t,i)=>t+Number(i.metres??i.billed_metres),0).toFixed(2); + const note=node('textarea');note.maxLength=1000;note.placeholder='O que aconteceu (opcional)'; + dialog('Abrir retrabalho · #'+order.number,[ + node('p','A causa não muda depois de aberta. O retrabalho conta na meta quando um administrador autoriza.','muted'), + field('Causa',cause),field('Metros refeitos',size),field('Observação',note)],async()=>{ + await api('/orders/'+order.id+'/reworks',{cause:cause.value,metres:size.value,note:note.value}); + say('Retrabalho aberto no pedido #'+order.number+'. Aguarda a autorização de um administrador.');await load(); + }); +} +function reworkSection(order){ + const section=node('section');section.append(node('p','Retrabalho','eyebrow')); + for(const r of order.reworks){ + const box=node('div',undefined,'fcard'); + box.append(node('b',REWORK_CAUSES[r.cause]+(r.cause===REWORK_OUTSIDE?' · fora da meta':'')+' · '+metres(r.metres)), + node('span','Aberto por '+r.opened_name+' em '+when(r.opened_at)+(r.printed_name?' · impresso por '+r.printed_name:''),'line')); + if(r.note)box.append(node('span',r.note,'line')); + if(r.decided_at)box.append(node('span',(r.authorized?'Autorizado por ':'Não autorizado por ')+r.decided_name+' em '+when(r.decided_at)+ + (r.decline_reason?': '+r.decline_reason:''),'line')); + else if(may('authorize')&&r.opened_by!==ME.email){ + const why=node('input');why.placeholder='Motivo, se não autorizar';why.setAttribute('aria-label','Motivo, se não autorizar');why.maxLength=1000; + const decide=authorized=>async()=>{ + await api('/reworks/'+r.id+'/decision',{authorized,reason:why.value}); + say(authorized?'Retrabalho autorizado.':'Retrabalho não autorizado.');await load();}; + const row=node('div',undefined,'buttons'); + row.append(button('Autorizar',decide(true),'btn primary'),why,button('Não autorizar',decide(false),'btn ghost')); + box.append(row); + }else box.append(node('span','Aguardando a autorização de um administrador','line')); + section.append(box); + } + return section; +} function historySection(order,rows,section){ const list=node('ol',undefined,'timeline'); const entry=(color,title,who,at,reason)=>{ @@ -1435,6 +1480,26 @@ async function loadStats(){ tr.append(node('td',t.who),node('td',t.orders+(t.orders>1?' pedidos':' pedido')));return tr;}); if(!treatedRows.length){const tr=node('tr');const td=node('td','Nenhuma arte tratada no período.','faint');td.colSpan=2;tr.append(td);treatedRows.push(tr);} $('stats-treated').replaceChildren(...treatedRows); + // Rework (D-02 to D-04): authorized metres redone over the film printed, against the goal. + const rw=data.rework, share=v=>v==null?'—':String(v).replace('.',',')+'%'; + const goal=String(rw.goal_percent).replace('.',',')+'%'; + const reworkRows=rw.causes.map(r=>{const tr=node('tr'),outside=r.cause===REWORK_OUTSIDE; + const over=!outside&&r.percent!=null&&r.percent>rw.goal_percent; + tr.append(node('td',REWORK_CAUSES[r.cause]),node('td',metres(r.metres)+(r.orders?' · '+r.orders+(r.orders>1?' pedidos':' pedido'):'')), + node('td',share(r.percent),over?'late':''),node('td',outside?'fora da meta':goal,'faint')); + if(!r.metres)tr.classList.add('off');return tr;}); + const house=node('tr');house.append(node('td','Total da casa'),node('td',metres(rw.house.metres)), + node('td',share(rw.house.percent),rw.house.percent>rw.house.goal_percent?'late':''),node('td',String(rw.house.goal_percent).replace('.',',')+'%','faint')); + house.querySelectorAll('td').forEach(td=>td.style.fontWeight='700'); + $('stats-rework').replaceChildren(...reworkRows,house); + $('stats-rework-film').textContent=metres(rw.film_metres)+' impressos no período.'; + const printerRows=rw.by_printer.map(p=>{const tr=node('tr');tr.append(node('td',p.who),node('td',metres(p.metres)));return tr;}); + if(!printerRows.length){const tr=node('tr');const td=node('td','Nenhum retrabalho da casa autorizado no período.','faint');td.colSpan=2;tr.append(td);printerRows.push(tr);} + $('stats-rework-printers').replaceChildren(...printerRows); + const waiting=rw.pending.map(p=>{const li=node('li');const open=node('button','#'+p.number,'linkbtn');open.type='button'; + open.onclick=()=>openPanel(p.order_id); + li.append(open,' · '+REWORK_CAUSES[p.cause]+' · '+metres(p.metres)+' · aberto por '+p.opened_by+' em '+when(p.opened_at));return li;}); + $('stats-rework-pending').replaceChildren(...(waiting.length?waiting:[node('li','Nenhum.','faint')])); // Each way in apart (D-21): its orders, metres, money and time to Finalizado. $('stats-origins').replaceChildren(...data.origins.map(o=>{const tr=node('tr'); tr.append(node('td',ORIGINS[o.origin]),node('td',String(o.orders)),node('td',metres(o.metres)),node('td',money(o.cents)),