feat: discount coupons (front 8.3)

Gestão creates coupons in the Site tab: a code, a percentage or an amount
per billed metre, validity, a minimum of metres, use limits in all and per
customer, one product or all, and a note; they can be paused and deleted
(kept for history). The customer types the code at checkout; the server
checks it when the quote is made and again at approval, discounts only the
eligible items after the bands (never freight or the treatment) and keeps
the coupon on the order. Tiny gets the discount, the e-mail and receipt
show it, the order panel carries a badge and Números counts orders,
metres, discount and money per coupon.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 15:24:44 -03:00
parent 07ee38d677
commit 1d0353fe54
18 changed files with 698 additions and 15 deletions

View File

@@ -22,6 +22,7 @@ jobs:
tests.test_staging_readiness \
deploy.test_production_preflight \
tests.test_pricing \
tests.test_coupons \
tests.test_secrets -v
sh -n infra/lock_dependencies.sh
@@ -73,7 +74,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 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 finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_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 finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test; do
echo "--- $suite"
$COMPOSE exec -T \
-e SITE_BASE_URL=http://site \

View File

@@ -1486,6 +1486,16 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
LEFT JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m
WHERE m.order_id=o.id AND m.to_state='fin') f ON true
WHERE {REAL_ORDER} AND {within} GROUP BY o.origin''', period).fetchall()}
# Coupons used by the period's paid orders (front 8.3): what each code
# brought in orders, billed metres, discount and money received.
coupons_used = c.execute(f'''SELECT o.snapshot->'coupon'->>'id' AS id,
o.snapshot->'coupon'->>'code' AS code, count(*) AS orders,
COALESCE(sum({metres}),0) AS metres,
COALESCE(sum((o.snapshot->'coupon'->>'discount_cents')::bigint),0) AS discount_cents,
COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents
FROM dtf_local.orders o
WHERE {REAL_ORDER} AND {within} AND o.snapshot->'coupon'->>'id' IS NOT NULL
GROUP BY 1,2 ORDER BY orders DESC, code''', period).fetchall()
# Speed (item 0.12): the browser's marks on the way to a quote, the
# Prumo's print generation and the time from payment event to card.
site_speed = c.execute(f'''WITH samples AS (
@@ -1568,7 +1578,10 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start
'average_hours': hours(row['average_hours'])} for row in stages},
'waiting': {row['state']: {'orders': row['orders'], 'oldest_hours': hours(row['oldest_hours'])} for row in waiting},
'speed': speed_figures(site_speed, print_speed, card_speed),
'machines': printed, 'rework': rework_figures(printed, redone, by_printer, undecided)}
'machines': printed, 'rework': rework_figures(printed, redone, by_printer, undecided),
'coupons': [{'id': row['id'], 'code': row['code'], 'orders': row['orders'],
'metres': float(row['metres']), 'discount_cents': int(row['discount_cents']),
'cents': int(row['cents'])} for row in coupons_used]}
def speed_figures(site, generation, card):

View File

@@ -8,7 +8,7 @@ from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException
from psycopg.types.json import Jsonb
from .. import catalog, payments
from .. import catalog, coupons, payments
from ..core import db
from ..core.auth import owner
from ..core.models import QuoteRequest
@@ -26,7 +26,11 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
if abs(item.metres*100-item.production.height_cm) > Decimal('0.02'):
raise HTTPException(422, 'A metragem não confere com a montagem enviada. Monte o pedido de novo.')
require_delivery_available(body.freight.service)
# The coupon code is stored normalized, so a quote waiting for review keeps
# the code the operator will see (front 8.3).
code = (body.coupon or '').strip().upper() or None
draft = body.model_dump(mode='json', exclude={'request_key'})
draft['coupon'] = code
digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest()
accepted_at = datetime.now(timezone.utc).isoformat()
for item in draft['items']:
@@ -36,8 +40,9 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
item['stroke_choice_at'] = accepted_at
reason = quote_review.review_reason(draft)
with db.connect() as c:
if reason is not None:
# Waits for review: check the delivery now, priced at approval.
if reason is not None or code:
# Waits for review: check the delivery now, priced at approval. A
# coupon is checked on the same priced items (front 8.3).
try:
priced = []
for item in body.items:
@@ -57,10 +62,14 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
if price_for_total != catalog.unit_cents(c, mode):
banded[mode] = price_for_total
apply_bands(priced, banded)
freight.quote(body.freight.service, body.freight.postal_code,
sum(Decimal(i['billed_metres']) for i in priced), sum(i['total_cents'] for i in priced))
if reason is not None:
freight.quote(body.freight.service, body.freight.postal_code,
sum(Decimal(i['billed_metres']) for i in priced),
sum(i['total_cents'] for i in priced))
except ValueError as exc:
raise HTTPException(422, str(exc))
if code:
coupons.check(c, code, body.customer.cnpj, priced)
rows = {}
for item in body.items:
for uid in item.uploads:

View File

