Merge Ajuste Fino: priced per art, offered under the Prumo warnings
All checks were successful
Build and deploy / Validate source (push) Successful in 12s
Build and deploy / Integration suite on a real stack (push) Successful in 6m58s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m38s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-11 14:46:42 -03:00
26 changed files with 423 additions and 107 deletions

View File

@@ -49,17 +49,17 @@ def run():
refused = client.call('/quotes', quote_body(item, False, mail), expected=422)
assert refused['detail'] == ('Sua arte tem nota 50: para imprimir com qualidade, '
'o tratamento pelo designer é obrigatório neste pedido.'), refused
'o Ajuste Fino é obrigatório neste pedido.'), refused
made = client.call('/quotes', quote_body(item, True, mail))
quote_id = made['id']
assert made['status'] == 'approved', made
approved = client.call('/quotes/' + quote_id)['approved']
assert approved['grade_flags'] == {'aviso': 50, 'tratamento': 50}, approved
assert approved['treatment']['cents'] == 1000, approved
assert approved['treatment'] == {'cents': 1000, 'hours': 24, 'arts': 1,
'unit_cents': 1000}, approved
assert approved['total_cents'] == 9990, approved
print('PASS: the grade rule requires the designer treatment and flags the order'
' with the worst grade')
print('PASS: the grade rule requires Ajuste Fino and flags the order with the worst grade')
finally:
if rules_set:
try:

View File

