diff --git a/app/api/operator.py b/app/api/operator.py index 6b53be7..aa34e5d 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -795,6 +795,8 @@ def thumbnail(uid: UUID, user=Depends(operator)): # Real work only: an operator's test order and a cancelled one are not production. REAL_ORDER = "o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste'" +# Where orders come from (D-21), in the order Números lists them. +ORIGINS = ('site', 'dropflow', 'atendimento') LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date" @@ -881,6 +883,16 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start treated_orders = c.execute(f'''SELECT count(DISTINCT f.order_id) AS n FROM dtf_local.order_files f JOIN dtf_local.orders o ON o.id=f.order_id WHERE {REAL_ORDER} AND {within} AND {TREATED}''', period).fetchone()['n'] + # Each way in apart (D-21): what came from where, and how long it took + # from payment to Finalizado, Aguardando contato left out as above. + origins = {row['origin']: row for row in c.execute(f'''SELECT o.origin, count(*) AS orders, + COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents, COALESCE(sum({metres}),0) AS metres, + count(f.at) AS finished, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM + f.at - o.created_at) - {waited('o.id', 'o.created_at', 'f.at')}) / 3600 AS median_hours + FROM dtf_local.orders o + LEFT 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 true + WHERE {REAL_ORDER} AND {within} GROUP BY o.origin''', period).fetchall()} series = [] for offset in range((end - start).days + 1): day = start + timedelta(days=offset) @@ -892,6 +904,12 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start 'orders': total['orders'], 'cents': int(total['cents']), 'metres': float(total['metres']), 'corrected': total['corrected'], 'daily': series, 'treated': {'orders': treated_orders, 'by': [{'who': row['who'], 'orders': row['orders']} for row in treated]}, + 'origins': [{'origin': name, 'orders': origins[name]['orders'] if name in origins else 0, + 'cents': int(origins[name]['cents']) if name in origins else 0, + 'metres': float(origins[name]['metres']) if name in origins else 0.0, + 'finished': origins[name]['finished'] if name in origins else 0, + 'median_hours': hours(origins[name]['median_hours']) if name in origins else None} + for name in ORIGINS], 'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])}, 'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'], 'median_hours': hours(row['median_hours'])} for row in stages}, diff --git a/app/payments.py b/app/payments.py index 5cf1541..f6ec54d 100644 --- a/app/payments.py +++ b/app/payments.py @@ -92,7 +92,8 @@ def create_order(c, quote, payment): require_clean(upload_row(c, UUID(upload_id), quote['owner'])) order = c.execute( - 'INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s) RETURNING *', + '''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) + VALUES(%s,%s,%s,%s,%s,'site') RETURNING *''', (uuid4(), quote['id'], quote['owner'], Jsonb(approved), Jsonb(payment))).fetchone() # Paid: the files are kept for the order's retention, counted from upload. c.execute('''UPDATE dtf_local.uploads SET expires_at=GREATEST(expires_at, created_at+%s::interval) diff --git a/app/schema.sql b/app/schema.sql index b235254..1e37f1f 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -372,3 +372,14 @@ CREATE INDEX IF NOT EXISTS contact_waits_order ON dtf_local.contact_waits(order_ 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); + +-- Every card is born with its origin (Dropstar's rules D-21 and D-35, +-- 2026-10-26): site, dropflow (the montador's batches) or atendimento (an +-- order the team enters). No order without one, and no default: a default +-- would become the origin of almost everything, so each way in names its own. +-- The orders from before this column all came from the Site. +ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS origin text; +UPDATE dtf_local.orders SET origin='site' WHERE origin IS NULL; +ALTER TABLE dtf_local.orders ALTER COLUMN origin SET NOT NULL; +ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check; +ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento')); diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 4723fe3..147d400 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -462,9 +462,24 @@ Still to do (2026-10-26): money stays as the customer's credit in their financial control (D-15, the Kanban's cancel text says so, nothing on the Site); the Kanban keeps deleting Finalizado files after 30 days; the footer gets the white spot. -- Still open from the internal rules (docs received 2026-10-26): every - order's origin and a manual order entry in the Kanban (D-21, D-35; also how - orders paid with credit come in), and the rework register (D-02 to D-04). +- Every order has an origin (Dropstar's rules D-21 and D-35, 2026-10-26): + `site`, `dropflow` or `atendimento`, in dtf_local.orders.origin, required + and without a default (a default would become the origin of almost + everything, the document says), limited to the three by a check. The Site's + orders are marked `site` where they are created (app/payments.py); the + orders from before the column became `site`. The Kanban shows it on every + card and in the order panel, filters by it (Origem), and Números has a "Por + origem" table: orders, metres, money received and the median time from + payment to Finalizado for each way in, Aguardando contato left out. +- Still open from the internal rules (docs received 2026-10-26): the manual + order entry in the Kanban, where the origin must be chosen (D-35; also how + orders paid with credit come in, and the Dropflow batches until their API), + the Tiny revenue category for Dropflow orders (not DTF SITE; its name and + the origin value must be the same word, the document says), and the rework + register (D-02 to D-04: four causes, falha de impressão, perfil de cor, + erro de tratamento and erro de pedido; opened and classified by Mayana, + authorized by Thales or Alexandre, locked once opened; bad art the customer + approved does not count; goal 0,4% per cause, 1,6% in all). Done 2026-10-27: the folders catch up on what passed while the Kanban computer was off, 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 diff --git a/tests/kanban_test.py b/tests/kanban_test.py index b21c364..5bd1a1f 100644 --- a/tests/kanban_test.py +++ b/tests/kanban_test.py @@ -11,6 +11,7 @@ from urllib.request import Request from uuid import uuid4 import httpx +import psycopg from psycopg.types.json import Jsonb from app.core import db @@ -81,8 +82,8 @@ def run(): c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved) VALUES(%s,%s,%s,%s,%s,%s)''', (qid, owner, uuid4(), 'kanban-fixture', Jsonb(content), Jsonb(accepted) if accepted else None)) - number = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) - VALUES(%s,%s,%s,%s,%s) RETURNING number''', + number = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) + VALUES(%s,%s,%s,%s,%s,'site') RETURNING number''', (order_id, paid, owner, Jsonb({**draft(item('file')), 'total_cents': 1490}), Jsonb({'provider': 'teste', 'id': f'kanban-{tag}'}))).fetchone()['number'] @@ -126,6 +127,20 @@ def run(): assert (after['orders'], after['cents']) == (before['orders'] + 1, before['cents'] + 1490), (before, after) assert after['daily'][-1]['orders'] == before['daily'][-1]['orders'] + 1 assert after['waiting']['rec']['orders'] == before.get('waiting', {}).get('rec', {}).get('orders', 0) + 1 + # Each way in apart (D-21), all three listed even when empty. + assert [o['origin'] for o in after['origins']] == ['site', 'dropflow', 'atendimento'] + site = lambda stats: next(o for o in stats['origins'] if o['origin'] == 'site') + assert (site(after)['orders'], site(after)['cents']) == (site(before)['orders'] + 1, site(before)['cents'] + 1490) + # No order without an origin, and only the three (D-21, D-35). + for origin in (None, 'whatsapp'): + try: + with db.connect() as c: + c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) + VALUES(%s,%s,%s,'{}','{}',%s)''', (uuid4(), approved, owner, origin)) + except (psycopg.errors.NotNullViolation, psycopg.errors.CheckViolation): + pass + else: + raise AssertionError(f'an order with origin {origin!r} was accepted') client.call('/operator/stats?days=3', operator=True, expected=422) # Or two dates: the same week asked as a range gives the same numbers. week = client.call(f"/operator/stats?start={after['start']}&end={after['end']}", operator=True) diff --git a/tests/launch_reset_test.py b/tests/launch_reset_test.py index b66aa00..069dc6d 100644 --- a/tests/launch_reset_test.py +++ b/tests/launch_reset_test.py @@ -17,7 +17,7 @@ def run(): c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) VALUES(%s,%s,%s,'reset-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb({'customer': {}, 'items': []}), Jsonb({'items': [], 'total_cents': 1490}))) - c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)', + c.execute("INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')", (order, quote, owner, Jsonb({'items': [], 'total_cents': 1490}), Jsonb({'provider': 'teste'}))) live = c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method, status,amount_cents,response) VALUES(%s,%s,'mercadopago',%s,'card','approved',1490,%s) RETURNING id''', @@ -52,8 +52,8 @@ def run(): c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) VALUES(%s,%s,%s,'reset-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb({'customer': {}, 'items': []}), Jsonb({'items': [], 'total_cents': 1490}))) - first = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) - VALUES(%s,%s,%s,%s,%s) RETURNING number''', (uuid4(), quote, owner, Jsonb({'items': []}), + first = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) + VALUES(%s,%s,%s,%s,%s,'site') RETURNING number''', (uuid4(), quote, owner, Jsonb({'items': []}), Jsonb({'provider': 'teste'}))).fetchone()['number'] assert first == 1, first c.execute('DELETE FROM dtf_local.orders WHERE quote_id=%s', (quote,)) diff --git a/tests/order_actions_test.py b/tests/order_actions_test.py index 2394ae3..fb60f87 100644 --- a/tests/order_actions_test.py +++ b/tests/order_actions_test.py @@ -27,7 +27,7 @@ def run(): c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) VALUES(%s,%s,%s,'actions-fixture',%s,%s,now())''', (qid, owner, uuid4(), Jsonb({'customer': {'mail': mail}, 'items': []}), Jsonb(approved))) - c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)''', + c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')''', (paid_order, paid_quote, owner, Jsonb(approved), Jsonb({'provider': 'mercadopago', 'id': '1'}))) listed = lambda: {q['id'] for q in client.call('/operator/quotes?' + urlencode({'kind': 'approved', 'q': mail}), operator=True)['quotes']} @@ -94,8 +94,8 @@ def run(): # Dragged within its column: first paid first, unless moved; moving on resets it. with db.connect() as c: c.execute("UPDATE dtf_local.orders SET created_at=now()-interval '1 hour' WHERE id=%s", (paid_order,)) - c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,created_at) - VALUES(%s,%s,%s,%s,%s,now())''', (newer_order, newer_quote, owner, Jsonb(approved), + c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,created_at,origin) + VALUES(%s,%s,%s,%s,%s,now(),'site')''', (newer_order, newer_quote, owner, Jsonb(approved), Jsonb({'provider': 'teste', 'id': 't'}))) client.call(f'/operator/orders/{newer_order}/queue', {'before': str(paid_order)}, operator=True) with db.connect() as c: @@ -129,8 +129,8 @@ def run(): 'total_cents': 1490} c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) VALUES(%s,%s,%s,'actions-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb(content), Jsonb(content))) - c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,cancelled_at,cancelled_by,cancel_reason) - VALUES(%s,%s,%s,%s,%s,%s,%s,%s)''', (order, quote, owner, Jsonb(content), Jsonb({'provider': provider, 'id': '1'}), + c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,cancelled_at,cancelled_by,cancel_reason,origin) + VALUES(%s,%s,%s,%s,%s,%s,%s,%s,'site')''', (order, quote, owner, Jsonb(content), Jsonb({'provider': provider, 'id': '1'}), 'now()' if cancelled else None, 'x' if cancelled else None, 'teste' if cancelled else None)) place(gone_quote, gone_order, [files['original'], files['shared']], 'mercadopago', True) diff --git a/tests/thumbnail_backfill_test.py b/tests/thumbnail_backfill_test.py index e810cfe..ce1d72d 100644 --- a/tests/thumbnail_backfill_test.py +++ b/tests/thumbnail_backfill_test.py @@ -44,7 +44,7 @@ def run(): items = [{'mode': 'file', 'uploads': [str(image), str(drawing)]}] c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft) VALUES(%s,%s,%s,'backfill-fixture',%s)''', (quote, owner, uuid4(), Jsonb({'items': items}))) - c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)', + c.execute("INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')", (order, quote, owner, Jsonb({'items': items, 'total_cents': 1490}), Jsonb({'provider': 'teste'}))) lines = [] assert backfill_thumbnails.main([], out=lines.append, storage=storage) == 0 diff --git a/tests/users_test.py b/tests/users_test.py index 1f308f4..788d785 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -34,7 +34,7 @@ def order_fixture(c, owner, mode, metres='1', printed=None): 'items': [item], 'freight': {'service': 'pickup'}, 'total_cents': 1490} c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) VALUES(%s,%s,%s,'users-fixture',%s,%s,now())''', (quote, owner, uuid4(), Jsonb(content), Jsonb(content))) - c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)', + c.execute("INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site')", (order, quote, owner, Jsonb(content), Jsonb({'provider': 'teste', 'id': str(order)}))) return quote, order diff --git a/tests/workflow_test.py b/tests/workflow_test.py index 45c1787..4cec67c 100644 --- a/tests/workflow_test.py +++ b/tests/workflow_test.py @@ -12,6 +12,8 @@ def run(): q=customer.call('/quotes',{'request_key':str(uuid4()),'customer':profile,'items':[item],'freight':{'service':'pickup'}}) approved_quote(customer,q,[item]) order=customer.call('/orders/dev-paid',{'quote_id':q['id']});oid=order['id'] + # A Site order is born marked as one (Dropstar's rule D-21). + assert next(o for o in customer.call('/operator/board',operator=True)['orders'] if o['id']==oid)['origin']=='site' before=list(customer.jar)[0].value password='local-test-password-'+uuid4().hex register(customer,profile,password) diff --git a/web/kanban.css b/web/kanban.css index 2ed426c..ccc98ff 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -129,6 +129,7 @@ main{padding:0 24px 24px} .card .num{font-size:14.5px;font-weight:800} .card .age{margin-left:auto;font-size:13.5px;color:var(--faint)} .card .cust{font-size:14px;font-weight:600;color:var(--tx);width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.origin{font-size:12px;font-weight:700;padding:1px 7px;border-radius:6px;border:1px solid var(--line3);color:var(--muted)} .tag-teste{font-size:12.5px;font-weight:800;letter-spacing:.04em;padding:2px 7px;border-radius:6px;background:var(--warn);color:#1a1300} .late{font-size:13.5px;color:#F06A5B;font-weight:600} diff --git a/web/kanban.html b/web/kanban.html index d2fe08c..297dc03 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -94,6 +94,9 @@ Metros por hora: sobre o tempo em Imprimindo; pedidos imprimindo juntos na mesma máquina contam esse tempo uma vez.
| Máquina | Impresso | Metros por hora | Último finalizado | Agora |
|---|
Por onde o pedido entrou: o Site, os lotes do Dropflow ou a equipe, em Atendimento. O tempo vai do pagamento ao Finalizado, sem o tempo em Aguardando contato.
+| Origem | Pedidos | Metros | Recebido | Do pagamento ao Finalizado |
|---|
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 aprovou | Pedidos |
|---|