Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Secret scan and release gate (push) Has been cancelled
Build and deploy / Integration suite on a real stack (push) Has been cancelled
The price came from the layout the browser sent, checked only in part: - Pieces on top of each other passed: 100 copies stacked in one place bill 10 cm and print over each other. The layout validator now refuses any overlap. - A file laid out at proportions it does not have (a 5 m sheet sent as 10 cm) was found only by the print file, after payment. The quote now checks each raster file's proportions from the bytes it already reads. - The empty strips the Site cuts from a ready sheet were cut on its word. The print file now reads them: a strip with ink sends the item to hand preparation with the reason, instead of printing the art cut off. Test fixtures that laid real images out at impossible proportions now keep the image's own. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
301 lines
18 KiB
Python
301 lines
18 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 io
|
|
import os
|
|
import secrets
|
|
from datetime import date, datetime, timedelta, timezone
|
|
from unittest import mock
|
|
from uuid import uuid4
|
|
|
|
from PIL import Image, ImageDraw
|
|
|
|
from app import tiny
|
|
from app.adapters import FakeTiny
|
|
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'
|
|
PREMIUM = 'premium'
|
|
REDESIGN = 'redesenho'
|
|
|
|
|
|
def premium_sheet():
|
|
"""A 57 cm wide sheet above 96 DPI at that width, so the server accepts it."""
|
|
image = Image.new('RGBA', (2400, 800), (0, 0, 0, 0))
|
|
ImageDraw.Draw(image).rectangle([40, 40, 2360, 760], fill=(220, 30, 60, 255))
|
|
out = io.BytesIO()
|
|
image.save(out, 'PNG', dpi=(300, 300))
|
|
return out.getvalue()
|
|
|
|
|
|
def quote(client, item, mail, expected=200):
|
|
return client.call('/quotes', {'request_key': str(uuid4()),
|
|
'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail},
|
|
'items': [item], 'freight': {'service': 'pickup'}}, expected=expected)
|
|
|
|
|
|
def arts_item(upload_id, arts):
|
|
"""One loose-art item with `arts` sources of 10 x 5 cm (artwork() is 2:1),
|
|
one every 10 cm."""
|
|
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 5,
|
|
'copies': 1, 'rotation_degrees': 0, 'mirrored': False,
|
|
'measurement': 'customer'} for _ in range(arts)]
|
|
placements = [{'source_index': index, 'copy_index': 0, 'x_cm': 0, 'y_cm': index * 10,
|
|
'width_cm': 10, 'length_cm': 5, 'rotation_degrees': 0, 'mirrored': False}
|
|
for index in range(arts)]
|
|
return {'mode': 'avulsa', 'metres': '1', 'grade': 90, 'uploads': [upload_id] * arts,
|
|
'production': {'version': 3, 'film_width_cm': 57, 'height_cm': arts * 10,
|
|
'sources': sources, 'placements': placements},
|
|
'quality_status': 'ok', 'quality_acknowledged': False}
|
|
|
|
|
|
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, treatment_enabled, redesign_enabled = [], None, None, None
|
|
try:
|
|
products = manager.call('/operator/site/products')['products']
|
|
assert {product['id'] for product in products} == \
|
|
{'file', 'avulsa', 'uvfile', 'uv', 'premium', 'tratamento', REDESIGN}
|
|
assert all(product['unit'] in ('metro', 'pedido', 'arte') and product['title'] for product in products)
|
|
|
|
# Front 3: Premium is listed and starts switched off (Marcus, 2026-11-10).
|
|
premium_entry = next(product for product in products if product['id'] == PREMIUM)
|
|
assert premium_entry['enabled'] is False, premium_entry
|
|
assert premium_entry['title'] == 'Têxtil Premium · 8 passadas', premium_entry
|
|
assert client.call('/session')['products'][PREMIUM]['enabled'] is False
|
|
premium_item = {**item_spec(PREMIUM, '1', 0, upload_bytes(
|
|
client, premium_sheet(), name='LOCAL-SITE-PREMIUM.png'), aspect=3),
|
|
'quality_status': 'warning', 'quality_acknowledged': True}
|
|
refused = quote(client, premium_item, mail, expected=422)
|
|
assert refused['detail'] == 'Este produto não está à venda agora.', refused
|
|
manager.call(f'/operator/site/products/{PREMIUM}', {'enabled': True})
|
|
assert client.call('/session')['products'][PREMIUM]['enabled'] is True
|
|
created = quote(client, premium_item, mail)
|
|
assert created['status'] == 'approved', created
|
|
approved = client.call('/quotes/' + created['id'])['approved']
|
|
assert approved['items'][0]['mode'] == PREMIUM, approved
|
|
assert approved['items'][0]['unit_cents'] == 3990, approved
|
|
assert approved['total_cents'] == 3990, approved
|
|
manager.call(f'/operator/site/products/{PREMIUM}', {'enabled': False})
|
|
|
|
# Front 1a: Ajuste Fino per art, with the batch band set in the Site tab.
|
|
treatment = next(product for product in products if product['id'] == 'tratamento')
|
|
treatment_enabled = treatment['enabled']
|
|
manager.call('/operator/site/products/tratamento', {'enabled': True})
|
|
made = manager.call('/operator/site/products/tratamento/prices', {
|
|
'unit_cents': 990, 'bands': [{'from_metres': '10', 'unit_cents': 690}]})
|
|
prices.append(made['id'])
|
|
session = client.call('/session')
|
|
assert session['treatment_cents'] == 990, session
|
|
assert session['treatment_bands'] == [{'from_metres': 10.0, 'unit_cents': 690}], session
|
|
arts = arts_item(upload_bytes(client, artwork(), name='LOCAL-AJUSTE-FINO.png'), 10)
|
|
customer = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail}
|
|
three = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
|
'items': [arts], 'treatment': [[0, 0], [0, 1], [0, 2]],
|
|
'freight': {'service': 'pickup'}})
|
|
assert three['status'] == 'approved', three
|
|
ajuste = client.call('/quotes/' + three['id'])['approved']
|
|
assert ajuste['treatment'] == {'cents': 2970, 'hours': 24, 'arts': 3,
|
|
'unit_cents': 990}, ajuste
|
|
assert ajuste['total_cents'] == ajuste['items'][0]['total_cents'] + 2970, ajuste
|
|
ten = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
|
'items': [arts], 'treatment': [[0, index] for index in range(10)],
|
|
'freight': {'service': 'pickup'}})
|
|
ten = client.call('/quotes/' + ten['id'])['approved']
|
|
assert ten['treatment'] == {'cents': 6900, 'hours': 24, 'arts': 10,
|
|
'unit_cents': 690}, ten
|
|
old = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
|
'items': [arts], 'treatment': True, 'freight': {'service': 'pickup'}})
|
|
old = client.call('/quotes/' + old['id'])['approved']
|
|
assert old['treatment'] == {'cents': 6900, 'hours': 24, 'arts': 10,
|
|
'unit_cents': 690}, old
|
|
# Tiny: the quantity is the number of arts and the unit is the band price.
|
|
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
|
|
pedido = tiny.order_payload({'order_id': three['id'], 'order': ajuste,
|
|
'number': 1, 'payment': {}, 'origin': 'site'}, 777,
|
|
date(2026, 11, 11), product_id=lambda code: 999)
|
|
assert [line for line in pedido['itens'] if line['produto']['id'] == 105] == [
|
|
{'produto': {'id': 105}, 'quantidade': 3, 'valorUnitario': 9.9,
|
|
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}], pedido['itens']
|
|
|
|
# Front 1b: Ajuste Fino Redesenho, one price per art, never a band.
|
|
redesign = next(product for product in products if product['id'] == REDESIGN)
|
|
redesign_enabled = redesign['enabled']
|
|
assert redesign['enabled'] is False, redesign
|
|
assert redesign['title'] == 'Ajuste Fino Redesenho', redesign
|
|
assert redesign['unit'] == 'arte', redesign
|
|
manager.call(f'/operator/site/products/{REDESIGN}', {'enabled': True})
|
|
# Enabled but still unpriced: the Site hides it and the server refuses it.
|
|
refused = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
|
'items': [arts], 'redesign': [[0, 0]], 'freight': {'service': 'pickup'}}, expected=422)
|
|
assert refused['detail'] == 'O Redesenho não está disponível agora.', refused
|
|
banded = manager.call(f'/operator/site/products/{REDESIGN}/prices', {
|
|
'unit_cents': 2990,
|
|
'bands': [{'from_metres': '10', 'unit_cents': 690}]}, expected=422)
|
|
assert 'faixas' in banded['detail'], banded
|
|
made = manager.call(f'/operator/site/products/{REDESIGN}/prices', {'unit_cents': 2990})
|
|
prices.append(made['id'])
|
|
assert client.call('/session')['redesign_cents'] == 2990
|
|
two = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
|
'items': [arts], 'redesign': [[0, 0], [0, 1]], 'freight': {'service': 'pickup'}})
|
|
assert two['status'] == 'approved', two
|
|
redesenho = client.call('/quotes/' + two['id'])['approved']
|
|
assert redesenho['redesign'] == {'cents': 5980, 'hours': 48, 'arts': 2,
|
|
'unit_cents': 2990}, redesenho
|
|
assert redesenho['total_cents'] == redesenho['items'][0]['total_cents'] + 5980, redesenho
|
|
# Basic and Redesenho on different arts: each priced on its own service,
|
|
# and the basic band counts only the basic arts.
|
|
mixed = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
|
'items': [arts], 'treatment': [[0, 0], [0, 1], [0, 2]],
|
|
'redesign': [[0, 3], [0, 4]], 'freight': {'service': 'pickup'}})
|
|
mixed = client.call('/quotes/' + mixed['id'])['approved']
|
|
assert mixed['treatment'] == {'cents': 2970, 'hours': 24, 'arts': 3,
|
|
'unit_cents': 990}, mixed
|
|
assert mixed['redesign'] == {'cents': 5980, 'hours': 48, 'arts': 2,
|
|
'unit_cents': 2990}, mixed
|
|
assert mixed['total_cents'] == mixed['items'][0]['total_cents'] + 2970 + 5980, mixed
|
|
# Tiny: the line resolves DTFIMP.AJF.RED through the fake catalogue.
|
|
fake = FakeTiny()
|
|
pedido = tiny.order_payload({'order_id': two['id'], 'order': redesenho,
|
|
'number': 2, 'payment': {}, 'origin': 'site'}, 777,
|
|
date(2026, 11, 12), product_id=fake.product_id)
|
|
red_code = fake.product_id('DTFIMP.AJF.RED')
|
|
assert [line for line in pedido['itens'] if line['produto']['id'] == red_code] == [
|
|
{'produto': {'id': red_code}, 'quantidade': 2, 'valorUnitario': 29.9,
|
|
'infoAdicional': 'Ajuste Fino Redesenho · 2 artes · +48 h'}], pedido['itens']
|
|
# One service per art: a pair in both lists is refused by the model.
|
|
both = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
|
'items': [arts], 'treatment': [[0, 0]], 'redesign': [[0, 0]],
|
|
'freight': {'service': 'pickup'}}, expected=422)
|
|
assert 'Escolha Ajuste Fino ou Redesenho' in str(both['detail']), both
|
|
# Switched off again, a chosen Redesenho is refused.
|
|
manager.call(f'/operator/site/products/{REDESIGN}', {'enabled': False})
|
|
refused = client.call('/quotes', {'request_key': str(uuid4()), 'customer': customer,
|
|
'items': [arts], 'redesign': [[0, 0]], 'freight': {'service': 'pickup'}}, expected=422)
|
|
assert refused['detail'] == 'O Redesenho não está disponível agora.', refused
|
|
|
|
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, aspect=2), '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)
|
|
|
|
# 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, lists Premium switched off'
|
|
' and accepts it once enabled, prices Ajuste Fino per art with its band,'
|
|
' prices Redesenho per art without bands and sends it to Tiny,'
|
|
' 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,))
|
|
c.execute("UPDATE dtf_local.products SET enabled=false WHERE id=%s", (PREMIUM,))
|
|
if redesign_enabled is not None:
|
|
c.execute("UPDATE dtf_local.products SET enabled=%s WHERE id=%s",
|
|
(redesign_enabled, REDESIGN))
|
|
if treatment_enabled is not None:
|
|
try:
|
|
manager.call('/operator/site/products/tratamento', {'enabled': treatment_enabled})
|
|
except Exception:
|
|
pass
|
|
if user:
|
|
try:
|
|
manager.call('/operator/users/' + str(user['id']) + '/delete', {}, expected=200)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
if __name__ == '__main__':
|
|
run()
|