feat: rework register, opened by Gestao with a locked cause and authorized by an Administrador (Dropstar's rules D-02 to D-04)
All checks were successful
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 3m27s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m2s
All checks were successful
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 3m27s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m2s
Gestao opens a rework from the order panel with its cause (falha de impressao, perfil de cor, erro de tratamento, erro de pedido, or arte aprovada pelo cliente, outside the goal), the metres redone and a note; the cause never changes. An Administrador authorizes or declines it with a reason, never one they opened, and only an authorized rework counts. The order keeps who printed it. Numeros shows the metres redone per cause over the film printed, against 0,4% per cause and 1,6% for the house, by who printed, and the reworks waiting for authorization. Vendedor goes back to viewing only (D-30): registering orders paid outside is Administrador and Gestao. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user