Merge main into front-7a

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

# Conflicts:
#	.gitea/workflows/deploy.yml
This commit is contained in:
Cauê Faleiros
2026-11-09 15:40:55 -03:00
20 changed files with 701 additions and 18 deletions

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()