@@ -6,15 +6,18 @@ scheduled (future) price may be cancelled. Approved quotes keep the price they
were approved with (app/quote_review.py); a switched-off product refuses new
quotes and approvals with 422.
"""
import re
from datetime import datetime, timedelta, timezone
from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException
from psycopg.errors import UniqueViolation
from psycopg.types.json import Jsonb
from .. import catalog
from ..core import db
from ..core.auth import audit, can
from ..core.models import SitePriceNew, SiteProductToggle
from ..core.models import CouponNew, CouponUpdate, SitePriceNew, SiteProductToggle
router = APIRouter()
@@ -123,3 +126,110 @@ def cancel_price(price_id: int, user=Depends(can('manage'))):
c.execute('DELETE FROM dtf_local.product_prices WHERE id=%s', (price_id,))
audit('site_price_cancelled', price=price_id, product=row['product'], operator=user)
return {'ok': True}
def as_utc(value):
if value is None:
return None
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
def coupon_code(value):
code = (value or '').strip().upper()
if not re.fullmatch(r'[A-Z0-9-]{3,30}', code):
raise HTTPException(422, 'O código precisa ter de 3 a 30 letras, números ou hífens.')
return code
def check_coupon(kind, value, valid_from, valid_until):
if kind == 'percent' and not 1 <= value <= 90:
raise HTTPException(422, 'A porcentagem do cupom precisa ser de 1 a 90.')
if valid_until is not None and valid_until <= valid_from:
raise HTTPException(422, 'A validade final precisa ser depois do início.')
@router.get('/api/operator/site/coupons')
def site_coupons(user=Depends(can('manage'))):
with db.connect() as c:
rows = c.execute('''SELECT c.*, (SELECT count(*) FROM dtf_local.orders o
WHERE o.snapshot->'coupon'->>'id'=c.id::text
AND o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste'
AND o.parent_id IS NULL) AS uses
FROM dtf_local.coupons c WHERE c.deleted_at IS NULL
ORDER BY c.paused, c.created_at DESC''').fetchall()
return {'coupons': [{'id': str(row['id']), 'code': row['code'], 'kind': row['kind'],
'value': row['value'], 'valid_from': row['valid_from'].isoformat(),
'valid_until': row['valid_until'].isoformat() if row['valid_until'] else None,
'min_metres': float(row['min_metres']) if row['min_metres'] is not None else None,
'max_uses': row['max_uses'], 'max_uses_per_customer': row['max_uses_per_customer'],
'product': row['product'], 'note': row['note'], 'paused': row['paused'],
'created_by': row['created_by'], 'created_at': row['created_at'].isoformat(),
'uses': row['uses']} for row in rows]}
@router.post('/api/operator/site/coupons')
def create_coupon(body: CouponNew, user=Depends(can('manage'))):
code = coupon_code(body.code)
valid_from = as_utc(body.valid_from) or datetime.now(timezone.utc)
valid_until = as_utc(body.valid_until)
check_coupon(body.kind, body.value, valid_from, valid_until)
coupon_id = uuid4()
try:
with db.connect() as c:
if c.execute('SELECT 1 FROM dtf_local.coupons WHERE code=%s AND deleted_at IS NULL',
(code,)).fetchone():
raise HTTPException(409, 'Já existe um cupom com este código.')
c.execute('''INSERT INTO dtf_local.coupons(id,code,kind,value,valid_from,valid_until,
min_metres,max_uses,max_uses_per_customer,product,note,created_by)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)''',
(coupon_id, code, body.kind, body.value, valid_from, valid_until, body.min_metres,
body.max_uses, body.max_uses_per_customer, body.product, body.note.strip(), user))
except UniqueViolation:
# Two requests with the same new code at once: the partial index decides.
raise HTTPException(409, 'Já existe um cupom com este código.')
audit('site_coupon_created', coupon=str(coupon_id), code=code, operator=user)
return {'id': str(coupon_id)}
@router.post('/api/operator/site/coupons/{coupon_id}')
def update_coupon(coupon_id: UUID, body: CouponUpdate, user=Depends(can('manage'))):
fields = body.model_dump(exclude_unset=True)
# The form never sends null for these; a null would try to write NULL into
# a NOT NULL column, so an explicit null means "keep what is there".
for name in ('kind', 'value', 'paused'):
if name in fields and fields[name] is None:
fields.pop(name)
with db.connect() as c:
row = c.execute('''SELECT * FROM dtf_local.coupons
WHERE id=%s AND deleted_at IS NULL FOR UPDATE''', (coupon_id,)).fetchone()
if not row:
raise HTTPException(404, 'Cupom não encontrado.')
kind = fields.get('kind', row['kind'])
value = fields.get('value', row['value'])
valid_from = as_utc(fields['valid_from']) if 'valid_from' in fields else row['valid_from']
valid_from = valid_from or row['valid_from']
valid_until = as_utc(fields['valid_until']) if 'valid_until' in fields else row['valid_until']
check_coupon(kind, value, valid_from, valid_until)
if 'valid_from' in fields:
fields['valid_from'] = valid_from
if 'valid_until' in fields:
fields['valid_until'] = valid_until
if 'note' in fields:
fields['note'] = (fields['note'] or '').strip()
if fields:
names = list(fields)
c.execute(f'''UPDATE dtf_local.coupons SET {', '.join(f'{name}=%s' for name in names)}
WHERE id=%s''', (*[fields[name] for name in names], coupon_id))
audit('site_coupon_updated', coupon=str(coupon_id), operator=user)
return {'ok': True}
@router.post('/api/operator/site/coupons/{coupon_id}/delete')
def delete_coupon(coupon_id: UUID, user=Depends(can('manage'))):
with db.connect() as c:
row = c.execute('''UPDATE dtf_local.coupons SET deleted_at=now()
WHERE id=%s AND deleted_at IS NULL RETURNING code''', (coupon_id,)).fetchone()
if not row:
raise HTTPException(404, 'Cupom não encontrado.')
audit('site_coupon_deleted', coupon=str(coupon_id), code=row['code'], operator=user)
return {'ok': True}

View File

@@ -267,6 +267,8 @@ class QuoteRequest(StrictModel):
proof: bool = False
# "Quero o tratamento pelo designer": a fixed service line, when priced (front 5).
treatment: bool = False
# A coupon code typed at checkout (front 8.3); the server prices it.
coupon: str | None = Field(default=None, max_length=30)
# What the browser measured while the customer built the cart (item 0.12).
timings: ClientTimings | None = None
@@ -371,6 +373,34 @@ class SitePriceNew(StrictModel):
bands: list[PriceBand] = Field(default_factory=list)
class CouponNew(StrictModel):
"""Um cupom novo, criado na aba Site (front 8.3)."""
code: str = Field(min_length=1, max_length=30)
kind: Literal['percent', 'per_metre']
value: int = Field(gt=0, le=10000000, strict=True)
valid_from: datetime | None = None
valid_until: datetime | None = None
min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1)
max_uses: int | None = Field(default=None, gt=0, strict=True)
max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True)
product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None
note: str = Field(default='', max_length=1000)
class CouponUpdate(StrictModel):
"""Os campos de um cupom que podem mudar; o código fica como foi criado."""
kind: Literal['percent', 'per_metre'] | None = None
value: int | None = Field(default=None, gt=0, le=10000000, strict=True)
valid_from: datetime | None = None
valid_until: datetime | None = None
min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1)
max_uses: int | None = Field(default=None, gt=0, strict=True)
max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True)
product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None
note: str | None = Field(default=None, max_length=1000)
paused: bool | None = None
class Contraction(StrictModel):
item_index: int = Field(ge=0, le=100)
# None returns the item to the class the browser measured.

81
app/coupons.py Normal file
View File

@@ -0,0 +1,81 @@
"""Discount coupons typed by the customer at checkout (Fase 2, front 8.3).
One coupon per order. It is checked when the quote is created and again at
approval; only paid orders count against its limits, so a cart that waits or
expires never spends a use. The discount is computed on the server after the
bands of app/catalog.py, on the eligible items only, and never on freight or
the treatment. An approved quote keeps the coupon it was approved with.
"""
from decimal import Decimal, ROUND_FLOOR
from . import catalog
# A test order, a cancelled one and a proof card are not a sale (as the
# board's REAL_ORDER): they do not spend a coupon use.
PAID_ORDER = ("o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste' "
"AND o.parent_id IS NULL")
def eligible_items(items, product):
"""The items a coupon applies to: all of them, or one product's."""
return [item for item in items if product is None or item.get('mode') == product]
def discount_cents(kind, value, items):
"""The discount on the eligible items, in cents. Percent: floor of the
items' total. Per metre: the value times their billed metres, floored.
Never more than the items' total."""
total = sum(int(item.get('total_cents') or 0) for item in items)
if kind == 'percent':
discount = int((Decimal(total) * value / 100).to_integral_value(rounding=ROUND_FLOOR))
elif kind == 'per_metre':
metres = sum(Decimal(str(item.get('billed_metres') or 0)) for item in items)
discount = int((metres * value).to_integral_value(rounding=ROUND_FLOOR))
else:
raise ValueError('Invalid coupon kind')
return max(0, min(discount, total))
def metres_label(value):
"""5,5 m: how a minimum reads on the Site."""
return f'{Decimal(value).normalize():f}'.replace('.', ',')
def check(c, code, customer_document, priced_items):
"""The coupon for this cart and customer, or a 422 saying why not.
Returns {'id', 'code', 'discount_cents'}."""
# Imported here so the pure helpers above load without the web framework
# (tests/test_coupons.py runs on the host, where FastAPI is not installed).
from fastapi import HTTPException
code = (code or '').strip().upper()
row = c.execute('''SELECT *, now() AS now FROM dtf_local.coupons
WHERE code=%s AND deleted_at IS NULL''', (code,)).fetchone()
if not row:
raise HTTPException(422, 'Cupom não encontrado.')
if row['paused']:
raise HTTPException(422, 'Este cupom está pausado.')
if row['valid_from'] > row['now']:
raise HTTPException(422, 'Este cupom ainda não começou.')
if row['valid_until'] is not None and row['valid_until'] <= row['now']:
raise HTTPException(422, 'Este cupom expirou.')
eligible = eligible_items(priced_items, row['product'])
if row['product'] and not eligible:
raise HTTPException(422, f'Este cupom vale só para {catalog.TITLES[row["product"]]}.')
metres = sum(Decimal(str(item.get('billed_metres') or 0)) for item in eligible)
if row['min_metres'] is not None and metres < row['min_metres']:
raise HTTPException(422, f'Este cupom pede pelo menos {metres_label(row["min_metres"])} m.')
# Uses count only paid orders: the limit is spent at payment, not at the
# quote, and an order already paid is never refused afterwards.
used = c.execute(f'''SELECT count(*) AS n FROM dtf_local.orders o
WHERE o.snapshot->'coupon'->>'id'=%s AND {PAID_ORDER}''',
(str(row['id']),)).fetchone()['n']
if row['max_uses'] is not None and used >= row['max_uses']:
raise HTTPException(422, 'Este cupom já foi usado o máximo de vezes.')
if row['max_uses_per_customer'] is not None and customer_document:
mine = c.execute(f'''SELECT count(*) AS n FROM dtf_local.orders o
WHERE o.snapshot->'coupon'->>'id'=%s AND o.snapshot->'customer'->>'cnpj'=%s
AND {PAID_ORDER}''', (str(row['id']), str(customer_document))).fetchone()['n']
if mine >= row['max_uses_per_customer']:
raise HTTPException(422, 'Você já usou este cupom.')
return {'id': str(row['id']), 'code': row['code'],
'discount_cents': discount_cents(row['kind'], row['value'], eligible)}

