feat: an approved order nobody paid expires in 24 h (front 9)
All checks were successful
Build and deploy / Validate source (push) Successful in 1m15s
Build and deploy / Integration suite on a real stack (push) Successful in 5m10s
Build and deploy / Secret scan and release gate (push) Successful in 11s
Build and deploy / Publish images (push) Successful in 1m29s

An approved quote with no payment expires on its own after 24 h, never
while a Pix or card attempt is still live: the worker marks
quotes.expired_at, frees its files and e-mails the customer that the
order expired and can be sent again on the Site. The backlog from before
this front expires silently.

Kanban: Cotações › Aguardando pagamento shows when each one expires and
the review gets an "Abrir conversa" WhatsApp button; Números gets
"Pedidos sem pagamento" (made, paid, expired, waiting, abandonment rate).

release_files moves to app/payments.py so the worker can use it; an
expired quote no longer counts as open there. New tests/unpaid_test.py
in the integration job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 10:01:26 -03:00
parent 448a7fa8c3
commit 1a9611942d
11 changed files with 269 additions and 32 deletions

View File

@@ -73,7 +73,7 @@ jobs:
# one a developer exercises on localhost.
- name: API and workflow regressions
run: |
for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test; do
for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test; do
echo "--- $suite"
$COMPOSE exec -T \
-e SITE_BASE_URL=http://site \

View File