@@ -4,12 +4,15 @@ Run against the local stack: SITE_BASE_URL=http://site SITE_HOST_HEADER=localhos
python -m tests.site_admin_test
"""
import io
import os
import secrets
from datetime import datetime, timedelta, timezone
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.core import db
from tests.print_file_test import artwork
from tests.smoke_test import Client, item_spec, upload_bytes
@@ -34,6 +37,20 @@ def quote(client, item, mail, expected=200):
'items': [item], 'freight': {'service': 'pickup'}}, expected=expected)
def arts_item(upload_id, arts):
"""One loose-art item with `arts` sources of 10 x 10 cm, one metre long."""
sources = [{'upload_id': upload_id, 'kind': 'artwork', 'width_cm': 10, 'length_cm': 10,
'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': 10, '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'
@@ -44,12 +61,12 @@ def run():
manager.call('/session')
manager.call('/operator/me', operator=True)
manager = manager.operator_client
prices, user = [], None
prices, user, treatment_enabled = [], None, None
try:
products = manager.call('/operator/site/products')['products']
assert {product['id'] for product in products} == \
{'file', 'avulsa', 'uvfile', 'uv', 'premium', 'tratamento'}
assert all(product['unit'] in ('metro', 'pedido') and product['title'] for product in products)
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)
@@ -71,6 +88,46 @@ def run():
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']
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}
@@ -143,8 +200,6 @@ def run():
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'
@@ -158,14 +213,19 @@ def run():
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, schedules and cancels prices, charges the new price,'
' and refuses a non-manage profile')
' and accepts it once enabled, prices Ajuste Fino per art with its band,'
' 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 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)

View File

@@ -9,7 +9,7 @@ import unittest
from decimal import Decimal
from app import catalog
from app.cart_pricing import price_items
from app.cart_pricing import price_items, treatment_price
from app.core import pricing
@@ -156,6 +156,21 @@ class CartPricingCharacterizationTest(unittest.TestCase):
floating = priced('band-floating-metres')[0]
self.assertEqual((floating['billed_metres'], floating['total_cents']), ('2.9', 24650))
def test_ajuste_fino_is_per_art_with_the_band(self):
# Front 1a: 1 to 9 arts at R$ 9,90, from 10 at R$ 6,90, all arts charged
# at the band. `true` keeps meaning every art of the cart.
offer = {'enabled': True, 'unit_cents': 990,
'bands': [{'from_metres': '10', 'unit_cents': 690}]}
for arts, unit in ((1, 990), (9, 990), (10, 690), (12, 690)):
items = [item('avulsa', '1', uid=f'u{index}') for index in range(arts)]
self.assertEqual(treatment_price(items, True, offer),
{'cents': unit * arts, 'hours': 24, 'arts': arts, 'unit_cents': unit})
items = [item('file', '1', uid='u1'), item('file', '1', uid='u2')]
self.assertEqual(treatment_price(items, [[1, 0]], offer),
{'cents': 990, 'hours': 24, 'arts': 1, 'unit_cents': 990})
self.assertEqual(treatment_price(items, [], offer), {})
self.assertEqual(treatment_price(items, True, {**offer, 'enabled': False}), {})
if __name__ == '__main__':
unittest.main()

View File

@@ -34,7 +34,7 @@ class GradeRulesTest(unittest.TestCase):
def test_treatment_message(self):
self.assertEqual(
treatment_message(45),
'Sua arte tem nota 45: para imprimir com qualidade, o tratamento pelo designer '
'Sua arte tem nota 45: para imprimir com qualidade, o Ajuste Fino '
'é obrigatório neste pedido.')

View File

@@ -133,6 +133,22 @@ class PricingTests(unittest.TestCase):
with self.subTest(metres=metres):
self.assertEqual(cents, band_price(PRICES['file'], bands, Decimal(metres)))
def test_ajuste_fino_band_against_actual_site_javascript(self):
# Ajuste Fino counts its band in arts: the Site helper must charge the
# same unit price as catalog.band_price.
source = Path('web/site-config.js').read_text()
body = source.split('function precoAjuste', 1)[1].split('\n}', 1)[0]
bands = [{'from_metres': 10, 'unit_cents': 690}]
js = ('const TAXA_TRATAMENTO=9.9;const FAIXAS=' + json.dumps({'tratamento': bands}) + ';'
'function precoAjuste' + body + '\n}'
';const results=[];for(const n of [1,9,10,12])'
'results.push([n,Math.round(precoAjuste(n)*100)]);'
'process.stdout.write(JSON.stringify(results));')
cases = json.loads(subprocess.check_output(['node', '-e', js], text=True))
for arts, cents in cases:
with self.subTest(arts=arts):
self.assertEqual(cents, band_price(990, bands, Decimal(arts)))
def test_which_items_are_opened_by_hand(self):
def item(kind, measurement, uid='u1'):
return {'production': {'sources': [{'kind': kind, 'measurement': measurement, 'upload_id': uid}]}}

View File

@@ -160,8 +160,17 @@ class TinyTests(FakeTinyCase):
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
pedido = order_payload(treatment, 777, date(2026, 9, 24))
self.assertIn({'produto': {'id': 105}, 'quantidade': 1, 'valorUnitario': 9.9,
'infoAdicional': 'Tratamento da arte pelo designer · +24 h'}, pedido['itens'])
'infoAdicional': 'Ajuste Fino · 1 arte · +24 h'}, pedido['itens'])
self.assertNotEqual(pedido['dataPrevista'], order_payload(plain, 777, date(2026, 9, 24))['dataPrevista'])
# Per art: the quantity is the number of arts and the unit is the band price.
per_art = {'order': {**base, 'treatment': {'cents': 2070, 'hours': 24, 'arts': 3,
'unit_cents': 690},
'total_cents': base['total_cents'] + 2070},
**{k: v for k, v in PAID.items() if k != 'order'}}
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
pedido = order_payload(per_art, 777, date(2026, 9, 24))
self.assertIn({'produto': {'id': 105}, 'quantidade': 3, 'valorUnitario': 6.9,
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}, pedido['itens'])
def test_second_delivery_finds_the_first_order(self):
first = self.tiny.deliver('k1', PAID)

View File

@@ -24,14 +24,14 @@ def run():
'note': 'Gerado pelo Prumo'}, operator=True)
blocked = client.call('/operator/orders/' + order['id'] + '/move',
{'state': 'tra', 'version': approved['version']}, operator=True, expected=409)
assert 'Tratamento pago' in blocked['detail'], blocked
assert 'Ajuste Fino pago' in blocked['detail'], blocked
prepared = upload_bytes(client, artwork(), name='LOCAL-TREATMENT-FINAL.png', order_id=order['id'])
approved = client.call('/operator/orders/' + order['id'] + '/final-files',
{'version': approved['version'], 'files': [{'item_index': 0, 'upload_id': prepared}],
'note': 'PNG tratado pelo designer'}, operator=True)
client.call('/operator/orders/' + order['id'] + '/move',
{'state': 'tra', 'version': approved['version']}, operator=True)
print('PASS: generated artwork cannot satisfy paid treatment; designer PNG opens the print queue')
print('PASS: generated artwork cannot satisfy paid Ajuste Fino; designer PNG opens the print queue')
if __name__ == '__main__':