View File

@@ -75,8 +75,12 @@ def order_paid(c, order, origin):
rows = [('Itens', '\n'.join(f"{PRODUCTS.get(i.get('mode'), i.get('mode'))}{sheet_label(i)} · "
f"{str(i.get('billed_metres') or i.get('metres')).replace('.', ',')} m"
for i in snapshot.get('items', []))),
('Entrega', delivery),
('Total', money(snapshot.get('total_cents') or 0) + (f' · {paid}' if paid else ''))]
('Entrega', delivery)]
coupon = snapshot.get('coupon') or {}
if coupon:
rows.append((f"Cupom {coupon.get('code', '')}",
f"− {money(coupon.get('discount_cents') or 0)}"))
rows.append(('Total', money(snapshot.get('total_cents') or 0) + (f' · {paid}' if paid else '')))
number, link = order['number'], f"{origin}/conta/pedidos?order={order['id']}"
text = '\n'.join([mail_html.greeting(customer.get('name')), '',
f'Seu pagamento foi aprovado e o pedido #{number} já está com a nossa equipe. '

View File

@@ -19,7 +19,7 @@ from decimal import Decimal
from fastapi import HTTPException
from psycopg.types.json import Jsonb
from . import catalog, payments
from . import catalog, coupons, payments
from .proof import PROOF_ABOVE_METRES
from .core.models import PRODUCTION_VERSIONS
from .core.pricing import apply_bands, bill_splits, is_manual, manual_extra_cents, price
@@ -103,10 +103,18 @@ def approve(c, row, items, reviewer):
if price_for_total != catalog.unit_cents(c, mode):
banded[mode] = price_for_total
apply_bands(priced, banded)
items_total = sum(i['total_cents'] for i in priced)
# The coupon discounts the items, after their bands, never freight or the
# treatment (front 8.3). It is checked again here: a quote that waited may
# have met an expiry or a use limit since it was created.
coupon = None
if draft.get('coupon'):
coupon = coupons.check(c, draft['coupon'], (draft.get('customer') or {}).get('cnpj'), priced)
discount = coupon['discount_cents'] if coupon else 0
metres = sum(Decimal(i['billed_metres']) for i in priced)
try:
quoted_freight = freight.quote(draft['freight']['service'], draft['freight'].get('postal_code', ''),
metres, sum(i['total_cents'] for i in priced))
metres, items_total)
except ValueError as exc:
raise HTTPException(422, str(exc))
treatment = 0
@@ -120,9 +128,11 @@ def approve(c, row, items, reviewer):
**({'proof': True} if draft.get('proof') and metres > PROOF_ABOVE_METRES else {}),
# Designer treatment is one fixed service line (front 5).
**({'treatment': {'cents': treatment, 'hours': 24}} if treatment else {}),
# The coupon used, for the order card, Números and Tiny (front 8.3).
**({'coupon': coupon} if coupon else {}),
# Browser timings are kept for Números, never for the price (0.12).
**({'timings': draft['timings']} if draft.get('timings') else {}),
'total_cents': sum(i['total_cents'] for i in priced) + quoted_freight['total_cents'] + treatment}
'total_cents': items_total - discount + quoted_freight['total_cents'] + treatment}
c.execute('UPDATE dtf_local.quotes SET approved=%s, reviewed_by=%s, approved_at=now() WHERE id=%s',
(Jsonb(approved), reviewer, row['id']))
# Approved and payable now: the files wait for the payment, not for ever.

