Compare commits
7 Commits
e81b2b1681
...
8997e22f5e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8997e22f5e | ||
|
|
b3c5f63553 | ||
|
|
581fbe6be4 | ||
|
|
b1fbaad2bd | ||
|
|
1b445f0459 | ||
|
|
f567e6da89 | ||
|
|
c5b1bd37a6 |
@@ -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; do
|
||||
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 thumbnail_backfill_test launch_reset_test; do
|
||||
echo "--- $suite"
|
||||
$COMPOSE exec -T \
|
||||
-e SITE_BASE_URL=http://site \
|
||||
@@ -86,7 +86,7 @@ jobs:
|
||||
# the generator's geometry. The provider suites use a fake transport: they
|
||||
# prove the documented contract, not the integration.
|
||||
- name: Print-file geometry and provider adapters
|
||||
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_jadlog tests.test_quote_review tests.test_large_files tests.test_grade_check -v
|
||||
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_jadlog tests.test_quote_review tests.test_large_files tests.test_grade_check -v
|
||||
|
||||
- name: Runtime and retention regressions
|
||||
run: |
|
||||
|
||||
@@ -15,10 +15,10 @@ from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, client_ip, o
|
||||
login_failed, password_matches, throttle)
|
||||
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel
|
||||
from ..printjobs import queue as queue_print_files
|
||||
from .. import payments, quote_review
|
||||
from .. import cnpj, payments, quote_review
|
||||
from .. import tiny
|
||||
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, STATES, TRANSITIONS, payment,
|
||||
enqueue, freight, quote_view, storage)
|
||||
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES,
|
||||
TRANSITIONS, payment, enqueue, freight, quote_view, storage)
|
||||
from ..scanning import require_clean
|
||||
|
||||
router = APIRouter()
|
||||
@@ -122,9 +122,11 @@ def board(user=Depends(operator)):
|
||||
quotes = [quote_view(c, q) for q in pending + approved]
|
||||
return {'states': STATES, 'transitions': TRANSITIONS, 'back': BACK,
|
||||
'orders': orders, 'payment_issues_total': issues_total, 'tiny': tiny_status(), 'operator': user,
|
||||
'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup}, 'environment': ENVIRONMENT,
|
||||
'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup},
|
||||
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
|
||||
'finished_shown': len(finished), 'finished_total': finished_total,
|
||||
'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
|
||||
'names': company_names(c, orders, quotes),
|
||||
'pending_total': pending_total, 'approved_total': approved_total}
|
||||
|
||||
|
||||
@@ -149,6 +151,12 @@ def thumbnails(c, *groups):
|
||||
return [str(r['upload_id']) for r in rows]
|
||||
|
||||
|
||||
def company_names(c, *groups):
|
||||
"""The registry's company names for these orders' and quotes' CNPJs (app/cnpj.py)."""
|
||||
return cnpj.names(c, [((row.get('snapshot') or row.get('draft') or {}).get('customer') or {}).get('cnpj')
|
||||
for rows in groups for row in rows])
|
||||
|
||||
|
||||
# An item's final counts while its file is still there and scanned clean: the
|
||||
# same rule that lets an order into the print queue.
|
||||
FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean'"""
|
||||
@@ -168,7 +176,11 @@ def with_print_files(c, orders):
|
||||
(u.expires_at<=now() OR u.purged_at IS NOT NULL) AS expired FROM dtf_local.order_files f
|
||||
JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||
WHERE f.order_id=ANY(%s) AND f.kind='correction' AND f.active ORDER BY f.item_index''', (ids,)).fetchall()
|
||||
# Why each order was last sent to correction, for the notice to the customer.
|
||||
reasons = {row['order_id']: row['reason'] for row in c.execute('''SELECT DISTINCT ON (order_id) order_id,reason
|
||||
FROM dtf_local.movements WHERE order_id=ANY(%s) AND to_state='cor' ORDER BY order_id,id DESC''', (ids,)).fetchall()}
|
||||
for order in orders:
|
||||
order['correction_reason'] = reasons.get(order['id']) if order['state'] == 'cor' else None
|
||||
order['print_files'] = [row for row in generated if row['order_id'] == order['id']]
|
||||
order['final_items'] = sorted(row['item_index'] for row in finals if row['order_id'] == order['id'])
|
||||
order['corrections'] = [{k: row[k] for k in ('item_index', 'upload_id', 'name', 'expired')}
|
||||
@@ -193,7 +205,8 @@ def finished_page(before_created_at: datetime | None = None, before_id: UUID | N
|
||||
ORDER BY created_at DESC,id DESC LIMIT %s''',
|
||||
((before_created_at, before_id) if paged else ()) + (limit + 1,)).fetchall()
|
||||
orders = with_print_files(c, rows[:limit])
|
||||
return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders)}
|
||||
return {'orders': orders, 'has_more': len(rows) > limit, 'thumbnails': thumbnails(c, orders),
|
||||
'names': company_names(c, orders)}
|
||||
|
||||
|
||||
@router.get('/api/operator/payment-events')
|
||||
@@ -255,13 +268,15 @@ def numeric(q):
|
||||
|
||||
|
||||
def customer_match(column, q):
|
||||
"""SQL and parameters matching a customer (e-mail, CNPJ or WhatsApp) in an
|
||||
order snapshot or a quote draft. CNPJ and phone match by their digits, and
|
||||
only when nothing but digits and punctuation was typed: the digits of an
|
||||
e-mail address are not a phone number."""
|
||||
"""SQL and parameters matching a customer (e-mail, company name, CNPJ or
|
||||
WhatsApp) in an order snapshot or a quote draft. CNPJ and phone match by
|
||||
their digits, and only when nothing but digits and punctuation was typed:
|
||||
the digits of an e-mail address are not a phone number."""
|
||||
text, digits = q.strip().lower(), numeric(q)
|
||||
sql = f"lower({column}->'customer'->>'mail') LIKE %s"
|
||||
params = [like(text)]
|
||||
cnpj = f"regexp_replace(coalesce({column}->'customer'->>'cnpj',''),'\\D','','g')"
|
||||
sql = (f"lower({column}->'customer'->>'mail') LIKE %s OR {cnpj} IN (SELECT n.cnpj FROM dtf_local.cnpj_names n"
|
||||
" WHERE lower(n.legal_name) LIKE %s OR lower(n.trade_name) LIKE %s)")
|
||||
params = [like(text)] * 3
|
||||
if len(digits) >= 3:
|
||||
sql += (f" OR regexp_replace(coalesce({column}->'customer'->>'cnpj',''),'\\D','','g') LIKE %s"
|
||||
f" OR regexp_replace(coalesce({column}->'customer'->>'zap',''),'\\D','','g') LIKE %s")
|
||||
@@ -305,7 +320,7 @@ def quote_page(kind: Literal['pending','approved'], before_created_at: datetime
|
||||
WHERE {where}''', params).fetchone()['n']
|
||||
quotes = [quote_view(c,row) for row in rows[:limit]]
|
||||
return {'quotes': quotes, 'has_more': len(rows)>limit, 'total': total,
|
||||
'thumbnails': thumbnails(c, quotes)}
|
||||
'thumbnails': thumbnails(c, quotes), 'names': company_names(c, quotes)}
|
||||
|
||||
|
||||
@router.get('/api/operator/search')
|
||||
@@ -334,7 +349,8 @@ def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator))
|
||||
ORDER BY q.created_at DESC LIMIT 8''', quote_params).fetchall()
|
||||
orders = with_print_files(c, orders)
|
||||
quotes = [quote_view(c, row) for row in rows]
|
||||
return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes)}
|
||||
return {'orders': orders, 'quotes': quotes, 'thumbnails': thumbnails(c, orders, quotes),
|
||||
'names': company_names(c, orders, quotes)}
|
||||
|
||||
@router.post('/api/operator/quotes/{uid}/approve')
|
||||
def approve(uid: UUID, body: Review, user=Depends(operator)):
|
||||
@@ -620,6 +636,90 @@ def thumbnail(uid: UUID, user=Depends(operator)):
|
||||
return Response(bytes(row['data']), media_type=row['mime'],
|
||||
headers={'Cache-Control': 'private, max-age=86400', 'Content-Disposition': 'inline'})
|
||||
|
||||
# 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'"
|
||||
LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date"
|
||||
|
||||
|
||||
@router.get('/api/operator/stats')
|
||||
def production_stats(days: int = Query(default=30, ge=7, le=365), user=Depends(operator)):
|
||||
"""Production numbers from what the board already records: orders paid in
|
||||
the period, how long each stage holds an order, and what is waiting now."""
|
||||
# From the start of the first local day of the period.
|
||||
since = ("o.created_at >= (((now() AT TIME ZONE 'America/Sao_Paulo')::date - make_interval(days => %s - 1))"
|
||||
" AT TIME ZONE 'America/Sao_Paulo')")
|
||||
metres = "(SELECT COALESCE(sum((i->>'billed_metres')::numeric),0) FROM jsonb_array_elements(o.snapshot->'items') i)"
|
||||
with db.connect() as c:
|
||||
total = c.execute(f'''SELECT count(*) AS orders, COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents,
|
||||
COALESCE(sum({metres}),0) AS metres,
|
||||
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 {since}''', (days,)).fetchone()
|
||||
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 {since}
|
||||
GROUP BY 1''', (days,)).fetchall()}
|
||||
# Each order's stages as spans: from entering a stage to the next move.
|
||||
spans = f'''WITH events AS (
|
||||
SELECT o.id, 'rec' AS state, o.created_at AS at FROM dtf_local.orders o WHERE {REAL_ORDER} AND {since}
|
||||
UNION ALL
|
||||
SELECT m.order_id, m.to_state, m.created_at FROM dtf_local.movements m
|
||||
JOIN dtf_local.orders o ON o.id=m.order_id WHERE {REAL_ORDER} AND {since})
|
||||
SELECT id, state, at, LEAD(at) OVER (PARTITION BY id ORDER BY at) AS until FROM events'''
|
||||
stages = c.execute(f'''SELECT state, count(*) AS orders,
|
||||
percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM until-at)) / 3600 AS median_hours
|
||||
FROM ({spans}) s WHERE until IS NOT NULL GROUP BY state''', (days, days)).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
|
||||
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 {since}''', (days,)).fetchone()
|
||||
# What waits now, however old, and since when in its stage.
|
||||
waiting = c.execute(f'''SELECT o.state, count(*) AS orders, max(extract(epoch FROM now() - COALESCE(
|
||||
(SELECT max(m.created_at) FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state=o.state),
|
||||
o.created_at))) / 3600 AS oldest_hours
|
||||
FROM dtf_local.orders o WHERE {REAL_ORDER} AND o.state<>'fin' GROUP BY o.state''').fetchall()
|
||||
today = datetime.now(timezone(timedelta(hours=-3))).date()
|
||||
series = []
|
||||
for offset in range(days - 1, -1, -1):
|
||||
day = today - timedelta(days=offset)
|
||||
row = daily.get(day)
|
||||
series.append({'day': day.isoformat(), 'orders': row['orders'] if row else 0,
|
||||
'metres': float(row['metres']) if row else 0.0})
|
||||
hours = lambda value: round(float(value), 1) if value is not None else None
|
||||
return {'days': days, 'orders': total['orders'], 'cents': int(total['cents']), 'metres': float(total['metres']),
|
||||
'corrected': total['corrected'], 'daily': series,
|
||||
'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])},
|
||||
'stages': {row['state']: {'orders': row['orders'], 'median_hours': hours(row['median_hours'])} for row in stages},
|
||||
'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting}}
|
||||
|
||||
|
||||
@router.get('/api/operator/queue/finals')
|
||||
def queue_finals(user=Depends(operator)):
|
||||
"""The approved final files of every order in the print queue, in queue
|
||||
order, each named after its order so a folder of them stays readable. The
|
||||
browser downloads them straight from storage: a zip of multi-GB sheets
|
||||
would go through the server."""
|
||||
with db.connect() as c:
|
||||
rows = c.execute(f'''SELECT o.number,f.item_index,u.object_key,u.name FROM dtf_local.orders o
|
||||
JOIN dtf_local.order_files f ON f.order_id=o.id JOIN dtf_local.uploads u ON u.id=f.upload_id
|
||||
WHERE o.state='fil' AND o.cancelled_at IS NULL AND {FINAL_OK}
|
||||
ORDER BY COALESCE(o.queue_key, extract(epoch FROM o.created_at)),o.id,f.item_index,f.created_at''').fetchall()
|
||||
files, names = [], set()
|
||||
for row in rows:
|
||||
prefix = f"pedido-{row['number']}-item-{row['item_index'] + 1}"
|
||||
name = row['name'] if row['name'].startswith(prefix) else f"{prefix}-{row['name']}"
|
||||
stem, dot, ext = name.rpartition('.')
|
||||
copy = 2
|
||||
while name in names:
|
||||
name = f'{stem} ({copy}).{ext}' if dot else f'{ext} ({copy})'
|
||||
copy += 1
|
||||
names.add(name)
|
||||
files.append({'number': row['number'], 'item': row['item_index'] + 1, 'name': name,
|
||||
'url': storage.download(row['object_key'], name)})
|
||||
audit('queue_finals_downloaded', operator=user, files=len(files))
|
||||
return {'files': files}
|
||||
|
||||
|
||||
@router.get('/api/operator/uploads/{uid}/download')
|
||||
def download(uid: UUID, user=Depends(operator)):
|
||||
with db.connect() as c:
|
||||
|
||||
100
app/cnpj.py
Normal file
100
app/cnpj.py
Normal file
@@ -0,0 +1,100 @@
|
||||
"""The company name behind a customer's CNPJ, from the public registry.
|
||||
|
||||
The Site asks for e-mail, CNPJ and WhatsApp only, so the Kanban showed an
|
||||
e-mail where a name belongs, and a new Tiny contact was named after it. The
|
||||
Receita's CNPJ registry is public, and BrasilAPI serves it without a key.
|
||||
Names are looked up by the worker, never while a customer waits, and kept in
|
||||
dtf_local.cnpj_names; a lookup that fails is tried again a day later.
|
||||
"""
|
||||
import os
|
||||
|
||||
import httpx
|
||||
|
||||
API = os.environ.get('CNPJ_LOOKUP_URL', 'https://brasilapi.com.br/api/cnpj/v1/')
|
||||
# A few per minute of the worker's time is plenty: customers repeat.
|
||||
PER_RUN = 5
|
||||
|
||||
|
||||
def digits(value):
|
||||
return ''.join(ch for ch in str(value or '') if ch.isdigit())
|
||||
|
||||
|
||||
def fetch(cnpj, transport=None):
|
||||
"""The registry's names for one CNPJ. An unknown CNPJ has none, and is not asked again."""
|
||||
with httpx.Client(timeout=8, transport=transport) as http:
|
||||
response = http.get(API + cnpj, headers={'Accept': 'application/json', 'User-Agent': 'dtf-sistema'})
|
||||
if response.status_code == 404:
|
||||
return {'legal_name': None, 'trade_name': None}
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
clean = lambda value: ' '.join(str(value).split()) or None if value else None
|
||||
return {'legal_name': clean(data.get('razao_social')), 'trade_name': clean(data.get('nome_fantasia'))}
|
||||
|
||||
|
||||
def pending(c, limit):
|
||||
"""CNPJs of orders and recent quotes never looked up, or whose lookup failed a day ago."""
|
||||
return [row['cnpj'] for row in c.execute('''WITH seen AS (
|
||||
SELECT regexp_replace(snapshot->'customer'->>'cnpj', '\\D', '', 'g') AS cnpj, created_at FROM dtf_local.orders
|
||||
UNION ALL
|
||||
SELECT regexp_replace(draft->'customer'->>'cnpj', '\\D', '', 'g'), created_at FROM dtf_local.quotes
|
||||
WHERE created_at > now() - interval '3 days')
|
||||
SELECT s.cnpj FROM seen s LEFT JOIN dtf_local.cnpj_names n ON n.cnpj=s.cnpj
|
||||
WHERE length(s.cnpj)=14 AND (n.cnpj IS NULL OR (n.fetched_at IS NULL AND n.failed_at < now() - interval '1 day'))
|
||||
GROUP BY s.cnpj ORDER BY max(s.created_at) DESC LIMIT %s''', (limit,)).fetchall()]
|
||||
|
||||
|
||||
def store(c, cnpj, found):
|
||||
c.execute('''INSERT INTO dtf_local.cnpj_names(cnpj,legal_name,trade_name,fetched_at) VALUES(%s,%s,%s,now())
|
||||
ON CONFLICT (cnpj) DO UPDATE SET legal_name=EXCLUDED.legal_name, trade_name=EXCLUDED.trade_name,
|
||||
fetched_at=now(), failed_at=NULL''', (cnpj, found['legal_name'], found['trade_name']))
|
||||
|
||||
|
||||
def failed(c, cnpj):
|
||||
c.execute('''INSERT INTO dtf_local.cnpj_names(cnpj,failed_at) VALUES(%s,now())
|
||||
ON CONFLICT (cnpj) DO UPDATE SET failed_at=now()''', (cnpj,))
|
||||
|
||||
|
||||
def resolve(connect, limit=PER_RUN, transport=None):
|
||||
"""Look up the next few CNPJs; returns how many were found."""
|
||||
with connect() as c:
|
||||
cnpjs = pending(c, limit)
|
||||
found = 0
|
||||
for cnpj in cnpjs:
|
||||
try:
|
||||
names = fetch(cnpj, transport)
|
||||
except (httpx.HTTPError, ValueError):
|
||||
with connect() as c:
|
||||
failed(c, cnpj)
|
||||
continue
|
||||
with connect() as c:
|
||||
store(c, cnpj, names)
|
||||
found += 1
|
||||
return found
|
||||
|
||||
|
||||
def names(c, cnpjs):
|
||||
"""{cnpj: {'legal': ..., 'trade': ...}} for the CNPJs already found."""
|
||||
wanted = sorted({digits(value) for value in cnpjs} - {''})
|
||||
if not wanted:
|
||||
return {}
|
||||
rows = c.execute('''SELECT cnpj,legal_name,trade_name FROM dtf_local.cnpj_names
|
||||
WHERE cnpj=ANY(%s) AND (legal_name IS NOT NULL OR trade_name IS NOT NULL)''', (wanted,)).fetchall()
|
||||
return {row['cnpj']: {'legal': row['legal_name'], 'trade': row['trade_name']} for row in rows}
|
||||
|
||||
|
||||
def company(cnpj, connect=None, transport=None):
|
||||
"""One CNPJ's names for a Tiny contact: stored, or looked up now. None if unavailable."""
|
||||
if connect is None:
|
||||
from .core.db import connect
|
||||
cnpj = digits(cnpj)
|
||||
with connect() as c:
|
||||
known = names(c, [cnpj]).get(cnpj)
|
||||
if known:
|
||||
return known
|
||||
try:
|
||||
found = fetch(cnpj, transport)
|
||||
except (httpx.HTTPError, ValueError):
|
||||
return None
|
||||
with connect() as c:
|
||||
store(c, cnpj, found)
|
||||
return {'legal': found['legal_name'], 'trade': found['trade_name']} if any(found.values()) else None
|
||||
@@ -226,3 +226,10 @@ ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancel_reason text;
|
||||
-- An order's place in its column's queue, when an operator dragged it up or
|
||||
-- down. Empty means "by payment time"; it is cleared when the order moves on.
|
||||
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS queue_key double precision;
|
||||
|
||||
-- The company name behind each customer's CNPJ, from the public registry
|
||||
-- (app/cnpj.py). failed_at alone: the lookup failed and is retried later.
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names (
|
||||
cnpj text PRIMARY KEY, legal_name text, trade_name text,
|
||||
fetched_at timestamptz, failed_at timestamptz
|
||||
);
|
||||
|
||||
21
app/tiny.py
21
app/tiny.py
@@ -286,12 +286,17 @@ def money(cents):
|
||||
return float(Decimal(cents) / 100)
|
||||
|
||||
|
||||
def contact_payload(order):
|
||||
def contact_payload(order, company=None):
|
||||
"""A new contact, named after the company's razão social when the
|
||||
registry gave it (app/cnpj.py), else the recipient or the e-mail."""
|
||||
customer = order['customer']
|
||||
destination = order.get('destination')
|
||||
contact = {'nome': (destination or {}).get('recipient') or customer['mail'],
|
||||
company = company or {}
|
||||
contact = {'nome': company.get('legal') or (destination or {}).get('recipient') or customer['mail'],
|
||||
'tipoPessoa': 'J', 'cpfCnpj': customer['cnpj'], 'email': customer['mail'],
|
||||
'celular': customer['zap'], 'situacao': 'A'}
|
||||
if company.get('trade'):
|
||||
contact['fantasia'] = company['trade']
|
||||
if destination:
|
||||
contact['endereco'] = address(destination)
|
||||
return contact
|
||||
@@ -412,7 +417,7 @@ def check(auth=None, transport=None, orders=None):
|
||||
|
||||
|
||||
class TinyOrders:
|
||||
def __init__(self, auth=None, transport=None, today=None):
|
||||
def __init__(self, auth=None, transport=None, today=None, names=None):
|
||||
missing = [name for name in required_settings() if not os.environ.get(name)]
|
||||
if auth is None and missing:
|
||||
raise RuntimeError('Tiny needs ' + ', '.join(missing))
|
||||
@@ -420,6 +425,8 @@ class TinyOrders:
|
||||
self.http = httpx.Client(base_url=API, transport=transport, timeout=30)
|
||||
self.today = today
|
||||
self.skus = {}
|
||||
# The company's names by CNPJ, for new contacts (app.cnpj.company).
|
||||
self.names = names
|
||||
|
||||
def request(self, method, path, **kwargs):
|
||||
headers = {'Authorization': f'Bearer {self.auth.access_token()}'}
|
||||
@@ -449,7 +456,13 @@ class TinyOrders:
|
||||
for entry in found.get('itens') or []:
|
||||
if ''.join(ch for ch in str(entry.get('cpfCnpj') or '') if ch.isdigit()) == cnpj:
|
||||
return entry['id']
|
||||
return self.request('POST', '/contatos', json=contact_payload(order))['id']
|
||||
company = None
|
||||
if self.names:
|
||||
try:
|
||||
company = self.names(cnpj)
|
||||
except Exception: # a name is a nicety; the order must still go
|
||||
company = None
|
||||
return self.request('POST', '/contatos', json=contact_payload(order, company))['id']
|
||||
|
||||
def find(self, payload, days=SEARCH_DAYS):
|
||||
"""An order a previous delivery already created, or None."""
|
||||
|
||||
@@ -18,10 +18,13 @@ adapters = {'tiny': FakeTiny(), 'whatsapp': FakeWhatsApp()}
|
||||
# Not yet confirmed against the client's account; see app/tiny.py.
|
||||
if os.environ.get('TINY_ADAPTER') == 'tiny':
|
||||
from .tiny import TinyOrders
|
||||
adapters['tiny'] = TinyOrders()
|
||||
from .cnpj import company
|
||||
adapters['tiny'] = TinyOrders(names=company)
|
||||
last_tick = 0.0
|
||||
last_cleanup = 0.0
|
||||
last_reconcile = 0.0
|
||||
last_names = 0.0
|
||||
names_thread = None
|
||||
last_tiny_keepalive = 0.0
|
||||
storage = LocalS3Storage()
|
||||
scan_thread = None
|
||||
@@ -87,6 +90,23 @@ def reconcile_payments():
|
||||
from .runtime import payment
|
||||
payments.reconcile(connect, payment)
|
||||
|
||||
def resolve_names():
|
||||
"""Every minute: the company names of a few new customers' CNPJs, on a
|
||||
thread of their own, so a slow registry never holds up orders."""
|
||||
global last_names, names_thread
|
||||
if time.monotonic()-last_names < 60 or (names_thread and names_thread.is_alive()):
|
||||
return
|
||||
last_names = time.monotonic()
|
||||
from . import cnpj
|
||||
|
||||
def run():
|
||||
try:
|
||||
cnpj.resolve(connect)
|
||||
except Exception:
|
||||
logging.exception('CNPJ name lookup failed')
|
||||
names_thread = threading.Thread(target=run, daemon=True)
|
||||
names_thread.start()
|
||||
|
||||
def loop():
|
||||
global last_cleanup
|
||||
while True:
|
||||
@@ -97,6 +117,7 @@ def loop():
|
||||
last_cleanup = time.monotonic()
|
||||
tiny_keepalive()
|
||||
reconcile_payments()
|
||||
resolve_names()
|
||||
except Exception:
|
||||
logging.exception('Local worker tick failed')
|
||||
time.sleep(1)
|
||||
|
||||
@@ -175,6 +175,21 @@ SHA of the last known-good Gitea commit and redeploy. This rolls back Site, API,
|
||||
Kanban, and worker code; it does not undo database migrations or restore data.
|
||||
After recovery and a corrected release, return `IMAGE_TAG` to `latest`.
|
||||
|
||||
## 6. Before opening to customers
|
||||
|
||||
Once, right before launch, clear the test orders from the worker's console
|
||||
(Containers > worker > Console):
|
||||
|
||||
```bash
|
||||
python -m ops.launch_reset # only counts
|
||||
python -m ops.launch_reset --confirmar APAGAR # removes orders, quotes and payments
|
||||
```
|
||||
|
||||
It refuses if any payment was made with real money. Order numbers restart at
|
||||
#1 only with the database administrator: the script prints the `psql` line to
|
||||
run in the `db` container's console. Add `--contas` to remove the test
|
||||
customer accounts too.
|
||||
|
||||
## Current blocker
|
||||
|
||||
This is the final deployment shape, but it is not authorized for production
|
||||
|
||||
99
ops/backfill_thumbnails.py
Normal file
99
ops/backfill_thumbnails.py
Normal file
@@ -0,0 +1,99 @@
|
||||
"""Make the Kanban's artwork pictures for orders and quotes from before them.
|
||||
|
||||
The customer's browser makes each picture while uploading; older uploads have
|
||||
none, so their cards show "sem prévia". Run once from the worker's console:
|
||||
|
||||
python -m ops.backfill_thumbnails makes the missing pictures
|
||||
python -m ops.backfill_thumbnails --limite 20 at most 20 this run
|
||||
|
||||
Only PNG, JPEG and WebP: a PDF, CDR, AI or PSD needs a renderer the server
|
||||
does not have, and keeps showing the layout drawing. Files are read from
|
||||
storage one at a time, and very large images are skipped, so the worker is
|
||||
never asked for more memory than a normal sheet takes. Safe to run again: it
|
||||
only looks at uploads that still have no picture.
|
||||
"""
|
||||
import argparse
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
from app.core import db
|
||||
|
||||
# The Site's own picture size (site-upload.js: miniatura(..., 480, 720)).
|
||||
BOX = (480, 720)
|
||||
# Decoding a PNG takes about 4 bytes a pixel: 100 million pixels is ~400 MB.
|
||||
MAX_PIXELS = 100_000_000
|
||||
MAX_BYTES = 300 * 1024 * 1024
|
||||
IMAGES = ('.png', '.jpg', '.jpeg', '.webp')
|
||||
|
||||
|
||||
def missing(c, limit):
|
||||
"""Uploads an order or a live quote refers to, still readable, without a picture."""
|
||||
return c.execute('''WITH used AS (
|
||||
SELECT (jsonb_array_elements_text(i->'uploads'))::uuid AS id
|
||||
FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i
|
||||
UNION
|
||||
SELECT (jsonb_array_elements_text(i->'uploads'))::uuid
|
||||
FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i
|
||||
WHERE q.discarded_at IS NULL AND q.created_at > now() - interval '3 days')
|
||||
SELECT u.id, u.name, u.size, u.object_key FROM dtf_local.uploads u JOIN used ON used.id=u.id
|
||||
LEFT JOIN dtf_local.upload_thumbnails t ON t.upload_id=u.id
|
||||
WHERE t.upload_id IS NULL AND u.complete AND u.purged_at IS NULL AND u.expires_at>now()
|
||||
AND u.scan_state='clean'
|
||||
ORDER BY u.created_at DESC LIMIT %s''', (limit,)).fetchall()
|
||||
|
||||
|
||||
def picture(path):
|
||||
"""A WebP no larger than BOX, or None when the image is too large to decode."""
|
||||
from PIL import Image
|
||||
Image.MAX_IMAGE_PIXELS = None # the size is checked here, before decoding
|
||||
with Image.open(path) as image:
|
||||
width, height = image.size
|
||||
if width * height > MAX_PIXELS:
|
||||
return None
|
||||
image.draft('RGB', BOX) # JPEG decodes at a reduced size
|
||||
image.thumbnail(BOX)
|
||||
out = io.BytesIO()
|
||||
image.convert('RGBA' if 'A' in image.getbands() or image.mode == 'P' else 'RGB').save(
|
||||
out, 'WEBP', quality=80)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def main(argv=None, out=print, storage=None, connect=db.connect):
|
||||
parser = argparse.ArgumentParser(prog='python -m ops.backfill_thumbnails')
|
||||
parser.add_argument('--limite', type=int, default=500)
|
||||
args = parser.parse_args(argv)
|
||||
if storage is None:
|
||||
from app.runtime import storage
|
||||
with connect() as c:
|
||||
rows = missing(c, args.limite)
|
||||
made = skipped = 0
|
||||
for row in rows:
|
||||
if not row['name'].lower().endswith(IMAGES) or (row['size'] or 0) > MAX_BYTES:
|
||||
skipped += 1
|
||||
continue
|
||||
handle, path = tempfile.mkstemp(prefix='thumb-')
|
||||
os.close(handle)
|
||||
try:
|
||||
storage.fetch(row['object_key'], path)
|
||||
data = picture(path)
|
||||
except Exception as exc: # one unreadable file must not stop the others
|
||||
out(f"{row['name']}: não deu para ler ({type(exc).__name__})")
|
||||
skipped += 1
|
||||
continue
|
||||
finally:
|
||||
os.unlink(path)
|
||||
if data is None:
|
||||
skipped += 1
|
||||
continue
|
||||
with connect() as c:
|
||||
c.execute('''INSERT INTO dtf_local.upload_thumbnails(upload_id,mime,data) VALUES(%s,'image/webp',%s)
|
||||
ON CONFLICT (upload_id) DO NOTHING''', (row['id'], data))
|
||||
made += 1
|
||||
out(f'{made} miniatura(s) criada(s); {skipped} arquivo(s) sem miniatura possível (PDF, CDR, muito grande).')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
83
ops/launch_reset.py
Normal file
83
ops/launch_reset.py
Normal file
@@ -0,0 +1,83 @@
|
||||
"""Clear the test orders before the Site opens to customers, once, by hand.
|
||||
|
||||
Run from the worker's console (Portainer > Containers > worker > Console):
|
||||
|
||||
python -m ops.launch_reset shows what would be removed
|
||||
python -m ops.launch_reset --confirmar APAGAR removes it
|
||||
python -m ops.launch_reset --confirmar APAGAR --contas also customer accounts
|
||||
|
||||
Removes every order with its moves, files and notices, every quote, payment
|
||||
attempt and payment notification, and the artwork pictures. The artwork
|
||||
files are marked expired, so the worker deletes them from storage within a
|
||||
minute. Operators, the Tiny connection and the backups are kept.
|
||||
|
||||
It refuses if any payment was made with real money (Mercado Pago's
|
||||
live_mode): those are customers' orders, not tests.
|
||||
|
||||
Order numbers start again at #1 only with the database administrator's
|
||||
rights, which the worker does not have. The script prints the one command
|
||||
to run in the database container's console for that.
|
||||
"""
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from app.core import db
|
||||
|
||||
TABLES = [ # in an order the foreign keys allow
|
||||
('movements', 'movimentos de etapa'),
|
||||
('order_files', 'arquivos finais e correções'),
|
||||
('print_files', 'arquivos de impressão gerados'),
|
||||
('outbox', 'envios ao Tiny e avisos'),
|
||||
('orders', 'pedidos'),
|
||||
('payment_intents', 'tentativas de pagamento'),
|
||||
('payment_events', 'avisos de pagamento'),
|
||||
('quotes', 'cotações'),
|
||||
('upload_thumbnails', 'miniaturas das artes'),
|
||||
]
|
||||
ACCOUNTS = [('sessions', 'sessões de clientes'), ('accounts', 'contas de clientes')]
|
||||
CONFIRM = 'APAGAR'
|
||||
RESTART = 'ALTER TABLE dtf_local.orders ALTER COLUMN number RESTART WITH 1;'
|
||||
|
||||
|
||||
def counts(c, tables):
|
||||
return {table: c.execute(f'SELECT count(*) AS n FROM dtf_local.{table}').fetchone()['n'] for table, _ in tables}
|
||||
|
||||
|
||||
def main(argv=None, out=print, connect=db.connect):
|
||||
parser = argparse.ArgumentParser(prog='python -m ops.launch_reset')
|
||||
parser.add_argument('--confirmar', default='', help=f'escreva {CONFIRM} para apagar')
|
||||
parser.add_argument('--contas', action='store_true', help='apagar também as contas de clientes')
|
||||
args = parser.parse_args(argv)
|
||||
tables = TABLES + (ACCOUNTS if args.contas else [])
|
||||
with connect() as c:
|
||||
live = c.execute("""SELECT count(*) AS n FROM dtf_local.payment_intents
|
||||
WHERE response->>'live_mode'='true'""").fetchone()['n']
|
||||
if live:
|
||||
out(f'Recusado: {live} pagamento(s) com dinheiro real (live_mode). Esses pedidos são de clientes.')
|
||||
return 1
|
||||
before = counts(c, tables)
|
||||
files = c.execute('SELECT count(*) AS n FROM dtf_local.uploads WHERE purged_at IS NULL').fetchone()['n']
|
||||
for table, label in tables:
|
||||
out(f'{before[table]:>7} {label}')
|
||||
out(f'{files:>7} arquivos de arte (o worker apaga do armazenamento)')
|
||||
if args.confirmar != CONFIRM:
|
||||
out(f'Nada foi apagado. Repita com --confirmar {CONFIRM} para apagar.')
|
||||
return 0
|
||||
for table, _ in tables:
|
||||
c.execute(f'DELETE FROM dtf_local.{table}')
|
||||
c.execute('UPDATE dtf_local.uploads SET expires_at=now() WHERE purged_at IS NULL')
|
||||
out('Apagado.')
|
||||
try:
|
||||
with connect() as c:
|
||||
c.execute(RESTART)
|
||||
out('A numeração dos pedidos recomeça em #1.')
|
||||
except Exception as exc: # the application's role cannot alter the table
|
||||
if 'permission' not in str(exc).lower() and 'owner' not in str(exc).lower():
|
||||
raise
|
||||
out('Para a numeração recomeçar em #1, rode no console do container do banco (db):')
|
||||
out(f' psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "{RESTART}"')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -9,6 +9,7 @@ from urllib.parse import urlencode
|
||||
from urllib.request import Request
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from app.core import db
|
||||
@@ -113,13 +114,45 @@ def run():
|
||||
|
||||
board = client.call('/operator/board', operator=True)
|
||||
assert str(uid) in board['thumbnails']
|
||||
print('PASS: artwork pictures (owner only, images only), quote filters and the order/quote search')
|
||||
|
||||
# Numbers count real paid orders only: this test order counts once it is not one.
|
||||
before = client.call('/operator/stats?days=7', operator=True)
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.orders SET payment=%s WHERE id=%s",
|
||||
(Jsonb({'provider': 'mercadopago', 'id': f'kanban-{tag}'}), order_id))
|
||||
after = client.call('/operator/stats?days=7', operator=True)
|
||||
assert len(after['daily']) == 7
|
||||
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
|
||||
client.call('/operator/stats?days=3', operator=True, expected=422)
|
||||
|
||||
# The company's name from the registry: on the board, and found by the search.
|
||||
from app import cnpj as registry
|
||||
# Even after a failed try (the worker may have had no internet), a lookup stores the names.
|
||||
registry.company('11222333000181', db.connect, transport=httpx.MockTransport(lambda request: httpx.Response(
|
||||
200, json={'razao_social': f'KANBAN {tag} COMERCIO LTDA', 'nome_fantasia': f'Loja {tag}'})))
|
||||
board = client.call('/operator/board', operator=True)
|
||||
assert board['names']['11222333000181'] == {'legal': f'KANBAN {tag} COMERCIO LTDA', 'trade': f'Loja {tag}'}
|
||||
found = client.call('/operator/search?' + urlencode({'q': f'loja {tag}'}), operator=True)
|
||||
assert str(order_id) in {o['id'] for o in found['orders']}, found
|
||||
# A failed lookup is kept and not repeated within the day.
|
||||
with db.connect() as c:
|
||||
c.execute("DELETE FROM dtf_local.cnpj_names WHERE cnpj='11222333000181'")
|
||||
registry.resolve(db.connect, limit=200, transport=httpx.MockTransport(lambda request: httpx.Response(503)))
|
||||
with db.connect() as c:
|
||||
row = c.execute("SELECT fetched_at,failed_at FROM dtf_local.cnpj_names WHERE cnpj='11222333000181'").fetchone()
|
||||
assert row['fetched_at'] is None and row['failed_at'] is not None
|
||||
assert '11222333000181' not in registry.pending(c, 500)
|
||||
Client().call('/operator/stats', expected=401)
|
||||
print('PASS: artwork pictures (owner only, images only), quote filters, the order/quote search and the numbers')
|
||||
finally:
|
||||
with db.connect() as c:
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,))
|
||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([pending, approved, paid],))
|
||||
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (uid,))
|
||||
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s', (uid,))
|
||||
c.execute("DELETE FROM dtf_local.cnpj_names WHERE cnpj='11222333000181'")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
53
tests/launch_reset_test.py
Normal file
53
tests/launch_reset_test.py
Normal file
@@ -0,0 +1,53 @@
|
||||
"""The launch cleanup removes test orders and refuses when real money was paid.
|
||||
|
||||
It empties the order tables, so it runs last. Run inside the API container:
|
||||
python -m tests.launch_reset_test
|
||||
"""
|
||||
from uuid import uuid4
|
||||
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from app.core import db
|
||||
from ops import launch_reset
|
||||
|
||||
|
||||
def run():
|
||||
quote, order, owner = uuid4(), uuid4(), uuid4()
|
||||
with db.connect() as c:
|
||||
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)',
|
||||
(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''',
|
||||
(uuid4(), quote, str(uuid4()), Jsonb({'live_mode': True}))).fetchone()['id']
|
||||
|
||||
lines = []
|
||||
# Real money paid: nothing happens, even when confirmed.
|
||||
assert launch_reset.main(['--confirmar', 'APAGAR'], out=lines.append) == 1
|
||||
assert 'dinheiro real' in lines[-1]
|
||||
with db.connect() as c:
|
||||
c.execute("UPDATE dtf_local.payment_intents SET response='{\"live_mode\": false}' WHERE id=%s", (live,))
|
||||
|
||||
# Without the word, it only counts.
|
||||
lines.clear()
|
||||
assert launch_reset.main([], out=lines.append) == 0
|
||||
assert 'Nada foi apagado' in lines[-1]
|
||||
with db.connect() as c:
|
||||
assert c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (order,)).fetchone()
|
||||
|
||||
lines.clear()
|
||||
assert launch_reset.main(['--confirmar', 'APAGAR'], out=lines.append) == 0, lines
|
||||
with db.connect() as c:
|
||||
for table in ('orders', 'quotes', 'payment_intents', 'movements', 'outbox'):
|
||||
assert c.execute(f'SELECT count(*) AS n FROM dtf_local.{table}').fetchone()['n'] == 0, table
|
||||
assert not c.execute('''SELECT 1 FROM dtf_local.uploads WHERE purged_at IS NULL
|
||||
AND expires_at>now()''').fetchone()
|
||||
assert c.execute('SELECT count(*) AS n FROM dtf_local.operators').fetchone()['n'] >= 1
|
||||
assert 'Apagado.' in lines and any('#1' in line for line in lines), lines
|
||||
print('PASS: launch cleanup refuses real payments, counts first, then removes test orders and quotes')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run()
|
||||
38
tests/test_cnpj.py
Normal file
38
tests/test_cnpj.py
Normal file
@@ -0,0 +1,38 @@
|
||||
"""The CNPJ registry lookup against a fake BrasilAPI. Runs where httpx is installed."""
|
||||
import unittest
|
||||
|
||||
import httpx
|
||||
|
||||
from app import cnpj
|
||||
|
||||
|
||||
def transport(status, body=None):
|
||||
return httpx.MockTransport(lambda request: httpx.Response(status, json=body or {}))
|
||||
|
||||
|
||||
class CnpjTests(unittest.TestCase):
|
||||
def test_names_come_from_the_registry_tidied(self):
|
||||
found = cnpj.fetch('11222333000181', transport(200, {
|
||||
'razao_social': 'LOJA TESTE COMERCIO LTDA ', 'nome_fantasia': 'Loja Teste'}))
|
||||
self.assertEqual(found, {'legal_name': 'LOJA TESTE COMERCIO LTDA', 'trade_name': 'Loja Teste'})
|
||||
self.assertEqual(cnpj.fetch('11222333000181', transport(200, {'razao_social': 'X LTDA', 'nome_fantasia': ''})),
|
||||
{'legal_name': 'X LTDA', 'trade_name': None})
|
||||
|
||||
def test_an_unknown_cnpj_has_no_names_and_an_outage_is_an_error(self):
|
||||
self.assertEqual(cnpj.fetch('00000000000000', transport(404)), {'legal_name': None, 'trade_name': None})
|
||||
with self.assertRaises(httpx.HTTPError):
|
||||
cnpj.fetch('11222333000181', transport(503))
|
||||
|
||||
def test_new_tiny_contacts_are_named_after_the_company(self):
|
||||
from app.tiny import contact_payload
|
||||
order = {'customer': {'cnpj': '11222333000181', 'mail': 'loja@example.test', 'zap': '16999999999'},
|
||||
'destination': None}
|
||||
named = contact_payload(order, {'legal': 'LOJA TESTE LTDA', 'trade': 'Loja Teste'})
|
||||
self.assertEqual((named['nome'], named['fantasia']), ('LOJA TESTE LTDA', 'Loja Teste'))
|
||||
plain = contact_payload(order)
|
||||
self.assertEqual(plain['nome'], 'loja@example.test')
|
||||
self.assertNotIn('fantasia', plain)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
71
tests/thumbnail_backfill_test.py
Normal file
71
tests/thumbnail_backfill_test.py
Normal file
@@ -0,0 +1,71 @@
|
||||
"""Old orders get their artwork picture from the stored image, once.
|
||||
|
||||
Run inside the API container: python -m tests.thumbnail_backfill_test
|
||||
"""
|
||||
import io
|
||||
from uuid import uuid4
|
||||
|
||||
from PIL import Image
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from app.core import db
|
||||
from ops import backfill_thumbnails
|
||||
|
||||
|
||||
def png(width, height):
|
||||
out = io.BytesIO()
|
||||
Image.new('RGBA', (width, height), (255, 0, 0, 128)).save(out, 'PNG')
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
class Storage:
|
||||
"""Objects by key, written where the worker asks."""
|
||||
def __init__(self, objects):
|
||||
self.objects, self.fetched = objects, []
|
||||
|
||||
def fetch(self, key, path):
|
||||
"""Other uploads in a shared database are not this test's: they fail like unreadable files."""
|
||||
self.fetched.append(key)
|
||||
with open(path, 'wb') as handle:
|
||||
handle.write(self.objects[key])
|
||||
|
||||
|
||||
def run():
|
||||
owner, quote, order = uuid4(), uuid4(), uuid4()
|
||||
image, drawing = uuid4(), uuid4()
|
||||
files = {image: ('folha.png', png(1200, 3000)), drawing: ('arte.cdr', b'CDR')}
|
||||
storage = Storage({f'backfill/{uid}': content for uid, (_, content) in files.items()})
|
||||
try:
|
||||
with db.connect() as c:
|
||||
for uid, (name, content) in files.items():
|
||||
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
|
||||
expires_at,scan_state) VALUES(%s,%s,%s,%s,%s,'m',true,now()+interval '1 day','clean')''',
|
||||
(uid, owner, name, len(content), f'backfill/{uid}'))
|
||||
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)',
|
||||
(order, quote, owner, Jsonb({'items': items, 'total_cents': 1490}), Jsonb({'provider': 'teste'})))
|
||||
lines = []
|
||||
assert backfill_thumbnails.main([], out=lines.append, storage=storage) == 0
|
||||
with db.connect() as c:
|
||||
made = c.execute('SELECT mime,data FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (image,)).fetchone()
|
||||
assert made and made['mime'] == 'image/webp'
|
||||
with Image.open(io.BytesIO(bytes(made['data']))) as picture:
|
||||
assert picture.format == 'WEBP' and picture.size[0] <= 480 and picture.size[1] <= 720, picture.size
|
||||
assert not c.execute('SELECT 1 FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (drawing,)).fetchone()
|
||||
# The CDR is never fetched; a second run does not fetch the image again.
|
||||
assert storage.fetched.count(f'backfill/{image}') == 1 and f'backfill/{drawing}' not in storage.fetched
|
||||
backfill_thumbnails.main([], out=lines.append, storage=storage)
|
||||
assert storage.fetched.count(f'backfill/{image}') == 1
|
||||
print('PASS: old orders get a WebP picture from a stored PNG; drawings are skipped; a rerun repeats nothing')
|
||||
finally:
|
||||
with db.connect() as c:
|
||||
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s)', (list(files),))
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
|
||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
|
||||
c.execute('DELETE FROM dtf_local.uploads WHERE id=ANY(%s)', (list(files),))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run()
|
||||
@@ -61,7 +61,13 @@ def run():
|
||||
link=customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download')
|
||||
assert urlopen(link['url']).read()==b'LOCAL FINAL VERSION ONE'
|
||||
guest=Client();guest.call('/session');guest.call('/customer/orders/'+oid+'/files/'+final['id']+'/download',expected=404)
|
||||
version=move('fil',version);version=move('imp',version);version=move('cor',version)
|
||||
version=move('fil',version)
|
||||
# The print queue's files come named after their order, straight from storage.
|
||||
queued=customer.call('/operator/queue/finals',operator=True)['files']
|
||||
mine=[f for f in queued if urlopen(f['url']).read()==b'LOCAL FINAL VERSION ONE']
|
||||
assert len(mine)==1 and mine[0]['name'].startswith('pedido-%d-item-1-' % mine[0]['number']), queued
|
||||
customer.call('/operator/queue/finals',expected=401)
|
||||
version=move('imp',version);version=move('cor',version)
|
||||
customer.call('/customer/orders/'+oid+'/files/'+final['id']+'/download',expected=404)
|
||||
premature_final=upload_bytes(customer,b'FINAL BEFORE CUSTOMER CORRECTION',order_id=oid)
|
||||
version=customer.call('/operator/orders/'+oid+'/final-files',
|
||||
|
||||
@@ -51,8 +51,8 @@ input[type=file]{font-size:14px;color:var(--muted);max-width:100%}
|
||||
.tabs button{display:flex;align-items:center;gap:8px;padding:0 14px;border:0;border-bottom:2px solid transparent;background:none;color:var(--muted);font-weight:600;font-size:14.5px}
|
||||
.tabs button[aria-selected=true]{color:var(--tx);font-weight:700;border-bottom-color:var(--accent)}
|
||||
.tabs .count{font-family:var(--mono);font-size:13.5px;color:var(--muted)}
|
||||
.searchbox{position:relative;margin-left:auto}
|
||||
.search{display:flex;align-items:center;gap:8px;width:380px;height:38px;padding:0 12px;border:1px solid var(--line2);border-radius:9px;background:var(--card);color:var(--faint)}
|
||||
.searchbox{position:relative;margin-left:auto;flex:0 1 380px;min-width:200px}
|
||||
.search{display:flex;align-items:center;gap:8px;width:100%;box-sizing:border-box;height:38px;padding:0 12px;border:1px solid var(--line2);border-radius:9px;background:var(--card);color:var(--faint)}
|
||||
.search:focus-within{border-color:var(--accent);box-shadow:0 0 0 3px rgba(255,139,43,.18)}
|
||||
.search input{flex:1;min-width:0;border:0;background:transparent;height:auto;padding:0;outline:none}
|
||||
.search kbd{font:inherit;font-size:12px;padding:0 6px;border:1px solid var(--line3);border-radius:5px;color:var(--faint)}
|
||||
@@ -74,6 +74,8 @@ input[type=file]{font-size:14px;color:var(--muted);max-width:100%}
|
||||
.tinydot::before{content:"";width:8px;height:8px;border-radius:999px;background:var(--dot,#5B6168)}
|
||||
.tinydot:empty{display:none}
|
||||
.who{font-size:14px;color:var(--muted);white-space:nowrap;max-width:220px;overflow:hidden;text-overflow:ellipsis}
|
||||
/* With five tabs, the operator's e-mail is the first thing to give way; it stays on Sair's tooltip. */
|
||||
@media (max-width:1560px){.who{display:none}}
|
||||
#status{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);z-index:20;margin:0;max-width:min(640px,calc(100vw - 32px));padding:10px 16px;border-radius:10px;border:1px solid var(--line3);background:#1E2226;color:var(--tx);font-size:14px;box-shadow:0 10px 30px rgba(0,0,0,.45)}
|
||||
#status:empty,#login-status:empty{display:none}
|
||||
#status.error{border-color:var(--bad-line);color:var(--bad)}
|
||||
@@ -95,6 +97,8 @@ main{padding:0 24px 24px}
|
||||
.col-head .swatch{width:10px;height:10px;border-radius:3px;background:var(--c)}
|
||||
.col-head .n{margin-left:auto;font-family:var(--mono);font-size:13.5px;color:var(--muted)}
|
||||
.col-head small{font-size:13.5px;color:var(--faint)}
|
||||
.col-head .col-sub{justify-content:space-between;min-height:30px}
|
||||
.col-head .col-sub small{white-space:nowrap}
|
||||
.col .empty{font-size:13.5px;color:var(--faint);padding:8px 2px}
|
||||
.card{text-align:left;display:flex;flex-direction:column;gap:8px;padding:12px;border-radius:10px;border:1px solid var(--line2);background:var(--card);width:100%}
|
||||
.card:hover,.card.open{border-color:var(--line3);background:#1E2226}
|
||||
@@ -220,6 +224,28 @@ main{padding:0 24px 24px}
|
||||
.field select,.field input{height:38px;min-width:160px;padding:0 10px;border-radius:8px;border:1px solid var(--line3);background:var(--bg);color:var(--tx)}
|
||||
.field input{min-width:110px;width:110px}
|
||||
.issue input{width:320px}
|
||||
.pagehead{display:flex;align-items:center;gap:16px;flex-wrap:wrap}
|
||||
.statchips{display:flex;gap:8px;margin-left:auto}
|
||||
.stats-note{margin:-12px 0 0;font-size:13.5px}
|
||||
.kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px}
|
||||
.kpi{display:flex;flex-direction:column;gap:4px;padding:14px 16px;border:1px solid var(--line2);border-radius:12px;background:var(--card)}
|
||||
.kpi span{font-size:13.5px;color:var(--muted)}
|
||||
.kpi b{font-size:24px;font-weight:700;letter-spacing:-.01em;font-variant-numeric:proportional-nums}
|
||||
.kpi small{font-size:13px;color:var(--faint)}
|
||||
.statbox{padding:16px 18px;border:1px solid var(--line2);border-radius:12px;background:var(--card)}
|
||||
.chart{position:relative}
|
||||
.chart svg{display:block;width:100%;height:auto}
|
||||
.chart .grid{stroke:var(--line);stroke-width:1}
|
||||
.chart .tick{fill:var(--faint);font-size:12px;font-family:var(--mono)}
|
||||
.chart .bar{fill:var(--accent)}
|
||||
.chart .hit{fill:transparent;cursor:default}
|
||||
.chart .hit:hover{fill:rgba(255,255,255,.03)}
|
||||
.chart .tip{position:absolute;transform:translate(-50%,calc(-100% - 8px));pointer-events:none;padding:6px 10px;border-radius:8px;
|
||||
background:var(--card2);border:1px solid var(--line3);font-size:13px;white-space:nowrap;color:var(--tx)}
|
||||
.charttable{margin-top:10px;font-size:13.5px;color:var(--muted)}
|
||||
.charttable summary{cursor:pointer}
|
||||
.charttable table{margin-top:8px}
|
||||
#stats-stages .swatch{display:inline-block;width:10px;height:10px;border-radius:3px;background:var(--c);margin-right:8px}
|
||||
.grid4{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:12px}
|
||||
.integration{display:flex;flex-direction:column;gap:10px;padding:16px;border-radius:12px;border:1px solid var(--line2);background:var(--card)}
|
||||
.integration .head{display:flex;align-items:center;gap:8px}
|
||||
@@ -235,7 +261,7 @@ table.log td{padding:10px 12px;border-bottom:1px solid #1E2226;vertical-align:to
|
||||
|
||||
@media (max-width:900px){
|
||||
.top{flex-wrap:wrap;height:auto;padding:10px 16px;gap:10px}
|
||||
.searchbox{order:5;width:100%;margin-left:0}
|
||||
.searchbox{order:5;width:100%;flex-basis:100%;margin-left:0}
|
||||
.search{width:100%}
|
||||
.results{width:100%}
|
||||
main{padding:0 16px 16px}
|
||||
@@ -329,6 +355,7 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom}
|
||||
.copy:hover{color:var(--tx);border-color:var(--line3)}
|
||||
.zapbtn{display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 10px;border-radius:7px;background:rgba(111,209,156,.1);color:var(--ok);text-decoration:none;font-size:13px;font-weight:600}
|
||||
.zapbtn:hover{background:rgba(111,209,156,.18)}
|
||||
.zapbtn.big{height:36px;padding:0 14px;font-size:14px;border-radius:8px}
|
||||
|
||||
/* Facts: small labelled boxes */
|
||||
.factgrid{margin:0;display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:6px}
|
||||
@@ -390,7 +417,7 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom}
|
||||
.card.drop-after{box-shadow:0 3px 0 0 var(--accent)}
|
||||
|
||||
/* "Atualizar" and how often it happens by itself, as one control. */
|
||||
.refresh{display:inline-flex;align-items:stretch;border:1px solid var(--line2);border-radius:8px;overflow:hidden}
|
||||
.refresh{flex-shrink:0;display:inline-flex;align-items:stretch;border:1px solid var(--line2);border-radius:8px;overflow:hidden}
|
||||
.refresh .btn{border:0;border-radius:0;display:inline-flex;align-items:center;gap:6px}
|
||||
.refresh select{height:36px;padding:0 28px 0 10px;border:0;border-left:1px solid var(--line2);background:transparent;color:var(--muted);font:inherit;font-size:13.5px;font-weight:600;cursor:pointer}
|
||||
.refresh select{width:88px;height:36px;padding:0 24px 0 10px;border:0;border-left:1px solid var(--line2);background:transparent;color:var(--muted);font:inherit;font-size:13.5px;font-weight:600;cursor:pointer}
|
||||
.refresh select option{background:var(--card);color:var(--tx)}
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
<button type="button" data-tab="board" aria-selected="true">Produção <span class="count" id="count-board"></span></button>
|
||||
<button type="button" data-tab="quotes" aria-selected="false">Cotações <span class="badge" id="badge-quotes"></span></button>
|
||||
<button type="button" data-tab="payments" aria-selected="false">Pagamentos <span class="badge warn" id="badge-payments"></span></button>
|
||||
<button type="button" data-tab="stats" aria-selected="false">Números</button>
|
||||
<button type="button" data-tab="integrations" aria-selected="false">Integrações</button>
|
||||
</nav>
|
||||
<div class="searchbox">
|
||||
@@ -67,6 +68,15 @@
|
||||
<h1>Pagamentos</h1>
|
||||
<section id="payments"></section>
|
||||
</section>
|
||||
<section id="tab-stats" class="page" hidden>
|
||||
<div class="pagehead"><h1>Números</h1><div class="statchips" id="stats-period"></div></div>
|
||||
<p class="faint stats-note">Pedidos pagos no período. Pedidos de teste e cancelados ficam de fora.</p>
|
||||
<div class="kpis" id="stats-kpis"></div>
|
||||
<section class="statbox"><h2>Metros por dia</h2><div class="chart" id="stats-chart"></div></section>
|
||||
<section class="statbox"><h2>Tempo em cada etapa</h2>
|
||||
<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>
|
||||
<section id="tab-integrations" class="page" hidden>
|
||||
<h1>Integrações</h1>
|
||||
<section><div class="grid4" id="integrations"></div></section>
|
||||
|
||||
132
web/kanban.js
132
web/kanban.js
@@ -34,7 +34,10 @@ let quoteQuery='', quoteProduct='', quoteLayout='', quoteFlag='', quoteTimer=nul
|
||||
// Uploads that have an artwork picture (the customer's browser made it). Every
|
||||
// list the API returns says which, so only pictures that exist are asked for.
|
||||
const THUMBS=new Set();
|
||||
const absorb=r=>{for(const id of r?.thumbnails||[])THUMBS.add(String(id));return r;};
|
||||
// Company names by CNPJ, from the public registry (app/cnpj.py).
|
||||
const NAMES=new Map();
|
||||
const absorb=r=>{for(const id of r?.thumbnails||[])THUMBS.add(String(id));
|
||||
for(const [cnpj,name] of Object.entries(r?.names||{}))NAMES.set(cnpj,name);return r;};
|
||||
let olderFinished=[], finishedMore=null;
|
||||
|
||||
const money=cents=>(cents/100).toLocaleString('pt-BR',{style:'currency',currency:'BRL'});
|
||||
@@ -123,13 +126,15 @@ function facts(pairs){
|
||||
// receives the delivery), else the e-mail. With a name, the e-mail is the
|
||||
// second line, still searchable.
|
||||
function buyer(content){
|
||||
const c=content.customer||{}, name=(c.name||content.destination?.recipient||'').trim();
|
||||
return {title:name||c.mail, mail:name?c.mail:''};
|
||||
const c=content.customer||{}, company=NAMES.get(String(c.cnpj||'').replace(/\D/g,''));
|
||||
// The trade name people know the shop by, else its razão social.
|
||||
const name=(c.name||company?.trade||company?.legal||content.destination?.recipient||'').trim();
|
||||
return {title:name||c.mail, mail:name?c.mail:'', legal:company?.legal||''};
|
||||
}
|
||||
function buyerBlock(content,className){
|
||||
const who=buyer(content);
|
||||
const box=node('div',undefined,'buyer '+(className||''));
|
||||
const title=node('b',who.title);title.title=who.mail||who.title;box.append(title);
|
||||
const title=node('b',who.title);title.title=[who.legal,who.mail].filter(Boolean).join(' · ')||who.title;box.append(title);
|
||||
if(who.mail)box.append(node('span',who.mail,'buyer-mail'));
|
||||
return box;
|
||||
}
|
||||
@@ -172,6 +177,16 @@ function download(uid){return async()=>{
|
||||
const result=await api('/uploads/'+uid+'/download');
|
||||
const link=node('a');link.href=result.url;link.referrerPolicy='no-referrer';link.download=result.name;link.click();
|
||||
};}
|
||||
async function downloadQueue(){
|
||||
const {files}=await api('/queue/finals');
|
||||
if(!files.length){say('Nenhum arquivo final aprovado na fila.');return;}
|
||||
say('Baixando '+files.length+(files.length>1?' arquivos':' arquivo')+' da fila… Se o navegador perguntar, permita vários downloads.',false,8000);
|
||||
// One at a time: browsers drop clicks that come too close together.
|
||||
for(const file of files){
|
||||
const link=node('a');link.href=file.url;link.referrerPolicy='no-referrer';link.download=file.name;link.click();
|
||||
await new Promise(r=>setTimeout(r,700));
|
||||
}
|
||||
}
|
||||
function manifest(production){
|
||||
const url=URL.createObjectURL(new Blob([JSON.stringify(production,null,2)],{type:'application/json'}));
|
||||
const link=node('a');link.href=url;link.download='dtf-layout-'+production.sources[0].upload_id.slice(0,8)+'.json';
|
||||
@@ -243,18 +258,18 @@ async function load(quiet=false){
|
||||
function showTab(name){
|
||||
tab=name;
|
||||
for(const b of document.querySelectorAll('[data-tab]'))b.setAttribute('aria-selected',String(b.dataset.tab===name));
|
||||
for(const id of ['board','quotes','payments','integrations'])$('tab-'+id).hidden=name!==id;
|
||||
const lists={quotes:loadQuotes,payments:loadIssues,integrations:loadEvents};
|
||||
for(const id of ['board','quotes','payments','stats','integrations'])$('tab-'+id).hidden=name!==id;
|
||||
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:loadEvents};
|
||||
if(board&&lists[name])lists[name]().catch(e=>say(e.message,true));
|
||||
}
|
||||
function render(){
|
||||
$('who').textContent=board.operator||'';
|
||||
$('who').textContent=board.operator||'';$('logout').title=board.operator?'Sair ('+board.operator+')':'Sair';
|
||||
$('count-board').textContent=String(board.orders.filter(o=>o.state!=='fin'&&!o.cancelled_at).length);
|
||||
$('badge-quotes').textContent=board.pending_total?String(board.pending_total):'';
|
||||
$('badge-payments').textContent=board.payment_issues_total?String(board.payment_issues_total):'';
|
||||
tinyHeader();renderBoard();renderIntegrations();
|
||||
// Lists live on their own pages of the API; refresh the one being looked at.
|
||||
const lists={quotes:loadQuotes,payments:loadIssues,integrations:loadEvents};
|
||||
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:loadEvents};
|
||||
if(lists[tab])lists[tab]().catch(e=>say(e.message,true));
|
||||
if(openOrder){const order=board.orders.find(o=>o.id===openOrder);if(order)renderPanel(order);else closePanel();}
|
||||
}
|
||||
@@ -315,7 +330,13 @@ function renderBoard(){
|
||||
// Finished orders are a recent window, not the whole history: say so.
|
||||
const count=state==='fin'&&board.finished_total>orders.length?orders.length+' de '+board.finished_total:String(orders.length);
|
||||
line.append(swatch,node('h2',title),node('span',count,'n'));
|
||||
head.append(line,node('small',orders.length?metres(total)+' no total':'vazio'));
|
||||
const sub=node('div',undefined,'col-sub');sub.append(node('small',orders.length?metres(total)+' no total':'vazio'));
|
||||
// The print queue's files, all at once, to import into FlexiPRINT.
|
||||
if(state==='fil'&&orders.length){
|
||||
const all=downloadButton('Baixar todos',downloadQueue,'btn ghost small');all.title='Baixar os arquivos finais de todos os pedidos da fila';
|
||||
sub.append(all);
|
||||
}
|
||||
head.append(line,sub);
|
||||
column.append(head);
|
||||
for(const order of orders)column.append(card(order));
|
||||
if(state==='fin'&&finishedMore&&filter==='all')moreButton(column,true,loadOlderFinished);
|
||||
@@ -490,6 +511,9 @@ function moves(order){
|
||||
},'btn danger');remove.style.alignSelf='flex-start';
|
||||
box.append(note,remove);return box;
|
||||
}
|
||||
// In correction, the customer has to be told: a message ready to send on
|
||||
// WhatsApp with the reason and where to send the new file.
|
||||
const waiting=order.state==='cor'?correctionNotice(order):null;
|
||||
const row=node('div',undefined,'moves');
|
||||
// One form open at a time under the buttons.
|
||||
const forms=[];
|
||||
@@ -572,7 +596,26 @@ function moves(order){
|
||||
const sendFix=node('button','Enviar para correção','btn danger');
|
||||
reason.append(text,sendFix);
|
||||
reason.onsubmit=async e=>{e.preventDefault();sendFix.disabled=true;try{await move(order,'cor',text.value.trim());}catch(error){say(error.message,true);sendFix.disabled=false;}};
|
||||
box.append(...(step?[step]:[]),row,...(sub.children.length?[sub]:[]),...forms.filter(f=>!f.parentNode));return box;
|
||||
box.append(...(waiting?[waiting]:[]),...(step?[step]:[]),row,...(sub.children.length?[sub]:[]),...forms.filter(f=>!f.parentNode));return box;
|
||||
}
|
||||
function correctionNotice(order){
|
||||
const s=order.snapshot, reason=order.correction_reason||'';
|
||||
const link=board.site_origin+'/conta/pedidos?order='+order.id;
|
||||
const message='Olá! Aqui é da Dropstar. O seu pedido '+orderCode(order.id)+' precisa de um ajuste na arte antes da impressão'+
|
||||
(reason?': '+reason:'.')+'\n\nEnvie o arquivo corrigido por aqui: '+link;
|
||||
const text=node('div');
|
||||
text.append(node('b','Aguardando a correção do cliente'),node('span',reason?'Motivo: '+reason:'O motivo está no histórico.'));
|
||||
const actions=node('div',undefined,'stepactions');
|
||||
const zap=whatsappLink(s.customer.zap);
|
||||
if(zap){
|
||||
const a=node('a','Avisar no WhatsApp','zapbtn big');a.href=zap+'?text='+encodeURIComponent(message);
|
||||
a.target='_blank';a.rel='noopener noreferrer';a.prepend(icon(ICON_CHAT));actions.append(a);
|
||||
}
|
||||
const copy=button('Copiar mensagem',async()=>{await navigator.clipboard.writeText(message);say('Mensagem copiada.');},'btn ghost');
|
||||
actions.append(copy);
|
||||
text.append(actions);
|
||||
if(!zap)text.append(node('span','Sem WhatsApp no pedido: envie a mensagem para '+s.customer.mail+'.'));
|
||||
const box=node('div',undefined,'nextstep lead');box.append(node('span','!','nextmark'),text);return box;
|
||||
}
|
||||
// ---- Final files: the file each item is printed from, approved by an operator.
|
||||
const finalDone=order=>order.snapshot.items.every((_,index)=>(order.final_items||[]).includes(index));
|
||||
@@ -721,6 +764,75 @@ function historySection(order,rows,section){
|
||||
section.replaceChildren(node('p','Histórico','eyebrow'),list);
|
||||
}
|
||||
|
||||
// ---- Numbers -------------------------------------------------------------
|
||||
|
||||
let statsDays=30;
|
||||
function duration(hours){
|
||||
if(hours===null||hours===undefined)return '—';
|
||||
if(hours<1)return Math.max(1,Math.round(hours*60))+' min';
|
||||
if(hours<48)return (hours<10?hours.toFixed(1):Math.round(hours).toString()).replace('.',',')+' h';
|
||||
return Math.round(hours/24)+' dias';
|
||||
}
|
||||
async function loadStats(){
|
||||
const data=await api('/stats?days='+statsDays);
|
||||
$('stats-period').replaceChildren(...[[7,'7 dias'],[30,'30 dias'],[90,'90 dias']].map(([days,label])=>{
|
||||
const b=node('button',label,'chip');b.type='button';b.setAttribute('aria-pressed',String(days===statsDays));
|
||||
b.onclick=()=>{statsDays=days;loadStats().catch(e=>say(e.message,true));};return b;}));
|
||||
const kpi=(label,value,note)=>{const k=node('div',undefined,'kpi');k.append(node('span',label),node('b',value));if(note)k.append(node('small',note));return k;};
|
||||
const pct=data.orders?Math.round(100*data.corrected/data.orders):0;
|
||||
$('stats-kpis').replaceChildren(
|
||||
kpi('Pedidos pagos',String(data.orders)),
|
||||
kpi('Metros vendidos',metres(data.metres)),
|
||||
kpi('Recebido',money(data.cents),'com frete'),
|
||||
kpi('Ticket médio',data.orders?money(Math.round(data.cents/data.orders)):'—'),
|
||||
kpi('Pedidos com correção',String(data.corrected),data.orders?pct+'% dos pedidos':null),
|
||||
kpi('Do pagamento ao Finalizado',duration(data.lead.median_hours),data.lead.orders?'mediana de '+data.lead.orders+' pedidos':'nenhum finalizado'));
|
||||
statsChart($('stats-chart'),data.daily);
|
||||
const rows=['rec','tra','fil','imp','cor'].map(state=>{
|
||||
const tr=node('tr'),name=node('td'),sw=node('span',undefined,'swatch');sw.style.setProperty('--c',STAGE_COLORS[state]);
|
||||
name.append(sw,board.states[state]);
|
||||
const st=data.stages[state], now=data.waiting[state];
|
||||
tr.append(name,node('td',st?duration(st.median_hours):'—'),node('td',st?String(st.orders):'0'),
|
||||
node('td',now?now.orders+(now.orders>1?' pedidos':' pedido')+' · o mais antigo há '+duration(now.oldest_hours):'nenhum'));
|
||||
return tr;});
|
||||
$('stats-stages').replaceChildren(...rows);
|
||||
}
|
||||
// Metres per day: one series, columns from one baseline, a tooltip per day
|
||||
// and the same numbers as a table under the chart.
|
||||
function statsChart(box,daily){
|
||||
const ns='http://www.w3.org/2000/svg', w=Math.max(320,box.clientWidth||800), h=220, left=44, bottom=26, top=10;
|
||||
const max=Math.max(...daily.map(d=>d.metres),0);
|
||||
const step=max<=0?1:(()=>{const raw=max/4, p=10**Math.floor(Math.log10(raw)), f=raw/p;return (f<=1?1:f<=2?2:f<=5?5:10)*p;})();
|
||||
const ceiling=step*Math.max(1,Math.ceil(max/step));
|
||||
const svg=document.createElementNS(ns,'svg');svg.setAttribute('viewBox','0 0 '+w+' '+h);svg.setAttribute('role','img');
|
||||
svg.setAttribute('aria-label','Metros vendidos por dia nos últimos '+daily.length+' dias');
|
||||
const el=(tag,attrs)=>{const e=document.createElementNS(ns,tag);for(const [k,v] of Object.entries(attrs))e.setAttribute(k,v);return e;};
|
||||
const y=v=>top+(h-top-bottom)*(1-v/ceiling);
|
||||
for(let v=0;v<=ceiling+1e-9;v+=step){
|
||||
svg.append(el('line',{x1:left,x2:w,y1:y(v),y2:y(v),class:'grid'}));
|
||||
const t=el('text',{x:left-8,y:y(v)+4,class:'tick','text-anchor':'end'});t.textContent=v.toLocaleString('pt-BR');svg.append(t);
|
||||
}
|
||||
const band=(w-left)/daily.length, bar=Math.min(24,Math.max(2,band-2));
|
||||
const tip=node('div',undefined,'tip');tip.hidden=true;
|
||||
const label=d=>new Date(d.day+'T12:00:00').toLocaleDateString('pt-BR',{day:'2-digit',month:'2-digit'});
|
||||
const every=Math.ceil(daily.length/8);
|
||||
daily.forEach((d,i)=>{
|
||||
const x=left+band*i+(band-bar)/2, top_=y(d.metres), base=y(0), r=Math.min(4,bar/2,base-top_);
|
||||
if(d.metres>0)svg.append(el('path',{class:'bar',d:`M${x},${base}V${top_+r}Q${x},${top_} ${x+r},${top_}H${x+bar-r}Q${x+bar},${top_} ${x+bar},${top_+r}V${base}Z`}));
|
||||
if((daily.length-1-i)%every===0){const t=el('text',{x:x+bar/2,y:h-8,class:'tick','text-anchor':'middle'});t.textContent=label(d);svg.append(t);}
|
||||
const hit=el('rect',{x:left+band*i,y:top,width:band,height:h-top-bottom,class:'hit'});
|
||||
hit.onmouseenter=()=>{tip.hidden=false;tip.textContent=label(d)+' · '+d.orders+(d.orders===1?' pedido':' pedidos')+' · '+metres(d.metres);
|
||||
tip.style.left=(100*(x+bar/2)/w)+'%';tip.style.top=(100*Math.min(top_,base-4)/h)+'%';};
|
||||
hit.onmouseleave=()=>{tip.hidden=true;};
|
||||
svg.append(hit);
|
||||
});
|
||||
const table=node('details',undefined,'charttable');table.append(node('summary','Ver em tabela'));
|
||||
const t=node('table',undefined,'log');const head=node('tr');head.append(node('th','Dia'),node('th','Pedidos'),node('th','Metros'));t.append(head);
|
||||
for(const d of [...daily].reverse()){const tr=node('tr');tr.append(node('td',label(d)),node('td',String(d.orders)),node('td',metres(d.metres)));t.append(tr);}
|
||||
table.append(t);
|
||||
box.replaceChildren(svg,tip,table);
|
||||
}
|
||||
|
||||
// ---- Quotes --------------------------------------------------------------
|
||||
|
||||
function quoteMetres(q){return (q.approved||q.draft).items.reduce((s,i)=>s+Number(i.billed_metres||i.metres),0);}
|
||||
|
||||
Reference in New Issue
Block a user