Files
dtf-system/tests/site_admin_test.py
Cauê Faleiros 2a6732eb37 feat: progressive price bands per product (front 8.2)
A price may carry up to five bands, "from N m, R$ Y": the order's total
billed metres of that product chooses one price for its whole quantity,
the manual-file extra still on top. Bands start and become history with
their price row. The Site charges the same band for the cart, shows
"Faltam X m para R$ Y o metro" and lists the bands under the price
table; the Kanban's Site tab edits them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 14:30:15 -03:00

142 lines
7.6 KiB
Python

"""The Kanban's Site tab: products switched on and off, prices with a history.
Run against the local stack: SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost
python -m tests.site_admin_test
"""
import secrets
from datetime import datetime, timedelta, timezone
from uuid import uuid4
from app.core import db
from tests.print_file_test import artwork
from tests.smoke_test import Client, item_spec, upload_bytes
PASSWORD = 'senha-de-teste-123'
UV = 'uv'
def quote(client, item, mail):
return client.call('/quotes', {'request_key': str(uuid4()),
'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail},
'items': [item], 'freight': {'service': 'pickup'}})
def run():
tag = secrets.token_hex(4)
mail = f'site-admin-{tag}@example.test'
client = Client()
client.call('/session')
# The default operator login is the superadmin, which may manage the Site.
manager = Client()
manager.call('/session')
manager.call('/operator/me', operator=True)
manager = manager.operator_client
prices, user = [], None
try:
products = manager.call('/operator/site/products')['products']
assert {product['id'] for product in products} == {'file', 'avulsa', 'uvfile', 'uv', 'tratamento'}
assert all(product['unit'] in ('metro', 'pedido') and product['title'] for product in products)
manager.call(f'/operator/site/products/{UV}', {'enabled': True})
uid = upload_bytes(client, artwork(), name='LOCAL-SITE-ADMIN.png')
item = {**item_spec('uv', '1', 0, uid), 'quality_status': 'warning', 'quality_acknowledged': True}
before = client.call('/session')['products'][UV]['unit_cents']
# Switched off: the Site sees it off and the server refuses a new quote.
manager.call(f'/operator/site/products/{UV}', {'enabled': False})
assert client.call('/session')['products'][UV]['enabled'] is False
refused = client.call('/quotes', {'request_key': str(uuid4()),
'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail},
'items': [item], 'freight': {'service': 'pickup'}}, expected=422)
assert refused['detail'] == 'Este produto não está à venda agora.', refused
manager.call(f'/operator/site/products/{UV}', {'enabled': True})
assert client.call('/session')['products'][UV]['enabled'] is True
# A price in the future does not change today's and can be cancelled.
made = manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 23456,
'starts_at': (datetime.now(timezone.utc) + timedelta(minutes=1)).isoformat()})
prices.append(made['id'])
assert client.call('/session')['products'][UV]['unit_cents'] == before
entry = next(product for product in manager.call('/operator/site/products')['products']
if product['id'] == UV)
assert any(row['id'] == made['id'] for row in entry['scheduled']), entry
manager.call(f'/operator/site/prices/{made["id"]}/cancel', {})
entry = next(product for product in manager.call('/operator/site/products')['products']
if product['id'] == UV)
assert not any(row['id'] == made['id'] for row in entry['scheduled']), entry
# A start date in the past is refused.
manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 1000,
'starts_at': (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()}, expected=422)
# A price that starts now is what /api/session and a new quote charge.
made = manager.call(f'/operator/site/products/{UV}/prices', {'unit_cents': 12345})
prices.append(made['id'])
assert client.call('/session')['products'][UV]['unit_cents'] == 12345
created = quote(client, item, mail)
assert created['status'] == 'approved', created
approved = client.call('/quotes/' + created['id'])['approved']
assert approved['items'][0]['unit_cents'] == 12345, approved
assert approved['items'][0]['total_cents'] == 12345, approved
# Bands (front 8.2): from 2 m the metre costs less; two items of uv
# (2 m together) pay the band price on both.
made = manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 12345, 'bands': [{'from_metres': '2', 'unit_cents': 10000}]})
prices.append(made['id'])
bands = client.call('/session')['products'][UV]['bands']
assert bands == [{'from_metres': 2.0, 'unit_cents': 10000}], bands
entry = next(product for product in manager.call('/operator/site/products')['products']
if product['id'] == UV)
assert entry['bands'] == [{'from_metres': '2', 'unit_cents': 10000}], entry
banded = client.call('/quotes', {'request_key': str(uuid4()),
'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail},
'items': [item, item], 'freight': {'service': 'pickup'}})
assert banded['status'] == 'approved', banded
approved = client.call('/quotes/' + banded['id'])['approved']
assert [line['unit_cents'] for line in approved['items']] == [10000, 10000], approved
assert [line['total_cents'] for line in approved['items']] == [10000, 10000], approved
assert approved['total_cents'] == 20000, approved
# Invalid bands are refused with 422 and do not become prices.
manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 12345, 'bands': [{'from_metres': '5', 'unit_cents': 1900},
{'from_metres': '5', 'unit_cents': 1800}]}, expected=422)
manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 12345, 'bands': [{'from_metres': '0', 'unit_cents': 1900}]}, expected=422)
manager.call(f'/operator/site/products/{UV}/prices', {
'unit_cents': 12345, 'bands': [{'from_metres': str(i), 'unit_cents': 1900}
for i in range(1, 7)]}, expected=422)
manager.call('/operator/site/products/tratamento/prices', {
'unit_cents': 1000, 'bands': [{'from_metres': '5', 'unit_cents': 900}]}, expected=422)
# A profile without "manage" cannot see or change the Site tab.
email = f'site-staff-{tag}@example.test'
user = manager.call('/operator/users', {'name': 'Teste Site', 'email': email,
'role': 'operador', 'password': PASSWORD})
staff = Client()
staff.call('/session')
staff.call('/operator/login', {'email': email, 'password': PASSWORD})
staff.call('/operator/site/products', expected=403)
staff.call(f'/operator/site/products/{UV}', {'enabled': True}, expected=403)
staff.call(f'/operator/site/products/{UV}/prices', {'unit_cents': 1000}, expected=403)
staff.call(f'/operator/site/prices/{made["id"]}/cancel', {}, expected=403)
print('PASS: the Site tab switches a product off and refuses quotes, schedules and cancels prices,'
' charges the new price, and refuses a non-manage profile')
finally:
with db.connect() as c:
if prices:
c.execute('DELETE FROM dtf_local.product_prices WHERE id=ANY(%s::bigint[])', (prices,))
c.execute("UPDATE dtf_local.products SET enabled=true WHERE id=%s", (UV,))
if user:
try:
manager.call('/operator/users/' + str(user['id']) + '/delete', {}, expected=200)
except Exception:
pass
if __name__ == '__main__':
run()