View File

@@ -97,6 +97,9 @@ def lines(order, paid_with, issued):
for item in snapshot.get('items') or []:
metres = str(item.get('billed_metres') or item.get('metres') or '').replace('.', ',')
out += [(part, 9.5, False, 2) for part in wrap(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))}{sheet_label(item)} — {metres} m", 9.5)]
coupon = snapshot.get('coupon') or {}
if coupon:
out.append((f"Cupom {coupon.get('code', '')}: - {money(coupon.get('discount_cents') or 0)}", 9, False, 4))
out += [('Valor', 7.5, False, 10), (money(snapshot.get('total_cents') or 0), 12, True, 1),
('Pagamento', 7.5, False, 6), (METHODS.get(paid_with, 'Teste' if paid_with == 'teste' else paid_with or '—'), 10, False, 1),
(f"Emitido em {issued.astimezone(LOCAL).strftime('%d/%m/%Y %H:%M')}", 8.5, False, 10),

View File

@@ -622,3 +622,25 @@ CREATE INDEX IF NOT EXISTS product_prices_current ON dtf_local.product_prices(pr
-- product: base price, then "from 5 m R$ Y", "from 20 m R$ Z" (jsonb list of
-- {"from_metres": "5", "unit_cents": 1990}, strictly increasing, at most 5).
ALTER TABLE dtf_local.product_prices ADD COLUMN IF NOT EXISTS bands jsonb NOT NULL DEFAULT '[]';
-- Front 8.3: discount coupons, created in the Kanban's Site tab. The id is
-- generated in Python (schema.sql does not use gen_random_uuid). A deleted
-- code may be created again; the orders that used it keep its id and code.
CREATE TABLE IF NOT EXISTS dtf_local.coupons (
id uuid PRIMARY KEY,
code text NOT NULL CHECK (code ~ '^[A-Z0-9-]{3,30}$'),
kind text NOT NULL CHECK (kind IN ('percent','per_metre')),
value integer NOT NULL CHECK (value > 0), -- percent: 1..90; per_metre: cents per billed metre
valid_from timestamptz NOT NULL DEFAULT now(),
valid_until timestamptz,
min_metres numeric(8,1),
max_uses integer CHECK (max_uses > 0),
max_uses_per_customer integer CHECK (max_uses_per_customer > 0),
product text CHECK (product IN ('file','avulsa','uvfile','uv')), -- NULL = every product
note text NOT NULL DEFAULT '',
paused boolean NOT NULL DEFAULT false,
deleted_at timestamptz,
created_by text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX IF NOT EXISTS coupons_live_code ON dtf_local.coupons(code) WHERE deleted_at IS NULL;

View File

@@ -518,6 +518,10 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non
'valorFrete': money(freight['total_cents']),
'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''),
'observacoesInternas': internal_note(payload)}
coupon = order.get('coupon') or {}
if coupon:
# Tiny's v3 order has the order-level discount next to valorFrete.
pedido['valorDesconto'] = money(coupon.get('discount_cents') or 0)
carrier = shipping(service) if shipping else None
if carrier:
pedido['transportador'] = {'fretePorConta': FREIGHT_PAID_BY, **carrier}

152
tests/coupons_test.py Normal file
View File

@@ -0,0 +1,152 @@
"""Coupons: creation, the discount on one product, refused states and uses.
Run against the local stack: SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost
python -m tests.coupons_test
"""
import secrets
from datetime import datetime, timedelta, timezone
from uuid import uuid4
from psycopg.types.json import Jsonb
from app.core import db
from tests.print_file_test import artwork
from tests.smoke_test import Client, item_spec, upload_bytes
def quote(client, items, coupon, mail, expected=200):
body = {'request_key': str(uuid4()),
'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail},
'items': items, 'freight': {'service': 'pickup'}, 'coupon': coupon}
return client.call('/quotes', body, expected=expected)
def run():
tag = secrets.token_hex(4)
code = f'CUPOM-{tag.upper()}'
mail = f'coupon-{tag}@example.test'
client = Client()
client.call('/session')
manager = Client()
manager.call('/session')
manager.call('/operator/me', operator=True)
manager = manager.operator_client
coupon_id = None
quote_id = None
order_id = None
upload_id = None
try:
upload_id = upload_bytes(client, artwork(), name=f'LOCAL-COUPON-{tag}.png')
sheet = {**item_spec('uvfile', '1', 0, upload_id),
'quality_status': 'warning', 'quality_acknowledged': True}
# The sheet is the customer's own file, not one someone opens by hand.
sheet['production']['sources'][0]['measurement'] = 'file'
art = {**item_spec('uv', '1', 0, upload_id),
'quality_status': 'warning', 'quality_acknowledged': True}
items = [sheet, art]
refused = quote(client, items, f'NAO-EXISTE-{tag.upper()}', mail, expected=422)
assert refused['detail'] == 'Cupom não encontrado.', refused
coupon_id = manager.call('/operator/site/coupons', {
'code': code, 'kind': 'percent', 'value': 10, 'product': 'uv'})['id']
# The discount is on the uv item only; the items keep their prices.
made = quote(client, items, code, mail)
quote_id = made['id']
assert made['status'] == 'approved', made
approved = client.call('/quotes/' + quote_id)['approved']
assert approved['coupon']['code'] == code, approved
assert approved['coupon']['discount_cents'] == 899, approved
assert [line['total_cents'] for line in approved['items']] == [7990, 8990], approved
assert approved['total_cents'] == 16081, approved
# One paid order spends a use (a fake payment, no print job).
order_id = uuid4()
with db.connect() as c:
owner = c.execute('SELECT owner FROM dtf_local.quotes WHERE id=%s', (quote_id,)).fetchone()['owner']
c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin)
VALUES(%s,%s,%s,%s,%s,'site')''',
(order_id, quote_id, owner, Jsonb(approved),
Jsonb({'provider': 'fake', 'id': f'coupon-{tag}'})))
listed = next(row for row in manager.call('/operator/site/coupons')['coupons']
if row['id'] == coupon_id)
assert listed['uses'] == 1, listed
# Paused.
manager.call('/operator/site/coupons/' + coupon_id, {'paused': True})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Este cupom está pausado.', refused
manager.call('/operator/site/coupons/' + coupon_id, {'paused': False})
now = datetime.now(timezone.utc)
# Expired.
manager.call('/operator/site/coupons/' + coupon_id, {
'valid_from': (now - timedelta(days=2)).isoformat(),
'valid_until': (now - timedelta(days=1)).isoformat()})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Este cupom expirou.', refused
# Not started yet.
manager.call('/operator/site/coupons/' + coupon_id, {
'valid_from': (now + timedelta(days=1)).isoformat(), 'valid_until': None})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Este cupom ainda não começou.', refused
manager.call('/operator/site/coupons/' + coupon_id,
{'valid_from': now.isoformat(), 'valid_until': None})
# Minimum metres, counted on the eligible uv item only.
manager.call('/operator/site/coupons/' + coupon_id, {'min_metres': '5'})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Este cupom pede pelo menos 5 m.', refused
manager.call('/operator/site/coupons/' + coupon_id, {'min_metres': None})
# Only one product.
manager.call('/operator/site/coupons/' + coupon_id, {'product': 'file'})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Este cupom vale só para Têxtil folha pronta.', refused
manager.call('/operator/site/coupons/' + coupon_id, {'product': 'uv'})
# Max uses, then the per-customer limit on its own.
manager.call('/operator/site/coupons/' + coupon_id, {'max_uses': 1})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Este cupom já foi usado o máximo de vezes.', refused
manager.call('/operator/site/coupons/' + coupon_id,
{'max_uses': None, 'max_uses_per_customer': 1})
refused = quote(client, items, code, mail, expected=422)
assert refused['detail'] == 'Você já usou este cupom.', refused
manager.call('/operator/site/coupons/' + coupon_id,
{'max_uses_per_customer': None})
# Números lists the coupon's paid order, metres, discount and money.
stats = manager.call('/operator/stats?days=30')
row = next(entry for entry in stats['coupons'] if entry['id'] == coupon_id)
assert row['orders'] == 1 and row['metres'] == 2.0, row
assert row['discount_cents'] == 899 and row['cents'] == 16081, row
# Soft delete: the code leaves the list, the paid order keeps it and
# Números keeps counting it.
manager.call('/operator/site/coupons/' + coupon_id + '/delete', {})
assert not any(entry['id'] == coupon_id
for entry in manager.call('/operator/site/coupons')['coupons'])
with db.connect() as c:
snapshot = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s',
(order_id,)).fetchone()['snapshot']
assert snapshot['coupon']['code'] == code, snapshot
stats = manager.call('/operator/stats?days=30')
assert any(entry['id'] == coupon_id for entry in stats['coupons']), stats['coupons']
print('PASS: a coupon discounts one product, refuses paused/expired/not-started/'
'minimum/product/use states, reaches Tiny data and Números, and soft delete keeps history')
finally:
with db.connect() as c:
if order_id:
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,))
if quote_id:
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote_id,))
if coupon_id:
c.execute('DELETE FROM dtf_local.coupons WHERE id=%s', (coupon_id,))
if upload_id:
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s', (upload_id,))
if __name__ == '__main__':
run()

38
tests/test_coupons.py Normal file
View File

@@ -0,0 +1,38 @@
"""Run from repository root: python3 -m unittest tests.test_coupons -v."""
import unittest
from app.coupons import discount_cents, eligible_items
def item(mode, billed_metres, total_cents):
return {'mode': mode, 'billed_metres': billed_metres, 'total_cents': total_cents}
class CouponTests(unittest.TestCase):
def test_percent_is_floored(self):
self.assertEqual(discount_cents('percent', 10, [item('file', '1', 1990)]), 199)
self.assertEqual(discount_cents('percent', 33, [item('file', '1', 1990)]), 656)
self.assertEqual(discount_cents('percent', 10, []), 0)
def test_per_metre_is_floored_to_the_cent(self):
items = [item('file', '2.5', 5475), item('file', '1.5', 3285)]
self.assertEqual(discount_cents('per_metre', 200, items), 800)
# 333 cents x 1.1 m = 366.3 cents: the customer gets 366.
self.assertEqual(discount_cents('per_metre', 333, [item('file', '1.1', 2409)]), 366)
def test_product_filter(self):
items = [item('file', '1', 1990), item('uv', '1', 8990)]
self.assertEqual(eligible_items(items, 'uv'), [items[1]])
self.assertEqual(eligible_items(items, None), items)
def test_never_more_than_the_items_total(self):
self.assertEqual(discount_cents('per_metre', 1000, [item('file', '2', 1500)]), 1500)
self.assertEqual(discount_cents('percent', 90, [item('file', '1', 100)]), 90)
def test_invalid_kind(self):
with self.assertRaises(ValueError):
discount_cents('other', 10, [item('file', '1', 1990)])
if __name__ == '__main__':
unittest.main()

View File

@@ -16,6 +16,7 @@
let requestBody = localStorage.getItem('dtf-request-body');
let quotedCart = localStorage.getItem('dtf-quote-cart');
let refreshVersion = 0;
const cupomCode=()=>{const el=document.getElementById('fCupom');return el?el.value.trim().toUpperCase():'';};
function cartSnapshot() {
const items=itensAPagar();
return JSON.stringify({customer:cliente,delivery:entrega,items:items.map(item=>({
@@ -26,7 +27,7 @@
stroke:item.strokeClass||null,strokeChoice:item.strokeChoice||null,
sheets:(item.partes||[]).map(part=>part.production),
files:(item.localFiles||[]).map(file=>({name:file.name,size:file.size,lastModified:file.lastModified}))
})),treatment:!!$('fTratamento')?.checked});
})),treatment:!!$('fTratamento')?.checked,coupon:cupomCode()});
}
// The quote this browser is paying, forgotten. clearDraft also empties the
// payment area; forgetDraft leaves on screen what is there (a confirmation).
@@ -171,6 +172,8 @@
approved.freight.total_cents ? rs(approved.freight.total_cents/100) : 'Grátis'));
if(quote.treatment?.cents)
rows.push(linha('Tratamento da arte pelo designer · +24 h', rs(quote.treatment.cents/100)));
if(approved.coupon)
rows.push(linha('Cupom '+approved.coupon.code, '− '+rs(approved.coupon.discount_cents/100)));
rows.push(linha('Total', rs(approved.total_cents/100), 'tot'));
const prumoBox=node('div',null,'prumoResumo');
if(quote.prumo?.length){
@@ -421,7 +424,9 @@
}
const service = entrega.tipo==='retira' ? 'pickup' : entrega.servico;
if (!service) throw new Error('A entrega ainda não está disponível. Escolha a retirada em Franca.');
const content = {customer:{...cliente},items,freight:{service,postal_code:entrega.tipo==='retira'?'':entrega.cep}};
const cupom=cupomCode();
const content = {customer:{...cliente},items,freight:{service,postal_code:entrega.tipo==='retira'?'':entrega.cep},
...(cupom?{coupon:cupom}:{})};
const destination = destinoApi();
if (destination) content.destination = destination;
// "Quero aprovar uma prova antes de imprimir": the order waits for the customer.
@@ -757,5 +762,13 @@
else if (!busy) { refreshVersion++; clearInterval(pixClock); message(''); actions.replaceChildren(); pintaResumo(null); }
if (!naPagina() && semPedidos) message('No momento não estamos recebendo pedidos pelo site.','warn');
});
// "Aplicar" sends the coupon with the cart: there is no public route to test
// a code, so the server's answer comes with the quote (front 8.3).
const aplicarCupom=document.getElementById('bCupom');
if(aplicarCupom)aplicarCupom.onclick=()=>window.dtfCheckout();
const campoCupom=document.getElementById('fCupom');
if(campoCupom)campoCupom.addEventListener('keydown',e=>{
if(e.key==='Enter'){e.preventDefault();window.dtfCheckout();}
});
refresh();
})();

View File

@@ -1089,6 +1089,19 @@ h2 em{font-style:normal;color:var(--laranja)}
</div>
</div>
<div class="cxE">
<h4>Cupom</h4>
<div class="campos">
<div class="cp larga">
<label for="fCupom">Código do cupom</label>
<div class="cepL">
<input id="fCupom" autocomplete="off" maxlength="30" placeholder="Ex.: REINA-2026">
<button type="button" id="bCupom">Aplicar</button>
</div>
</div>
</div>
</div>
<div class="cxE">
<h4>Prova antes de imprimir</h4>
<label class="provaOp"><input type="checkbox" id="fProva">

View File

@@ -148,11 +148,156 @@ function sitePriceBlock(product){
return block;
}
// ── Cupons (front 8.3) ──────────────────────────────────────────────────────
// A "ficha" of the date in the browser's timezone, for datetime-local inputs.
function couponDate(iso){
const d=new Date(iso),p=n=>String(n).padStart(2,'0');
return d.getFullYear()+'-'+p(d.getMonth()+1)+'-'+p(d.getDate())+'T'+p(d.getHours())+':'+p(d.getMinutes());
}
function ensureCouponsPanel(){
let panel=$('site-coupons-panel');
if(panel)return panel;
panel=node('section',undefined,'panel clip');panel.id='site-coupons-panel';
const head=node('div',undefined,'phead');
head.append(node('h2','Cupons'),button('Novo cupom',()=>couponDialog(null),'btn right'));
panel.append(head,node('p','Cupons de desconto do checkout: validade, mínimo de metros, limite de usos e produto. Um cupom por pedido.','phint'));
const list=node('div',undefined,'siteCouponList');list.id='site-coupons';panel.append(list);
const videos=$('site-videos-panel');
if(videos)videos.before(panel); else $('tab-site').append(panel);
return panel;
}
function couponRow(coupon){
const expired=coupon.valid_until && new Date(coupon.valid_until)<=new Date();
const status=coupon.paused?['Pausado','warn']:expired?['Expirado','']:['Ativo','ok'];
const row=node('div',undefined,'siteCouponRow');
const top=node('div',undefined,'siteCouponTop');
top.append(node('b',coupon.code),badge(status[0],status[1]),
node('span',coupon.kind==='percent'?coupon.value+'%':money(coupon.value)+'/m','siteCouponOffer'));
const meta=node('div',undefined,'siteCouponMeta');
meta.append(node('span','Validade: de '+when(coupon.valid_from)+
(coupon.valid_until?' até '+when(coupon.valid_until):' sem fim')),
node('span','Produto: '+(coupon.product?SHORT[coupon.product]:'todos')),
node('span','Usos: '+coupon.uses+(coupon.max_uses?' de '+coupon.max_uses:'')));
const actions=node('div',undefined,'siteCouponActions');
actions.append(button(coupon.paused?'Retomar':'Pausar',async()=>{
await api('/site/coupons/'+coupon.id,{paused:!coupon.paused});
say('Cupom '+coupon.code+(coupon.paused?' retomado.':' pausado.'));
await loadSiteCoupons();
},'btn'),
button('Editar',()=>couponDialog(coupon),'btn ghost'),
button('Apagar',async()=>{
if(!(await ask('Apagar cupom',
'O cupom '+coupon.code+' deixa de valer. Os pedidos que já o usaram continuam no histórico.',
'Apagar',{tone:'red'})))return;
await api('/site/coupons/'+coupon.id+'/delete',{});
say('Cupom '+coupon.code+' apagado.');
await loadSiteCoupons();
},'btn quiet'));
row.append(top,meta,actions);
if(coupon.note)row.append(node('p',coupon.note,'siteCouponNote'));
return row;
}
function couponDialog(coupon){
const editing=!!coupon;
const code=node('input');code.maxLength=30;code.value=coupon?coupon.code:'';code.placeholder='Ex.: REINA-2026';
if(editing)code.disabled=true;
const kind=node('select');
for(const [value,label] of [['percent','Porcentagem (%)'],['per_metre','Por metro (R$)']]){
const option=node('option',label);option.value=value;kind.append(option);
}
kind.value=coupon?coupon.kind:'percent';
const pct=node('input');pct.type='number';pct.min='1';pct.max='90';pct.step='1';
pct.value=coupon&&coupon.kind==='percent'?String(coupon.value):'';
const price=node('input');price.type='text';price.inputMode='decimal';price.placeholder='2,00';
if(coupon&&coupon.kind==='per_metre')price.value=(coupon.value/100).toFixed(2).replace('.',',');
const from=node('input');from.type='datetime-local';from.value=coupon?couponDate(coupon.valid_from):'';
const until=node('input');until.type='datetime-local';
until.value=coupon&&coupon.valid_until?couponDate(coupon.valid_until):'';
const min=node('input');min.type='text';min.inputMode='decimal';min.placeholder='5';
if(coupon&&coupon.min_metres!=null)min.value=String(coupon.min_metres).replace('.',',');
const max=node('input');max.type='number';max.min='1';max.step='1';
max.value=coupon&&coupon.max_uses?String(coupon.max_uses):'';
const per=node('input');per.type='number';per.min='1';per.step='1';
per.value=coupon&&coupon.max_uses_per_customer?String(coupon.max_uses_per_customer):'';
const product=node('select');
for(const [value,label] of [['','Todos os produtos'],...Object.entries(SHORT)]){
const option=node('option',label);option.value=value;product.append(option);
}
product.value=coupon?coupon.product||'':'';
const note=node('textarea');note.maxLength=1000;note.value=coupon?coupon.note:'';
const pctField=field('Desconto (%)',pct,'De 1 a 90.');
const priceField=field('Desconto por metro (R$)',price,'Valor em reais por metro, como 2,00.');
const paint=()=>{pctField.hidden=kind.value!=='percent';priceField.hidden=kind.value!=='per_metre';};
kind.onchange=paint;paint();
const fields=[
field('Código',code,editing?'O código não muda depois de criado.':'De 3 a 30 letras, números ou hífens.'),
field('Tipo de desconto',kind),
pctField,priceField,
field('Válido a partir de',from,'Vazio: agora.'),
field('Válido até',until,'Vazio: sem fim.'),
field('Mínimo de metros',min,'Vazio: sem mínimo. Conta só os metros dos itens do produto.'),
field('Limite de usos',max,'Vazio: sem limite.'),
field('Limite por cliente',per,'Vazio: sem limite.'),
field('Produto',product,'Todos os produtos, ou só um.'),
field('Observação',note,'Aparece só no Kanban.'),
];
formDialog(editing?'Editar cupom':'Novo cupom',{width:640,fields,label:'Salvar cupom',onsave:async()=>{
const rawMin=min.value.trim().replace(',','.');
const payload={
kind:kind.value,
value:kind.value==='percent'?Number(pct.value):moneyInputCents(price.value),
valid_from:from.value?new Date(from.value).toISOString():null,
valid_until:until.value?new Date(until.value).toISOString():null,
min_metres:rawMin||null,
max_uses:max.value.trim()?Number(max.value):null,
max_uses_per_customer:per.value.trim()?Number(per.value):null,
product:product.value||null,
note:note.value.trim(),
};
if(kind.value==='percent'&&(!Number.isInteger(payload.value)||payload.value<1||payload.value>90))
throw new Error('A porcentagem precisa ser de 1 a 90.');
if(kind.value==='per_metre'&&(payload.value===null||payload.value<=0))
throw new Error('Informe o desconto por metro em reais, como 2,00.');
if(rawMin&&!/^\d+([.,]\d)?$/.test(rawMin))
throw new Error('O mínimo de metros usa no máximo uma casa decimal.');
if(payload.min_metres!==null&&(!Number.isFinite(Number(payload.min_metres))||Number(payload.min_metres)<=0))
throw new Error('O mínimo de metros precisa ser maior que zero.');
if(payload.max_uses!==null&&(!Number.isInteger(payload.max_uses)||payload.max_uses<=0))
throw new Error('O limite de usos precisa ser um número inteiro maior que zero.');
if(payload.max_uses_per_customer!==null&&
(!Number.isInteger(payload.max_uses_per_customer)||payload.max_uses_per_customer<=0))
throw new Error('O limite por cliente precisa ser um número inteiro maior que zero.');
if(editing){
await api('/site/coupons/'+coupon.id,payload);
}else{
const clean=code.value.trim().toUpperCase();
if(!/^[A-Z0-9-]{3,30}$/.test(clean))
throw new Error('O código precisa ter de 3 a 30 letras, números ou hífens.');
await api('/site/coupons',{code:clean,...payload});
}
say(editing?'Cupom salvo.':'Cupom criado.');
await loadSiteCoupons();
}});
}
async function loadSiteCoupons(){
if(!may('manage'))return;
ensureCouponsPanel();
const data=await api('/site/coupons');
const host=$('site-coupons');
host.replaceChildren(...(data.coupons.length?data.coupons.map(couponRow)
:[node('p','Nenhum cupom criado ainda.','empty')]));
}
async function loadSiteAdmin(){
if(!may('manage'))return;
const data=await api('/site/products');
$('site-products').replaceChildren(...data.products.map(siteProductRow));
$('site-prices').replaceChildren(...data.products.map(sitePriceBlock));
await loadSiteCoupons();
await loadSiteVideos();
}

View File

@@ -663,6 +663,15 @@ label.fopt{cursor:pointer;user-select:none}
#tab-site .siteScheduledRow .btn{height:30px;padding:0 10px;font-size:12.5px}
#tab-site .siteHistory{display:flex;flex-direction:column;gap:6px}
#tab-site .siteHistory h4{margin:0;font-size:12.5px;font-weight:600;color:var(--tx3)}
#tab-site .siteCouponList{display:flex;flex-direction:column;padding:0 18px 18px}
#tab-site .siteCouponRow{display:flex;flex-direction:column;gap:8px;padding:16px 0;border-top:1px solid var(--ln)}
#tab-site .siteCouponTop{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
#tab-site .siteCouponTop b{font-size:14px}
#tab-site .siteCouponOffer{font-size:13.5px;font-weight:650;color:var(--tx2)}
#tab-site .siteCouponMeta{display:flex;gap:16px;flex-wrap:wrap;font-size:12.5px;color:var(--tx3)}
#tab-site .siteCouponActions{display:flex;gap:8px;flex-wrap:wrap}
#tab-site .siteCouponActions .btn{height:32px;padding:0 10px;font-size:12.5px}
#tab-site .siteCouponNote{margin:0;font-size:13px;color:var(--tx2)}
#tab-site .siteHistory .table{font-size:13px}
#tab-site .siteHistory .table th,#tab-site .siteHistory .table td{padding:8px 12px}
.page>*{flex-shrink:0}

View File

@@ -1426,6 +1426,8 @@ function renderPanel(order){
code.append(node('span','DTF-'+order.number,'code'),copyButton(fileCode(order),'Copiar “'+fileCode(order)+'”, o começo do nome dos arquivos deste pedido'));
const theirs=node('span','Código do cliente ','tip-l');theirs.append(node('span',orderCode(order.id),'code strong'));theirs.dataset.tip='O código que aparece para o cliente';
sub.append(paid,node('span','Entrou pelo '+(ORIGINS[order.origin]||order.origin)),code,theirs);
if(s.coupon && !order.proof_parent)
sub.append(badge('Cupom '+s.coupon.code,'','Desconto de '+money(s.coupon.discount_cents)));
if(isTest(order))sub.append(badge('Teste','','Pedido de teste: sem pagamento, não vai ao Tiny'));
if(stalled(order)&&!order.cancelled_at)sub.append(badge('Parado há '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at)));
const steps=node('ol',undefined,'stepper');steps.setAttribute('aria-label','Etapas');
@@ -3274,6 +3276,30 @@ async function loadStats(){
node('td',String(s.samples),'r'));
if(!s.samples)tr.classList.add('off');
return tr;}));
// Coupons of the period (front 8.3): the page's sections live in the HTML,
// so this panel is built here once and kept beside "Pedidos sem pagamento".
let couponPanel=$('stats-coupons-panel');
if(!couponPanel){
couponPanel=node('section',undefined,'panel clip');couponPanel.id='stats-coupons-panel';
const head=node('div',undefined,'phead');head.append(node('h2','Cupons'));
const table=node('table',undefined,'table');
const thead=node('thead'),headRow=node('tr');
for(const [label,cls] of [['Cupom',''],['Pedidos','r'],['Metros','r'],['Desconto','r'],['Recebido','r']])
headRow.append(node('th',label,cls));
thead.append(headRow);
const tbody=node('tbody');tbody.id='stats-coupons';
table.append(thead,tbody);
couponPanel.append(head,node('p','Cupons usados pelos pedidos pagos do período.','phint'),table);
const anchor=$('stats-unpaid')?.closest('section');
if(anchor)anchor.after(couponPanel);else $('tab-stats').append(couponPanel);
}
const couponRows=data.coupons||[];
$('stats-coupons').replaceChildren(...(couponRows.length?couponRows.map(coupon=>{
const tr=node('tr');
tr.append(node('td',coupon.code),node('td',String(coupon.orders),'r'),
node('td',metres(coupon.metres).replace(' m',''),'r'),
node('td',money(coupon.discount_cents),'r'),node('td',money(coupon.cents),'r'));
return tr;}):[emptyRow('Nenhum cupom usado no período.',5)]));
}
const emptyRow=(text,span)=>{const tr=node('tr');const td=node('td',text,'empty');td.colSpan=span;tr.append(td);return tr;};
// Metres per day: one series of columns from one baseline, the period's