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}