From 1d0353fe54fa3e1468cf9bbf603e2e8273164472 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Mon, 9 Nov 2026 15:24:44 -0300 Subject: [PATCH 1/2] feat: discount coupons (front 8.3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- .gitea/workflows/deploy.yml | 3 +- app/api/operator.py | 15 +++- app/api/quotes.py | 19 +++-- app/api/site_admin.py | 112 +++++++++++++++++++++++++- app/core/models.py | 30 +++++++ app/coupons.py | 81 +++++++++++++++++++ app/mail.py | 8 +- app/quote_review.py | 16 +++- app/receipt.py | 3 + app/schema.sql | 22 ++++++ app/tiny.py | 4 + tests/coupons_test.py | 152 ++++++++++++++++++++++++++++++++++++ tests/test_coupons.py | 38 +++++++++ web/checkout.js | 17 +++- web/index.html | 13 +++ web/kanban-site.js | 145 ++++++++++++++++++++++++++++++++++ web/kanban.css | 9 +++ web/kanban.js | 26 ++++++ 18 files changed, 698 insertions(+), 15 deletions(-) create mode 100644 app/coupons.py create mode 100644 tests/coupons_test.py create mode 100644 tests/test_coupons.py diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 6aa2840..c758d56 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -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 \ diff --git a/app/api/operator.py b/app/api/operator.py index c0206b1..156d2b4 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -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): diff --git a/app/api/quotes.py b/app/api/quotes.py index a834f4f..01b3217 100644 --- a/app/api/quotes.py +++ b/app/api/quotes.py @@ -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: diff --git a/app/api/site_admin.py b/app/api/site_admin.py index 6a29640..be5c67d 100644 --- a/app/api/site_admin.py +++ b/app/api/site_admin.py @@ -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} diff --git a/app/core/models.py b/app/core/models.py index 5b05ffc..420d0d7 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -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. diff --git a/app/coupons.py b/app/coupons.py new file mode 100644 index 0000000..c60288c --- /dev/null +++ b/app/coupons.py @@ -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)} diff --git a/app/mail.py b/app/mail.py index aaa7bbf..99b192f 100644 --- a/app/mail.py +++ b/app/mail.py @@ -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. ' diff --git a/app/quote_review.py b/app/quote_review.py index a962135..17f0319 100644 --- a/app/quote_review.py +++ b/app/quote_review.py @@ -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. diff --git a/app/receipt.py b/app/receipt.py index 713ceed..f146d3c 100644 --- a/app/receipt.py +++ b/app/receipt.py @@ -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), diff --git a/app/schema.sql b/app/schema.sql index 11766b5..b61378a 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -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; diff --git a/app/tiny.py b/app/tiny.py index 16ebcca..a4a078c 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -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} diff --git a/tests/coupons_test.py b/tests/coupons_test.py new file mode 100644 index 0000000..4423d5f --- /dev/null +++ b/tests/coupons_test.py @@ -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() diff --git a/tests/test_coupons.py b/tests/test_coupons.py new file mode 100644 index 0000000..9e43d1e --- /dev/null +++ b/tests/test_coupons.py @@ -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() diff --git a/web/checkout.js b/web/checkout.js index 8c861ba..0ea5b52 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -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(); })(); diff --git a/web/index.html b/web/index.html index 93c9f0d..308f662 100644 --- a/web/index.html +++ b/web/index.html @@ -1089,6 +1089,19 @@ h2 em{font-style:normal;color:var(--laranja)} +
+

Cupom

+
+
+ +
+ + +
+
+
+
+

Prova antes de imprimir