@@ -18,8 +18,9 @@ from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, MOVERS, audit, can,
login_failed, may_move, may_reorder, password_matches, throttle)
from ..core.models import Contraction, Move, OperatorLogin, Resolution, Review, StrictModel, UploadStart
from ..printjobs import CLAIM_TIMEOUT, file_prefix, queue as queue_print_files
from .. import cnpj, hotfolder, machines, mail, payments, proof, prumo, quote_review, receipt
from .. import cnpj, hotfolder, machines, mail, payments, proof, prumo, quote_review, receipt, unpaid
from .. import tiny
from ..payments import release_files
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES,
TRANSITIONS, payment, enqueue, freight, operator_identity, quote_view, quote_views, storage, upload_row)
from .uploads import begin_upload
@@ -27,10 +28,10 @@ from ..scanning import require_clean
router = APIRouter()
# A quote that can still become an order: waiting for review, or approved within
# the payment window. Expired ones leave the Kanban; they can never be paid.
LIVE_QUOTE = (f"(q.discarded_at IS NULL AND (q.approved_at IS NULL OR "
f"q.approved_at > now() - interval '{int(payments.QUOTE_VALID_HOURS)} hours'))")
# A quote that can still become an order: waiting for review, or approved and
# not expired yet. The worker marks it expired at 24 h (app/unpaid.py); until
# then it stays, even past the payment window while an attempt is still live.
LIVE_QUOTE = "(q.discarded_at IS NULL AND q.expired_at IS NULL)"
@router.post('/api/operator/login')
def operator_login(body: OperatorLogin, request: Request, response: Response):
@@ -723,28 +724,6 @@ def delete_order(uid: UUID, user=Depends(can('manage'))):
return {'ok': True}
def release_files(c, uploads):
"""Expire these uploads now, except any another order or an open quote
still uses: a customer can buy the same file again. Returns how many."""
free = []
for upload in uploads:
used = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.print_files WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.print_parts WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i
WHERE i->'uploads' ? %s
UNION ALL SELECT 1 FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i
WHERE q.discarded_at IS NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.orders x WHERE x.quote_id=q.id)
AND i->'uploads' ? %s
LIMIT 1''', (upload,) * 5).fetchone()
if not used:
free.append(upload)
if free:
c.execute('''UPDATE dtf_local.uploads SET expires_at=now() WHERE id=ANY(%s::uuid[])
AND purged_at IS NULL''', (free,))
return len(free)
@router.post('/api/operator/orders/{uid}/cancel')
def cancel_order(uid: UUID, body: Resolution, user=Depends(can('cancel'))):
"""A paid order leaves the board but keeps its payment and history. Nothing
@@ -1414,6 +1393,8 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
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 {within}''', period).fetchone()
# Approved quotes of the period nobody paid (front 9).
unpaid_figures = unpaid.figures(c, start, end)
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 {within}
GROUP BY 1''', period).fetchall()}
@@ -1553,6 +1534,7 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
'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],
'unpaid': unpaid_figures,
'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])},
'stage_limits': limits, 'late': late,
'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'],

View File

@@ -92,6 +92,29 @@ PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · ar
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
def quote_expired(c, quote, origin):
"""The customer's notice that an approved, unpaid order expired after 24 h
(Fase 2, front 9): its files were deleted and they can send it again on
the Site. Returns whether it was queued (False without an e-mail)."""
customer = (quote.get('draft') or {}).get('customer') or {}
if not customer.get('mail'):
return False
from . import mail_html
link = f'{origin}/'
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
'Seu pedido não foi pago em 24 horas e expirou. Os arquivos que você enviou foram apagados.', '',
f'Quando quiser, é só montar de novo no site: {link}'])
html = mail_html.layout('Seu pedido não foi pago em 24 horas e expirou.', 'Seu pedido', [
mail_html.pill('Pedido expirado', 'info'),
mail_html.title('Seu pedido expirou'),
mail_html.para(f'{mail_html.greeting(customer.get("name"))} Seu pedido não foi pago em 24 horas e '
'expirou. Os arquivos que você enviou foram apagados.'),
mail_html.button('Montar de novo', link),
mail_html.small(f'Quando quiser, é só montar de novo no site: {link}'),
])
return queue(c, 'notice', customer['mail'], 'Seu pedido expirou · DTF Dropstar', text, html)
def money(cents):
whole, cents = divmod(int(cents), 100)
return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}'

View File

@@ -89,6 +89,29 @@ def hold_uploads(c, upload_ids, interval):
WHERE id=ANY(%s) AND purged_at IS NULL''', (interval, [str(u) for u in upload_ids]))
def release_files(c, uploads):
"""Expire these uploads now, except any another order or an open quote
still uses: a customer can buy the same file again. Returns how many."""
free = []
for upload in uploads:
used = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.print_files WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.print_parts WHERE upload_id=%s
UNION ALL SELECT 1 FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i
WHERE i->'uploads' ? %s
UNION ALL SELECT 1 FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i
WHERE q.discarded_at IS NULL AND q.expired_at IS NULL
AND NOT EXISTS (SELECT 1 FROM dtf_local.orders x WHERE x.quote_id=q.id)
AND i->'uploads' ? %s
LIMIT 1''', (upload,) * 5).fetchone()
if not used:
free.append(upload)
if free:
c.execute('''UPDATE dtf_local.uploads SET expires_at=now() WHERE id=ANY(%s::uuid[])
AND purged_at IS NULL''', (free,))
return len(free)
def create_order(c, quote, payment, origin):
"""Create the order for a reviewed quote, or return the one already there.
`origin` is where it came from (D-21): each way in names its own.

View File

@@ -122,6 +122,7 @@ def quote_views(c, rows):
def quote_view(c, row, order=None, attempt=None, known=False):
from .quote_review import review_reason # it imports this module
from .payments import QUOTE_VALID_HOURS # it imports this module too
if not known:
order = c.execute('SELECT id,number,state FROM dtf_local.orders WHERE quote_id=%s', (row['id'],)).fetchone()
# The latest payment attempt, so the payment page can tell a refused card
@@ -133,13 +134,19 @@ def quote_view(c, row, order=None, attempt=None, known=False):
if attempt and attempt['status'] == 'rejected':
from .payment_messages import rejection
attempt = {**attempt, 'message': rejection(attempt['status_detail'])}
expired = row['approved_at'] and row['approved_at'] < datetime.now(timezone.utc)-timedelta(hours=24)
expires_at = (row['approved_at'] + timedelta(hours=QUOTE_VALID_HOURS)
if row['approved_at'] else None)
expired = (bool(row.get('expired_at')) or
bool(row['approved_at'] and row['approved_at'] <
datetime.now(timezone.utc)-timedelta(hours=QUOTE_VALID_HOURS)))
items = (row['approved'] or row['draft']).get('items') or []
treatment = (row['approved'] or {}).get('treatment')
if not treatment and (row['draft'] or {}).get('treatment') and treatment_cents():
treatment = {'cents': treatment_cents(), 'hours': 24}
return {'id': row['id'], 'created_at': row['created_at'],
'draft': row['draft'], 'approved': row['approved'],
'expires_at': expires_at.isoformat() if expires_at else None,
'expired_at': row['expired_at'].isoformat() if row.get('expired_at') else None,
'prumo': prumo.customer_summary(items), 'treatment': treatment,
'status': 'paid' if order else 'discarded' if row.get('discarded_at') else 'expired' if expired
else 'approved' if row['approved'] else 'pending_review',

View File

@@ -528,3 +528,6 @@ ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS seen_at timesta
-- The machine of whoever moved a card, as it was named then: "Imprimindo ·
-- Thales · máquina2".
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS machine text;
-- An approved quote nobody paid in 24 h expires (Fase 2, front 9, app/unpaid.py).
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS expired_at timestamptz;

72
app/unpaid.py Normal file
View File

@@ -0,0 +1,72 @@
"""Orders made on the Site and never paid (Dropstar's Fase 2, front 9, 05/11/2026).
An approved quote is an order the customer did not pay yet: Kanban's
Cotações › "Aguardando pagamento" lists it, with how long ago it came and
when it expires, so the seller can charge it by WhatsApp. After
QUOTE_VALID_HOURS (24 h) without payment it expires on its own: its files
are freed for deletion and the customer gets an e-mail ("seu pedido expirou,
suba de novo quando quiser"). Never while a payment attempt is still live
(a Pix not yet expired, a card being processed), so a late payment always
finds its files. Números counts orders made, paid and expired, and the
abandonment rate.
"""
from datetime import datetime, timedelta, timezone
from . import mail, payments
from .payments import QUOTE_VALID_HOURS
# An intent in one of these no longer waits for money: approved (it became an
# order), rejected, cancelled, expired or refunded (app/payments.py).
FINAL_INTENT = ('approved', 'rejected', 'cancelled', 'expired', 'refunded')
def expire(c, origin):
"""Expire the approved, unpaid quotes past QUOTE_VALID_HOURS: set
quotes.expired_at, free their files (payments.release_files) and queue the
customer's e-mail (mail.quote_expired). Returns how many expired."""
rows = c.execute('''SELECT q.* FROM dtf_local.quotes q
WHERE q.approved IS NOT NULL AND q.discarded_at IS NULL AND q.expired_at IS NULL
AND q.approved_at <= now() - make_interval(hours => %s)
AND NOT EXISTS (SELECT 1 FROM dtf_local.orders o WHERE o.quote_id=q.id)
AND NOT EXISTS (
SELECT 1 FROM dtf_local.payment_intents i
WHERE i.quote_id=q.id
AND i.id = (SELECT i2.id FROM dtf_local.payment_intents i2
WHERE i2.quote_id=q.id ORDER BY i2.created_at DESC LIMIT 1)
AND i.status <> ALL(%s)
AND i.created_at > now() - make_interval(hours => %s)
AND (i.response->>'expires_at' IS NULL
OR (i.response->>'expires_at')::timestamptz > now()))
ORDER BY q.approved_at LIMIT 50 FOR UPDATE OF q SKIP LOCKED''',
(QUOTE_VALID_HOURS, list(FINAL_INTENT), QUOTE_VALID_HOURS + 1)).fetchall()
for row in rows:
c.execute('UPDATE dtf_local.quotes SET expired_at=now() WHERE id=%s', (row['id'],))
# expired_at is set first: release_files must no longer see this quote
# as open, or its own files would stay held.
payments.release_files(c, payments.quote_uploads(row['approved']))
# Only a quote that just ran out is news to the customer: the backlog
# from before this front existed expires silently on the first pass.
if row['approved_at'] > datetime.now(timezone.utc) - timedelta(hours=2 * QUOTE_VALID_HOURS):
mail.quote_expired(c, row, origin)
return len(rows)
def figures(c, start, end):
"""Números, for quotes approved between the local days `start` and `end`
(inclusive): {'made': n, 'paid': n, 'expired': n, 'waiting': n,
'abandon_pct': float | None}. Paid has an order; expired has expired_at;
waiting is neither yet. abandon_pct is expired / (paid + expired) * 100,
one decimal, None when both are 0."""
row = c.execute('''SELECT count(*) AS made,
count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.orders o WHERE o.quote_id=q.id)) AS paid,
count(*) FILTER (WHERE q.expired_at IS NOT NULL) AS expired,
count(*) FILTER (WHERE q.expired_at IS NULL
AND NOT EXISTS (SELECT 1 FROM dtf_local.orders o WHERE o.quote_id=q.id)) AS waiting
FROM dtf_local.quotes q
WHERE q.discarded_at IS NULL AND q.approved_at IS NOT NULL
AND (q.approved_at AT TIME ZONE 'America/Sao_Paulo')::date BETWEEN %s AND %s''',
(start, end)).fetchone()
paid, expired = row['paid'], row['expired']
decided = paid + expired
return {'made': row['made'], 'paid': paid, 'expired': expired, 'waiting': row['waiting'],
'abandon_pct': round(expired / decided * 100, 1) if decided else None}

View File

@@ -6,7 +6,7 @@ import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from psycopg.types.json import Jsonb
from . import mail
from . import mail, unpaid
from .adapters import FakeTiny, LocalS3Storage, require_runtime
from .core.secrets import load as load_secret_files
from .core.db import connect
@@ -121,6 +121,9 @@ def loop():
tick()
if time.monotonic()-last_cleanup > 60:
cleanup()
# Approved quotes unpaid for 24 h expire on their own (front 9).
with connect() as c:
unpaid.expire(c, os.environ.get('PUBLIC_ORIGIN', 'http://localhost'))
last_cleanup = time.monotonic()
mail.send_pending(connect)
tiny_keepalive()

107
tests/unpaid_test.py Normal file
View File

@@ -0,0 +1,107 @@
"""Approved quotes nobody paid expire after 24 h (Fase 2, front 9).
Run inside the API container: python -m tests.unpaid_test
A live payment attempt keeps the files; once it is final, the quote expires,
its files are freed, the customer is e-mailed once and it leaves the Kanban.
"""
from datetime import datetime, timedelta, timezone
from urllib.parse import urlencode
from uuid import uuid4
from psycopg.types.json import Jsonb
from app import unpaid
from app.core import db
from tests.smoke_test import Client, approved_quote, item_spec, upload_bytes
ORIGIN = 'http://localhost'
SUBJECT = 'Seu pedido expirou · DTF Dropstar'
def reviewed_quote():
"""A quote an operator has approved, ready to be paid."""
customer = Client()
customer.call('/session')
uid = upload_bytes(customer, b'UNPAID EXPIRE TEST')
item = item_spec('file', '1.01', 0, uid)
mail = 'unpaid-' + uuid4().hex[:8] + '@example.test'
profile = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail}
quote = customer.call('/quotes', {'request_key': str(uuid4()), 'customer': profile,
'items': [item], 'freight': {'service': 'pickup'}})
approved = approved_quote(customer, quote, [item])
return customer, quote['id'], approved, mail
def attempt(c, quote_id, total, status, expires_at):
"""A payment attempt as the intent route records it."""
c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,
method,status,amount_cents,response) VALUES(%s,%s,'fake',%s,'pix',%s,%s,%s)''',
(uuid4(), quote_id, 'unpaid-' + uuid4().hex, status, total,
Jsonb({'status': status, 'expires_at': expires_at.isoformat()})))
def run():
customer, quote_id, approved, mail = reviewed_quote()
uploads = [uid for item in approved['items'] for uid in item['uploads']]
# 25 h old, but a PIX still open: the quote must not expire, nor its files.
with db.connect() as c:
c.execute("UPDATE dtf_local.quotes SET approved_at=now()-interval '25 hours' WHERE id=%s",
(quote_id,))
attempt(c, quote_id, approved['total_cents'], 'pending',
datetime.now(timezone.utc) + timedelta(minutes=30))
with db.connect() as c:
unpaid.expire(c, ORIGIN)
assert c.execute('SELECT expired_at FROM dtf_local.quotes WHERE id=%s',
(quote_id,)).fetchone()['expired_at'] is None
page = customer.call('/operator/quotes?' + urlencode({'kind': 'approved', 'q': mail}), operator=True)
assert quote_id in {q['id'] for q in page['quotes']}
print('PASS: a live payment attempt keeps an approved quote and its files')
# The attempt is final now: the quote expires, its files are freed and the
# customer is told once.
with db.connect() as c:
c.execute("UPDATE dtf_local.payment_intents SET status='expired' WHERE quote_id=%s", (quote_id,))
expired = unpaid.expire(c, ORIGIN)
assert expired >= 1, expired
with db.connect() as c:
row = c.execute('SELECT expired_at FROM dtf_local.quotes WHERE id=%s', (quote_id,)).fetchone()
assert row['expired_at'] is not None
files = c.execute('''SELECT count(*) AS total,
count(*) FILTER (WHERE expires_at<=now()) AS released
FROM dtf_local.uploads WHERE id=ANY(%s)''', (uploads,)).fetchone()
assert files['total'] and files['released'] == files['total'], files
mails = c.execute('SELECT kind,subject FROM dtf_local.mail_queue WHERE to_addr=%s ORDER BY id',
(mail,)).fetchall()
assert [m['subject'] for m in mails] == [SUBJECT], mails
page = customer.call('/operator/quotes?' + urlencode({'kind': 'approved', 'q': mail}), operator=True)
assert quote_id not in {q['id'] for q in page['quotes']}
print('PASS: the expired quote leaves the Kanban, frees its files and e-mails the customer')
# Expiring again is a no-op: the customer is not told twice.
with db.connect() as c:
unpaid.expire(c, ORIGIN)
with db.connect() as c:
sent = c.execute('SELECT count(*) AS n FROM dtf_local.mail_queue WHERE to_addr=%s AND subject=%s',
(mail, SUBJECT)).fetchone()['n']
assert sent == 1, sent
print('PASS: a second run does not e-mail the customer again')
# A quote from before this front ran out days ago: it expires silently.
_, old_id, _, old_mail = reviewed_quote()
with db.connect() as c:
c.execute("UPDATE dtf_local.quotes SET approved_at=now()-interval '3 days' WHERE id=%s", (old_id,))
unpaid.expire(c, ORIGIN)
with db.connect() as c:
assert c.execute('SELECT expired_at FROM dtf_local.quotes WHERE id=%s',
(old_id,)).fetchone()['expired_at'] is not None
assert not c.execute('SELECT 1 FROM dtf_local.mail_queue WHERE to_addr=%s', (old_mail,)).fetchone()
print('PASS: an old backlog quote expires without an e-mail')
stats = customer.call('/operator/stats?days=7', operator=True)
assert stats['unpaid']['expired'] >= 1, stats['unpaid']
print('PASS: Números counts the expired order')
if __name__ == '__main__':
run()

