Merge front 8.3: discount coupons
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 6m28s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m3s

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

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}