feat: Dropstar's corrections of 21/10 that need no answer from them
All checks were successful
Build and deploy / Validate source (push) Successful in 1m30s
Build and deploy / Integration suite on a real stack (push) Successful in 4m2s
Build and deploy / Secret scan and release gate (push) Successful in 14s
Build and deploy / Publish images (push) Successful in 1m48s
All checks were successful
Build and deploy / Validate source (push) Successful in 1m30s
Build and deploy / Integration suite on a real stack (push) Successful in 4m2s
Build and deploy / Secret scan and release gate (push) Successful in 14s
Build and deploy / Publish images (push) Successful in 1m48s
- the home example priced as the ready sheet it shows (nota 92, R$ 14,90) - opening hours 7h to 18h, and art sent at any time - uploads up to 1 GB, every file scanned - a Designer profile: artwork and corrections on every order, moving only among Arte recebida, Arte conferida and Correção - Números by date range, per machine, and orders apart from passages Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,7 +3,7 @@ import hashlib
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Literal
|
||||
from uuid import UUID
|
||||
|
||||
@@ -12,7 +12,7 @@ from fastapi.responses import RedirectResponse
|
||||
from pydantic import Field
|
||||
|
||||
from ..core import db
|
||||
from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, can, client_ip, operator,
|
||||
from ..core.auth import (COOKIE_SECURE, DESIGNER_STATES, DUMMY_PASSWORD_HASH, audit, can, client_ip, operator,
|
||||
login_failed, password_matches, throttle)
|
||||
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel
|
||||
from ..printjobs import queue as queue_print_files
|
||||
@@ -508,12 +508,19 @@ def cancel_order(uid: UUID, body: Resolution, user=Depends(can('manage'))):
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def designer_only(request, *states):
|
||||
"""A designer works on the artwork stages only: Arte recebida, Arte
|
||||
conferida and Correção. The queue onwards is the print room's."""
|
||||
if request.state.operator['role'] == 'designer' and not set(states) <= set(DESIGNER_STATES):
|
||||
raise HTTPException(403, 'O perfil Designer move pedidos só entre Arte recebida, Arte conferida e Correção.')
|
||||
|
||||
|
||||
class MachineChoice(StrictModel):
|
||||
machine_id: UUID | None = None
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/machine')
|
||||
def choose_machine(uid: UUID, body: MachineChoice, user=Depends(can('produce'))):
|
||||
def choose_machine(uid: UUID, body: MachineChoice, user=Depends(can('print'))):
|
||||
"""Send an order to a machine, or back to the automatic choice (None)."""
|
||||
with db.connect() as c:
|
||||
if body.machine_id and not c.execute('SELECT 1 FROM dtf_local.machines WHERE id=%s', (body.machine_id,)).fetchone():
|
||||
@@ -562,7 +569,7 @@ QUEUE_KEY = 'COALESCE(queue_key, extract(epoch FROM created_at))'
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/queue')
|
||||
def queue_place(uid: UUID, body: QueuePlace, user=Depends(can('produce'))):
|
||||
def queue_place(uid: UUID, body: QueuePlace, request: Request, user=Depends(can('produce'))):
|
||||
"""An order's place in its column: by default its payment time; dragged,
|
||||
halfway between the orders it was dropped between. It neither changes the
|
||||
order's stage nor counts as activity (the stalled clock keeps running)."""
|
||||
@@ -572,6 +579,7 @@ def queue_place(uid: UUID, body: QueuePlace, user=Depends(can('produce'))):
|
||||
row = c.execute('SELECT state FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Order not found')
|
||||
designer_only(request, row['state'])
|
||||
keys = {}
|
||||
for side in ('after', 'before'):
|
||||
other = getattr(body, side)
|
||||
@@ -592,7 +600,7 @@ def queue_place(uid: UUID, body: QueuePlace, user=Depends(can('produce'))):
|
||||
|
||||
|
||||
@router.post('/api/operator/orders/{uid}/move')
|
||||
def move(uid: UUID, body: Move, user=Depends(can('produce'))):
|
||||
def move(uid: UUID, body: Move, request: Request, user=Depends(can('produce'))):
|
||||
with db.connect() as c:
|
||||
row = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (uid,)).fetchone()
|
||||
if not row:
|
||||
@@ -603,6 +611,7 @@ def move(uid: UUID, body: Move, user=Depends(can('produce'))):
|
||||
raise HTTPException(409, 'Pedido cancelado.')
|
||||
if body.state == row['state']:
|
||||
return row
|
||||
designer_only(request, row['state'], body.state)
|
||||
back = BACK.get(row['state']) == body.state
|
||||
if body.state not in TRANSITIONS[row['state']] and not back:
|
||||
raise HTTPException(409, f"Não dá para ir de {STATES[row['state']]} para {STATES[body.state]}.")
|
||||
@@ -755,56 +764,121 @@ REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <>
|
||||
LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date"
|
||||
|
||||
|
||||
# Longest period one request may cover: a year and a day, for a year against the last.
|
||||
STATS_MAX_DAYS = 366
|
||||
|
||||
|
||||
def stats_period(days, start, end):
|
||||
"""The local days a request covers: the last `days`, or start to end."""
|
||||
today = datetime.now(timezone(timedelta(hours=-3))).date()
|
||||
if start is None and end is None:
|
||||
days = days or 30
|
||||
return today - timedelta(days=days - 1), today
|
||||
if start is None or end is None:
|
||||
raise HTTPException(422, 'Informe a data inicial e a final.')
|
||||
if start > end:
|
||||
raise HTTPException(422, 'A data inicial é depois da final.')
|
||||
if (end - start).days + 1 > STATS_MAX_DAYS:
|
||||
raise HTTPException(422, f'O período vai até {STATS_MAX_DAYS} dias.')
|
||||
return start, end
|
||||
|
||||
|
||||
@router.get('/api/operator/stats')
|
||||
def production_stats(days: int = Query(default=30, ge=7, le=365), user=Depends(operator)):
|
||||
def production_stats(days: int | None = Query(default=None, ge=7, le=365), start: date | None = None,
|
||||
end: date | None = None, user=Depends(operator)):
|
||||
"""Production numbers from what the board already records: orders paid in
|
||||
the period, how long each stage holds an order, and what is waiting now."""
|
||||
# From the start of the first local day of the period.
|
||||
since = ("o.created_at >= (((now() AT TIME ZONE 'America/Sao_Paulo')::date - make_interval(days => %s - 1))"
|
||||
" AT TIME ZONE 'America/Sao_Paulo')")
|
||||
the period, how long each stage holds an order, what each machine printed,
|
||||
and what is waiting now. The period is the last `days`, or start to end."""
|
||||
start, end = stats_period(days, start, end)
|
||||
period = (start, end)
|
||||
within = f"{LOCAL_DAY} BETWEEN %s AND %s"
|
||||
metres = "(SELECT COALESCE(sum((i->>'billed_metres')::numeric),0) FROM jsonb_array_elements(o.snapshot->'items') i)"
|
||||
with db.connect() as c:
|
||||
total = c.execute(f'''SELECT count(*) AS orders, COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents,
|
||||
COALESCE(sum({metres}),0) AS metres,
|
||||
count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.movements m WHERE m.order_id=o.id
|
||||
AND m.to_state='cor' AND NOT m.back)) AS corrected
|
||||
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {since}''', (days,)).fetchone()
|
||||
FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}''', period).fetchone()
|
||||
daily = {row['day']: row for row in c.execute(f'''SELECT {LOCAL_DAY} AS day, count(*) AS orders,
|
||||
COALESCE(sum({metres}),0) AS metres FROM dtf_local.orders o WHERE {REAL_ORDER} AND {since}
|
||||
GROUP BY 1''', (days,)).fetchall()}
|
||||
COALESCE(sum({metres}),0) AS metres FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}
|
||||
GROUP BY 1''', period).fetchall()}
|
||||
# Each order's stages as spans: from entering a stage to the next move.
|
||||
spans = f'''WITH events AS (
|
||||
SELECT o.id, 'rec' AS state, o.created_at AS at FROM dtf_local.orders o WHERE {REAL_ORDER} AND {since}
|
||||
SELECT o.id, 'rec' AS state, o.created_at AS at FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within}
|
||||
UNION ALL
|
||||
SELECT m.order_id, m.to_state, m.created_at FROM dtf_local.movements m
|
||||
JOIN dtf_local.orders o ON o.id=m.order_id WHERE {REAL_ORDER} AND {since})
|
||||
JOIN dtf_local.orders o ON o.id=m.order_id WHERE {REAL_ORDER} AND {within})
|
||||
SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events'''
|
||||
stages = c.execute(f'''SELECT state, count(*) AS orders,
|
||||
# Orders, not passages: an order sent back counts once, its passages apart.
|
||||
stages = c.execute(f'''SELECT state, count(DISTINCT id) AS orders, count(*) AS passages,
|
||||
percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM until-at)) / 3600 AS median_hours
|
||||
FROM ({spans}) s WHERE until IS NOT NULL GROUP BY state''', (days, days)).fetchall()
|
||||
FROM ({spans}) s WHERE until IS NOT NULL GROUP BY state''', period + period).fetchall()
|
||||
lead = c.execute(f'''SELECT count(*) AS orders, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM
|
||||
f.at - o.created_at)) / 3600 AS median_hours FROM dtf_local.orders o
|
||||
JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state='fin') f
|
||||
ON f.at IS NOT NULL
|
||||
WHERE {REAL_ORDER} AND {since}''', (days,)).fetchone()
|
||||
WHERE {REAL_ORDER} AND {within}''', period).fetchone()
|
||||
# What waits now, however old, and since when in its stage.
|
||||
waiting = c.execute(f'''SELECT o.state, count(*) AS orders, max(extract(epoch FROM now() - COALESCE(
|
||||
(SELECT max(m.created_at) FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state=o.state),
|
||||
o.created_at))) / 3600 AS oldest_hours
|
||||
FROM dtf_local.orders o WHERE {REAL_ORDER} AND o.state<>'fin' GROUP BY o.state''').fetchall()
|
||||
today = datetime.now(timezone(timedelta(hours=-3))).date()
|
||||
printed = machine_output(c, start, end)
|
||||
series = []
|
||||
for offset in range(days - 1, -1, -1):
|
||||
day = today - timedelta(days=offset)
|
||||
for offset in range((end - start).days + 1):
|
||||
day = start + timedelta(days=offset)
|
||||
row = daily.get(day)
|
||||
series.append({'day': day.isoformat(), 'orders': row['orders'] if row else 0,
|
||||
'metres': float(row['metres']) if row else 0.0})
|
||||
hours = lambda value: round(float(value), 1) if value is not None else None
|
||||
return {'days': days, 'orders': total['orders'], 'cents': int(total['cents']), 'metres': float(total['metres']),
|
||||
return {'days': len(series), 'start': start.isoformat(), 'end': end.isoformat(),
|
||||
'orders': total['orders'], 'cents': int(total['cents']), 'metres': float(total['metres']),
|
||||
'corrected': total['corrected'], 'daily': series,
|
||||
'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])},
|
||||
'stages': {row['state']: {'orders': row['orders'], '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}}
|
||||
'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}
|
||||
|
||||
|
||||
def machine_output(c, start, end):
|
||||
"""What each machine printed in the period: the orders that reached
|
||||
Finalizado then, on the machine they were on, their metres, the hours they
|
||||
spent in Imprimindo (so metres per hour is the machine's real pace, as the
|
||||
room moves the cards), when it last finished one, and what it has now."""
|
||||
metres = "(SELECT COALESCE(sum((i->>'billed_metres')::numeric),0) FROM jsonb_array_elements(o.snapshot->'items') i)"
|
||||
done = c.execute(f'''SELECT o.id, o.machine_id, {metres} AS metres, f.at
|
||||
FROM dtf_local.orders o
|
||||
JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m
|
||||
WHERE m.order_id=o.id AND m.to_state='fin') f ON f.at IS NOT NULL
|
||||
WHERE {REAL_ORDER} AND (f.at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s''',
|
||||
(start, end)).fetchall()
|
||||
ids = [row['id'] for row in done]
|
||||
printing = {row['id']: float(row['hours']) for row in c.execute('''WITH events AS (
|
||||
SELECT m.order_id AS id, m.to_state AS state, m.created_at AS at FROM dtf_local.movements m
|
||||
WHERE m.order_id=ANY(%s)),
|
||||
spans AS (SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events)
|
||||
SELECT id, sum(extract(epoch FROM until-at)) / 3600 AS hours FROM spans
|
||||
WHERE state='imp' AND until IS NOT NULL GROUP BY id''', (ids,)).fetchall()} if ids else {}
|
||||
last = {str(row['machine_id']): row['at'] for row in c.execute(f'''SELECT o.machine_id, max(m.created_at) AS at
|
||||
FROM dtf_local.orders o JOIN dtf_local.movements m ON m.order_id=o.id AND m.to_state='fin'
|
||||
WHERE {REAL_ORDER} AND o.machine_id IS NOT NULL GROUP BY o.machine_id''').fetchall()}
|
||||
result = []
|
||||
for m in machines.rows(c):
|
||||
mine = [row for row in done if str(row['machine_id'] or '') == m['id']]
|
||||
hours_in = sum(printing.get(row['id'], 0.0) for row in mine)
|
||||
made = float(sum(row['metres'] for row in mine))
|
||||
result.append({'id': m['id'], 'name': m['name'], 'active': m['active'], 'orders': len(mine),
|
||||
'metres': made, 'printing_hours': round(hours_in, 2),
|
||||
'metres_per_hour': round(made / hours_in, 1) if hours_in > 0 else None,
|
||||
'last_finished': last[m['id']].isoformat() if m['id'] in last else None,
|
||||
'now': {state: m['states'].get(state, 0) for state in ('fil', 'imp')}})
|
||||
loose = [row for row in done if row['machine_id'] is None]
|
||||
if loose:
|
||||
result.append({'id': None, 'name': 'Sem máquina', 'active': True, 'orders': len(loose),
|
||||
'metres': float(sum(row['metres'] for row in loose)), 'printing_hours': None,
|
||||
'metres_per_hour': None, 'last_finished': None, 'now': {}})
|
||||
return result
|
||||
|
||||
|
||||
def named_files(rows):
|
||||
@@ -854,7 +928,7 @@ def print_ready(c, request, states):
|
||||
|
||||
|
||||
@router.get('/api/operator/queue/finals')
|
||||
def queue_finals(request: Request, auto: bool = False, user=Depends(can('produce'))):
|
||||
def queue_finals(request: Request, auto: bool = False, user=Depends(can('print'))):
|
||||
"""The approved final files of every order in the print queue. The browser
|
||||
downloads them straight from storage: a zip of multi-GB sheets would go
|
||||
through the server."""
|
||||
@@ -872,7 +946,7 @@ class FolderSync(StrictModel):
|
||||
|
||||
|
||||
@router.post('/api/operator/queue/folder')
|
||||
def queue_folder(body: FolderSync, request: Request, user=Depends(can('produce'))):
|
||||
def queue_folder(body: FolderSync, request: Request, user=Depends(can('print'))):
|
||||
"""What the Kanban's automatic folder should hold. Early, it also gets the
|
||||
files of orders just received (to a "Recebidos" folder), so a large sheet is
|
||||
already on the computer when the order reaches the queue. `states` answers
|
||||
|
||||
Reference in New Issue
Block a user