View File

@@ -143,6 +143,8 @@
<section class="panel clip s6"><div class="phead"><h2>Tempo em cada etapa</h2><span class="hint tip-l" tabindex="0" data-tip="Tempo mediano por pedido: quem voltou para a etapa soma cada passagem. O tempo em Aguardando contato não conta."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span><button class="btn right" id="edit-stage-limits" type="button" hidden>Editar tempos</button></div>
<table class="table"><thead><tr><th scope="col">Etapa</th><th scope="col" class="r">Média</th><th scope="col" class="r">Aceitável</th><th scope="col" class="r">Estouros</th><th scope="col">Agora</th></tr></thead><tbody id="stats-stages"></tbody></table></section>
</div>
<section class="panel clip"><div class="phead"><h2>Pedidos sem pagamento</h2><span class="hint" tabindex="0" data-tip="Cotações aprovadas no período, pela data de aprovação. Pagas viraram pedido; expiradas passaram de 24 horas sem pagamento; aguardando ainda podem ser pagas. A taxa de abandono é expiradas sobre pagas mais expiradas."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<table class="table"><thead><tr><th scope="col">Indicador</th><th scope="col" class="r">Valor</th></tr></thead><tbody id="stats-unpaid"></tbody></table></section>
<section class="panel clip"><div class="phead"><h2>Velocidade do site e do Prumo</h2><span class="hint tip-l" tabindex="0" data-tip="Média e p95 do que o cliente sente, por pedido pago no período: abrir a página, subir o arquivo (segundos por MB), a conferência do Prumo, a montagem das avulsas, a geração do arquivo final por 10 m e o tempo do evento de pagamento até o card. Referências: página < 3 s; conferência < 30 s; geração < 2 min por 10 m; card em até 1 min."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<table class="table"><thead><tr><th scope="col">Etapa</th><th scope="col" class="r">Média</th><th scope="col" class="r">p95</th><th scope="col" class="r">Amostras</th></tr></thead><tbody id="stats-speed"></tbody></table></section>
</section>

