"""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)}