From 494925dff46e2d856c076666efc392b8e5e31023 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Tue, 27 Oct 2026 10:45:14 -0300 Subject: [PATCH] =?UTF-8?q?feat:=20time=20in=20"Aguardando=20contato"=20no?= =?UTF-8?q?=20longer=20counts=20in=20N=C3=BAmeros=20(Dropstar's=20rule=20D?= =?UTF-8?q?-38)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- app/api/operator.py | 18 ++++++++++++++++-- app/payments.py | 1 + app/schema.sql | 14 ++++++++++++++ docs/CONTEXT.md | 6 ++++-- tests/kanban_test.py | 7 +++++++ tests/order_actions_test.py | 5 +++++ web/kanban.html | 2 +- 7 files changed, 48 insertions(+), 5 deletions(-) diff --git a/app/api/operator.py b/app/api/operator.py index a9d5dae..6b53be7 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -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() diff --git a/app/payments.py b/app/payments.py index 81bc07b..5cf1541 100644 --- a/app/payments.py +++ b/app/payments.py @@ -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 diff --git a/app/schema.sql b/app/schema.sql index 336c60b..b235254 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -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); diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 4672921..5ca46bf 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -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 diff --git a/tests/kanban_test.py b/tests/kanban_test.py index 4a82868..b21c364 100644 --- a/tests/kanban_test.py +++ b/tests/kanban_test.py @@ -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 diff --git a/tests/order_actions_test.py b/tests/order_actions_test.py index 19f65f6..2394ae3 100644 --- a/tests/order_actions_test.py +++ b/tests/order_actions_test.py @@ -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. diff --git a/web/kanban.html b/web/kanban.html index 40bf234..d2fe08c 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -98,7 +98,7 @@

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.

Quem aprovouPedidos

Tempo em cada etapa

-

Tempo mediano por pedido: um pedido que voltou para a etapa soma o tempo de cada passagem.

+

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”.

EtapaTempo medianoPedidos que passaramAgora