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);

View File

@@ -451,8 +451,10 @@ Still to do (2026-10-26):
- Still open from the internal rules (docs received 2026-10-26): file type by
its first bytes (D-13), every order's origin and a manual order entry in
the Kanban (D-21, D-35; also how orders paid with credit come in), the
rework register (D-02 to D-04), and Aguardando contato time out of the time
figures (D-38).
and the rework register (D-02 to D-04). Done 2026-10-27: the folders catch
up on what passed while the Kanban computer was off, and 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).
- Settled on 2026-10-26: the DTF SITE category (986932924, CATEGORY in app/tiny.py),
the white spot also under the print PDF's footer (nothing to change here),
and the montador's order format (customer, files, product, the batch with

View File

@@ -157,6 +157,13 @@ def run():
day = client.call(f'/operator/stats?start={alone}&end={alone}', operator=True)
assert day['stages']['tra'] == {'orders': 1, 'passages': 2, 'median_hours': 2.0}, day['stages']
assert day['stages']['rec']['median_hours'] == 1.0, day['stages']
# Half an hour of it waiting for the customer does not count (D-38).
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.contact_waits(order_id, started_at, ended_at)
VALUES(%s, %s::timestamptz, %s::timestamptz)''', (order_id, f'{alone} 09:15-03', f'{alone} 09:45-03'))
day = client.call(f'/operator/stats?start={alone}&end={alone}', operator=True)
assert day['stages']['tra']['median_hours'] == 1.5, day['stages']
assert day['stages']['rec']['median_hours'] == 1.0, day['stages']
# The company's name from the registry: on the board, and found by the search.
from app import cnpj as registry

View File

@@ -63,6 +63,11 @@ def run():
client.call(f'/operator/orders/{paid_order}/contact', {'waiting': False}, operator=True)
cleared = {o['id']: o for o in client.call('/operator/board', operator=True)['orders']}[str(paid_order)]
assert cleared['contact_since'] is None and cleared['contact_note'] is None
# The wait is kept, from mark to clear, for the time figures that leave it out (D-38).
with db.connect() as c:
waits = c.execute('SELECT started_at, ended_at FROM dtf_local.contact_waits WHERE order_id=%s',
(paid_order,)).fetchall()
assert len(waits) == 1 and waits[0]['ended_at'] and waits[0]['ended_at'] >= waits[0]['started_at'], waits
# A paid order is cancelled with a reason, kept, and can no longer move.
# A paid order in progress is not deleted: it is cancelled first.

View File

@@ -98,7 +98,7 @@
<p class="faint stats-hint">Pedidos do período em que o arquivo final aprovado não é a arte do cliente: alguém da equipe preparou. Por quem aprovou o arquivo.</p>
<table class="log"><thead><tr><th scope="col">Quem aprovou</th><th scope="col">Pedidos</th></tr></thead><tbody id="stats-treated"></tbody></table></section>
<section class="statbox"><h2>Tempo em cada etapa</h2>
<p class="faint stats-hint">Tempo mediano por pedido: um pedido que voltou para a etapa soma o tempo de cada passagem.</p>
<p class="faint stats-hint">Tempo mediano por pedido: um pedido que voltou para a etapa soma o tempo de cada passagem. O tempo em Aguardando contato não conta, aqui nem em “Do pagamento ao Finalizado”.</p>
<table class="log"><thead><tr><th scope="col">Etapa</th><th scope="col">Tempo mediano</th><th scope="col">Pedidos que passaram</th><th scope="col">Agora</th></tr></thead><tbody id="stats-stages"></tbody></table>
</section>
</section>