feat: time in "Aguardando contato" no longer counts in Números (Dropstar's rule D-38)
All checks were successful
Build and deploy / Validate source (push) Successful in 4s
Build and deploy / Integration suite on a real stack (push) Successful in 3m20s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m0s

Dropstar's internal rules (2026-10-26): waiting for a word with the customer
has no deadline and does not enter the time figures.

- each wait is kept, from the mark to "Contato feito" (and from checkout when
  the customer asks for a proof), in a new table; waits open today are
  recorded from their start
- the time in each stage and "Do pagamento ao Finalizado" leave those waits
  out, and the Números page says so

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-27 10:45:14 -03:00
parent 6a921415ea
commit 494925dff4
7 changed files with 48 additions and 5 deletions

View File

@@ -562,6 +562,10 @@ def contact(uid: UUID, body: ContactWait, user=Depends(can('produce'))):
(body.waiting, body.waiting, user, body.waiting, note, uid)).fetchone()
if not row:
raise HTTPException(404, 'Pedido não encontrado.')
# The wait's history, for the time figures that leave it out (D-38).
c.execute('UPDATE dtf_local.contact_waits SET ended_at=now() WHERE order_id=%s AND ended_at IS NULL', (uid,))
if body.waiting:
c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (uid,))
audit('order_contact_waiting' if body.waiting else 'order_contact_done', order=row['number'], operator=user)
return {'ok': True}
@@ -794,6 +798,15 @@ REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <>
LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date"
def waited(order, start, end):
"""SQL: the seconds `order` spent in "Aguardando contato" between `start`
and `end`. Dropstar's rule D-38: that wait has no deadline and does not
count in the time figures."""
return f'''COALESCE((SELECT sum(extract(epoch FROM least({end}, COALESCE(w.ended_at, now()))
- greatest({start}, w.started_at))) FROM dtf_local.contact_waits w
WHERE w.order_id={order} AND w.started_at<{end} AND COALESCE(w.ended_at, now())>{start}), 0)'''
# Longest period one request may cover: a year and a day, for a year against the last.
STATS_MAX_DAYS = 366
@@ -844,11 +857,12 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
# that came back twice reads as three quick passages, not one slow order.
stages = c.execute(f'''SELECT state, count(*) AS orders, sum(passages)::int AS passages,
percentile_cont(0.5) WITHIN GROUP (ORDER BY seconds) / 3600 AS median_hours
FROM (SELECT id, state, count(*) AS passages, sum(extract(epoch FROM until-at)) AS seconds
FROM (SELECT id, state, count(*) AS passages,
sum(extract(epoch FROM until-at) - {waited('s.id', 's.at', 's.until')}) AS seconds
FROM ({spans}) s WHERE until IS NOT NULL GROUP BY id, state) per_order
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
f.at - o.created_at) - {waited('o.id', 'o.created_at', 'f.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 {within}''', period).fetchone()

View File

@@ -102,6 +102,7 @@ def create_order(c, quote, payment):
# The customer asked for a proof: the order waits for their word.
order = c.execute('''UPDATE dtf_local.orders SET contact_since=now(), contact_by='Site', contact_note=%s
WHERE id=%s RETURNING *''', (proof.CUSTOMER_NOTE, order['id'])).fetchone()
c.execute('INSERT INTO dtf_local.contact_waits(order_id, started_at) VALUES(%s, now())', (order['id'],))
machines.route(c)
if is_test(order):
return order, True

View File

@@ -358,3 +358,17 @@ WITH moved AS (UPDATE dtf_local.orders SET state='tra', version=version+1, updat
WHERE state='fil' RETURNING id)
INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
SELECT id,'fil','tra','sistema','A Fila de impressão saiu do quadro: Arte conferida é a fila.' FROM moved;
-- Each time an order waited for a word with the customer ("Aguardando
-- contato"): that wait has no deadline and does not count in the time figures
-- of Números (Dropstar's rule D-38, 2026-10-26). An open wait has no end. The
-- waits already open when this table came are recorded from their start.
CREATE TABLE IF NOT EXISTS dtf_local.contact_waits (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
started_at timestamptz NOT NULL, ended_at timestamptz
);
CREATE INDEX IF NOT EXISTS contact_waits_order ON dtf_local.contact_waits(order_id);
INSERT INTO dtf_local.contact_waits(order_id, started_at)
SELECT o.id, o.contact_since FROM dtf_local.orders o
WHERE o.contact_since IS NOT NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.contact_waits w WHERE w.order_id=o.id);