View File

@@ -2609,6 +2609,13 @@ async function loadStats(){
tr.append(node('td',ORIGINS[o.origin]),node('td',String(o.orders),'r'),node('td',metres(o.metres).replace(' m',''),'r'),node('td',money(o.cents),'r'),
node('td',o.finished?duration(o.median_hours):'—','r'));
if(!o.orders)tr.classList.add('off');return tr;}));
// Approved orders never paid: made, paid, expired and the abandonment rate.
const unpaid=data.unpaid;
const unpaidRows=[['Pedidos feitos',String(unpaid.made)],['Pagos',String(unpaid.paid)],
['Expirados sem pagamento',String(unpaid.expired)],['Aguardando pagamento',String(unpaid.waiting)],
['Taxa de abandono',unpaid.abandon_pct==null?'—':unpaid.abandon_pct.toFixed(1).replace('.',',')+'%']];
$('stats-unpaid').replaceChildren(...unpaidRows.map(([label,value])=>{const tr=node('tr');
tr.append(node('td',label),node('td',value,'r'));return tr;}));
// Who prepared the finals of the period's orders, for the designer's productivity.
const most=Math.max(1,...data.treated.by.map(t=>t.orders));
$('stats-treated').replaceChildren(...(data.treated.by.length?data.treated.by.map(t=>{
@@ -2742,6 +2749,14 @@ function quoteWarning(q){
if(items.some(i=>i.quality_status==='warning'))return ['warn','Ressalva de resolução aceita'];
return null;
}
// How long an approved quote has left before the worker expires it.
function quoteExpiry(q){
if(!q.expires_at)return null;
const left=new Date(q.expires_at).getTime()-Date.now();
if(left<=0)return 'expirando';
if(left<3600000)return 'expira em '+Math.max(1,Math.ceil(left/60000))+' min';
return 'expira em '+Math.ceil(left/3600000)+'h';
}
function renderQuotes(){
const kinds=[['pending','A revisar',board.pending_total],['approved','Aguardando pagamento',board.approved_total]];
$('quote-filters').replaceChildren(...kinds.map(([key,label,count])=>{
@@ -2775,7 +2790,7 @@ function renderQuotes(){
first.append(name,node('span',q.approved?money(q.approved.total_cents):metres(quoteMetres(q)),'qm'));
const second=node('span',undefined,'qline sub');
const what=node('span');what.append(gradePill(lowestGrade(items)),' '+productLine(items)+', '+(q.draft.destination?q.draft.destination.city+'/'+q.draft.destination.state:'Retirada'));
second.append(what,node('span',shortAgo(q.created_at)));
second.append(what,node('span',(quoteKind==='approved'?quoteExpiry(q):null)||shortAgo(q.created_at)));
main.append(first,second);
const warn=quoteWarning(q);
if(warn){const w=node('span',undefined,'qwarn'+(warn[0]==='bad'?' bad':''));w.append(svgIcon(IC.alert,'i s'),node('span',warn[1]));main.append(w);}
@@ -2829,7 +2844,7 @@ function review(quote){
words.append(title,meta);head.append(words);
if(quote.approved){const total=node('div',undefined,'qbig');total.append(node('span','Total','lbl'),node('b',money(quote.approved.total_cents)));head.append(total);}
const zap=whatsappLink(c.zap);
if(zap){const a=node('a','WhatsApp','btn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.title=c.zap;a.prepend(svgIcon(IC.chat,'i m'));head.append(a);}
if(zap){const a=node('a',quote.status==='approved'?'Abrir conversa':'WhatsApp','btn');a.href=zap;a.target='_blank';a.rel='noopener noreferrer';a.title=c.zap;a.prepend(svgIcon(IC.chat,'i m'));head.append(a);}
const body=node('div',undefined,'rbody');
const foot=node('div',undefined,'rfoot');
if(quote.status==='pending_review'&&quote.draft.items.some(item=>!LAYOUT_VERSIONS.includes(item.production?.version))){