Files
dtf-system/app/api/operator/rework.py
Cauê Faleiros f5df5b96e4 refactor: app/api/operator.py split by area into a package
A pure move: the 48 Kanban routes, their code and comments are unchanged,
grouped in session, board, quotes, orders, rework, integrations, stats
and files, with shared helpers in common. The fast CI check now compiles
the package's files too (app/**/*.py does not reach a third level without
globstar).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 17:11:19 -03:00

74 lines
3.4 KiB
Python

"""Rework: its causes, and opening and deciding one (D-02 to D-04)."""
from decimal import Decimal
from typing import Literal
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException
from pydantic import Field
from ...core import db
from ...core.auth import audit, can
from ...core.models import StrictModel
router = APIRouter()
# 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