Merge main into fix-pdf-check
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -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:
|
||||
|
||||
99
tests/label_test.py
Normal file
99
tests/label_test.py
Normal file
@@ -0,0 +1,99 @@
|
||||
"""The 10x15 thermal label at Finalizado (Fase 2, front 10).
|
||||
|
||||
Run inside the API container: python -m tests.label_test
|
||||
"""
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request
|
||||
from uuid import uuid4
|
||||
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from app.core import db
|
||||
from tests.smoke_test import BASE, Client, with_host
|
||||
from tests.users_test import PASSWORD, order_fixture
|
||||
|
||||
|
||||
def label_page(client, order_id, expected=200):
|
||||
"""GET the label as the browser does; returns the HTML (or the error body)."""
|
||||
request = Request(BASE + '/api/operator/orders/' + order_id + '/label', headers=with_host())
|
||||
try:
|
||||
with client.opener.open(request, timeout=30) as response:
|
||||
assert response.status == expected, (response.status, expected)
|
||||
assert response.headers.get_content_type() == 'text/html', response.headers
|
||||
return response.read().decode()
|
||||
except HTTPError as error:
|
||||
if error.code != expected:
|
||||
raise AssertionError((error.code, expected, error.read().decode())) from error
|
||||
return error.read().decode()
|
||||
|
||||
|
||||
def user(superadmin, tag, role, name):
|
||||
email = f'etiqueta-{tag}-{role}@example.test'
|
||||
superadmin.call('/operator/users',
|
||||
{'name': name, 'email': email, 'role': role, 'password': PASSWORD}, operator=True)
|
||||
client = Client()
|
||||
client.call('/session')
|
||||
client.call('/operator/login', {'email': email, 'password': PASSWORD})
|
||||
return client
|
||||
|
||||
|
||||
def run():
|
||||
su = Client()
|
||||
su.call('/session')
|
||||
su.call('/operator/me', operator=True) # the default superadmin
|
||||
tag = uuid4().hex[:6]
|
||||
revisor_email = f'etiqueta-{tag}-revisor@example.test'
|
||||
revisor = user(su, tag, 'revisor', 'Revisor Etiqueta')
|
||||
designer = user(su, tag, 'designer', 'Designer Etiqueta')
|
||||
expedicao = user(su, tag, 'expedicao', 'Expedição Etiqueta')
|
||||
|
||||
owner = uuid4()
|
||||
with db.connect() as c:
|
||||
_, order_id = order_fixture(c, owner, 'file', metres='2.5')
|
||||
snapshot = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone()['snapshot']
|
||||
snapshot['customer']['name'] = 'Cliente Etiqueta'
|
||||
snapshot['destination'] = {'recipient': 'Loja Etiqueta', 'street': 'Rua A', 'number': '10',
|
||||
'complement': '', 'district': 'Centro', 'city': 'Franca',
|
||||
'state': 'SP', 'postal_code': '14400000'}
|
||||
snapshot['freight'] = {'service': 'jadlog', 'description': 'Jadlog .Package', 'total_cents': 1500}
|
||||
c.execute("UPDATE dtf_local.orders SET snapshot=%s, state='fin' WHERE id=%s",
|
||||
(Jsonb(snapshot), order_id))
|
||||
c.execute("INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason) "
|
||||
"VALUES(%s,'rev','fin',%s,'')", (order_id, revisor_email))
|
||||
number = c.execute('SELECT number FROM dtf_local.orders WHERE id=%s', (order_id,)).fetchone()['number']
|
||||
oid = str(order_id)
|
||||
|
||||
# The first computer claims the automatic print; the second does not.
|
||||
assert su.call(f'/operator/orders/{oid}/label/claim', {}, operator=True) == {'print': True}
|
||||
assert su.call(f'/operator/orders/{oid}/label/claim', {}, operator=True) == {'print': False}
|
||||
# A reprint always prints, on any computer.
|
||||
assert su.call(f'/operator/orders/{oid}/label/reprint', {}, operator=True) == {'print': True}
|
||||
|
||||
# The page is the server's HTML: customer, what the order is, delivery, QR.
|
||||
page = label_page(revisor, oid)
|
||||
assert 'Cliente Etiqueta' in page, page
|
||||
assert 'DTF · 1 folha · 2,50 m' in page, page
|
||||
assert 'Envio · Jadlog .Package' in page, page
|
||||
assert 'Revisor Etiqueta' in page, page
|
||||
assert '<svg' in page, page
|
||||
# No Tiny receipt: the order's own DTF number, also in the QR.
|
||||
assert f'DTF-{number}' in page, page
|
||||
|
||||
# With the Tiny sale receipt, its number takes the big type and the QR.
|
||||
with db.connect() as c:
|
||||
c.execute('''INSERT INTO dtf_local.outbox(event_key,provider,payload,receipt,delivered_at)
|
||||
VALUES(%s,'tiny',%s,%s,now())''', (f'{oid}:paid:tiny', Jsonb({}),
|
||||
Jsonb({'tiny_number': '98765'})))
|
||||
page = label_page(revisor, oid)
|
||||
assert '98765' in page, page
|
||||
assert f'DTF-{number}' not in page, page
|
||||
|
||||
# Only the label profiles print it: the designer may not, Expedição may.
|
||||
label_page(designer, oid, expected=403)
|
||||
label_page(expedicao, oid)
|
||||
print('PASS: the label page, one automatic print, reprint, Tiny number, designer refused '
|
||||
'and Expedição allowed')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run()
|
||||
@@ -3,22 +3,52 @@
|
||||
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 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
|
||||
|
||||
PASSWORD = 'senha-de-teste-123'
|
||||
UV = 'uv'
|
||||
PREMIUM = 'premium'
|
||||
|
||||
|
||||
def quote(client, item, mail):
|
||||
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'}})
|
||||
'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():
|
||||
@@ -31,11 +61,72 @@ 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', 'tratamento'}
|
||||
assert all(product['unit'] in ('metro', 'pedido') and product['title'] for product in products)
|
||||
assert {product['id'] for product in products} == \
|
||||
{'file', 'avulsa', 'uvfile', 'uv', 'premium', 'tratamento'}
|
||||
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')),
|
||||
'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']
|
||||
|
||||
manager.call(f'/operator/site/products/{UV}', {'enabled': True})
|
||||
uid = upload_bytes(client, artwork(), name='LOCAL-SITE-ADMIN.png')
|
||||
@@ -109,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'
|
||||
@@ -123,13 +212,20 @@ def run():
|
||||
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')
|
||||
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,'
|
||||
' 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)
|
||||
|
||||
@@ -131,7 +131,7 @@ def item_spec(mode, metres, grade, uid):
|
||||
return {'mode':mode,'metres':str(metres),'grade':grade,'uploads':[uid],
|
||||
'production':{'version':2,'film_width_cm':film_width,'height_cm':length_cm,
|
||||
'sources':[{'upload_id':uid,
|
||||
'kind':'sheet' if mode in ('file','uvfile') else 'artwork',
|
||||
'kind':'sheet' if mode in ('file','uvfile','premium') else 'artwork',
|
||||
'width_cm':film_width,'length_cm':length_cm,'copies':1,
|
||||
'rotation_degrees':0,'mirrored':False,'measurement':'customer'}],
|
||||
'placements':[{'source_index':0,'copy_index':0,'x_cm':0,'y_cm':0,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""The montador: stamp sizes, and the invoiced order a sheet becomes.
|
||||
"""The montador: stamp sizes, brand per stamp, and the Interno and Venda
|
||||
orders a sheet becomes (fronts 7a to 7a.3).
|
||||
|
||||
Run against the local stack: python -m tests.stamps_test
|
||||
"""
|
||||
@@ -14,6 +15,7 @@ from tests.smoke_test import Client
|
||||
|
||||
PASSWORD = 'senha-de-teste-123'
|
||||
PNG = (Path(__file__).resolve().parent / 'fixtures' / 'final-300.png').read_bytes()
|
||||
INTERNAL_MISSING = 'Peça à Gestão para completar o cliente interno.'
|
||||
|
||||
|
||||
def signed_in(email, password=PASSWORD):
|
||||
@@ -55,6 +57,10 @@ def montador_item(uid, mode='avulsa'):
|
||||
'quality_status': 'ok', 'quality_acknowledged': False, 'residue_accepted': 0}
|
||||
|
||||
|
||||
def price_table(stats):
|
||||
return {row['method']: row for row in stats['price_table']}
|
||||
|
||||
|
||||
def run():
|
||||
tag = secrets.token_hex(3)
|
||||
su = Client()
|
||||
@@ -62,27 +68,39 @@ def run():
|
||||
assert su.call('/operator/me', operator=True)['role'] == 'superadmin'
|
||||
with db.connect() as c:
|
||||
original = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall()
|
||||
emails = {role: f'{role}-{tag}@example.test' for role in ('expedicao', 'designer', 'gestao')}
|
||||
internal = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone()
|
||||
# The seed state: only the name, so Interno must be refused until
|
||||
# Gestão completes the other fields.
|
||||
c.execute("UPDATE dtf_local.internal_customer SET name='Nexstar · Marketplace',"
|
||||
"cnpj='',zap='',mail=''")
|
||||
emails = {role: f'{role}-{tag}@example.test' for role in ('expedicao', 'vendedor', 'designer', 'gestao')}
|
||||
table = [(row['letter'], float(row['width_cm'])) for row in original]
|
||||
customer = {'name': 'Cliente Montador', 'cnpj': '11222333000181', 'zap': '16999999999',
|
||||
'mail': f'montador-{tag}@example.test'}
|
||||
identity = operator_identity(emails['expedicao'])
|
||||
internal_customer = {'name': 'Nexstar · Marketplace', 'cnpj': '11222333000181',
|
||||
'zap': '1633334444', 'mail': f'interno-{tag}@example.test'}
|
||||
venda_customer = {'name': 'Maria Souza', 'cnpj': '12345678909',
|
||||
'zap': '16988887777', 'mail': f'venda-{tag}@example.test'}
|
||||
envio_customer = {'name': 'Maria Souza', 'cnpj': '12345678909',
|
||||
'zap': '16988887777', 'mail': f'envio-{tag}@example.test'}
|
||||
identities = [operator_identity(emails['expedicao']), operator_identity(emails['vendedor'])]
|
||||
made_orders, made_quotes = [], []
|
||||
# A code of its own, so a brand someone saved in Estampas/ is never touched.
|
||||
stamp_code = 'T' + tag
|
||||
try:
|
||||
for role, email in emails.items():
|
||||
su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role,
|
||||
'password': PASSWORD}, operator=True)
|
||||
# The new profile creates through the users API and reads the table.
|
||||
shipping = signed_in(emails['expedicao'])
|
||||
seller = signed_in(emails['vendedor'])
|
||||
manager = signed_in(emails['gestao'])
|
||||
designer = signed_in(emails['designer'])
|
||||
me = shipping.call('/operator/me')
|
||||
assert me['role'] == 'expedicao' and me['can'] == ['assemble', 'view'], me
|
||||
assert me['role'] == 'expedicao' and me['can'] == ['assemble', 'label', 'view'], me
|
||||
read = shipping.call('/operator/stamp-sizes')['sizes']
|
||||
assert [(row['letter'], float(row['width_cm'])) for row in read] == table, read
|
||||
# The designer does not assemble: no reading the table.
|
||||
designer = signed_in(emails['designer'])
|
||||
designer.call('/operator/stamp-sizes', expected=403)
|
||||
# Gestão replaces the whole table in one go and reads it back, by width.
|
||||
manager = signed_in(emails['gestao'])
|
||||
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'D', 'width_cm': 30},
|
||||
{'letter': 'A', 'width_cm': 20},
|
||||
{'letter': 'B', 'width_cm': 24.5}]})
|
||||
@@ -102,35 +120,123 @@ def run():
|
||||
read = manager.call('/operator/stamp-sizes')['sizes']
|
||||
assert [(row['letter'], float(row['width_cm'])) for row in read] == [('A', 20), ('B', 24.5), ('D', 30)], read
|
||||
|
||||
# The montador's order: the stamp upload, then the invoiced card in rec.
|
||||
# The brand per stamp: read by whoever assembles, saved by Gestão.
|
||||
default = shipping.call('/operator/stamps/' + stamp_code)
|
||||
assert default == {'code': stamp_code, 'brand': '', 'public': False}, default
|
||||
manager.call('/operator/stamps/' + stamp_code, {'brand': 'Dropstar', 'public': True})
|
||||
saved = shipping.call('/operator/stamps/' + stamp_code)
|
||||
assert saved == {'code': stamp_code, 'brand': 'Dropstar', 'public': True}, saved
|
||||
designer.call('/operator/stamps/' + stamp_code, {'brand': 'X', 'public': False}, expected=403)
|
||||
shipping.call('/operator/stamps/' + stamp_code, {'brand': 'X', 'public': False}, expected=403)
|
||||
|
||||
# The fake Tiny answers the Venda customer search with two contacts.
|
||||
contacts = shipping.call('/operator/tiny/contacts?q=Nexstar')
|
||||
assert len(contacts) == 2, contacts
|
||||
assert set(contacts[0]) == {'id', 'name', 'document', 'email', 'phone'}, contacts[0]
|
||||
assert contacts[0]['document'] == '11.222.333/0001-81', contacts[0]
|
||||
|
||||
# Interno is refused while Gestão has not completed the customer.
|
||||
stamp = upload_stamp(shipping)
|
||||
request_key = uuid4()
|
||||
body = {'request_key': str(request_key), 'customer': customer,
|
||||
'items': [montador_item(stamp)]}
|
||||
order = shipping.call('/operator/montador/orders', body)
|
||||
made_orders.append(UUID(order['id']))
|
||||
made_quotes.append(UUID(order['quote_id']))
|
||||
assert order['state'] == 'rec' and order['origin'] == 'dropflow', order
|
||||
payment = order['payment']
|
||||
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'faturado', 'paid'), payment
|
||||
assert payment['total_cents'] == order['snapshot']['total_cents'], payment
|
||||
interno = {'kind': 'interno', 'items': [montador_item(stamp)]}
|
||||
refused = shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno},
|
||||
expected=409)
|
||||
assert refused['detail'] == INTERNAL_MISSING, refused
|
||||
manager.call('/operator/internal-customer', internal_customer)
|
||||
completed = shipping.call('/operator/internal-customer')
|
||||
assert (completed['name'], completed['cnpj'], completed['zap'], completed['mail']) == (
|
||||
'Nexstar · Marketplace', '11222333000181', '1633334444', internal_customer['mail']), completed
|
||||
|
||||
before_stats = manager.call('/operator/stats?days=30')
|
||||
before = price_table(before_stats)
|
||||
# Interno: the fixed customer, origin dropflow, no Tiny, no paid e-mail.
|
||||
order_interno = shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno})
|
||||
made_orders.append(UUID(order_interno['id']))
|
||||
made_quotes.append(UUID(order_interno['quote_id']))
|
||||
assert order_interno['state'] == 'rec' and order_interno['origin'] == 'dropflow', order_interno
|
||||
assert order_interno['snapshot']['kind'] == 'interno', order_interno['snapshot'].get('kind')
|
||||
assert order_interno['snapshot']['customer']['cnpj'] == '11222333000181', order_interno['snapshot']
|
||||
payment = order_interno['payment']
|
||||
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'interno', 'paid'), payment
|
||||
with db.connect() as c:
|
||||
assert c.execute('SELECT 1 FROM dtf_local.print_files WHERE order_id=%s',
|
||||
(UUID(order['id']),)).fetchone()
|
||||
(UUID(order_interno['id']),)).fetchone()
|
||||
assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s',
|
||||
(f"{order['id']}:paid:tiny",)).fetchone()
|
||||
(f"{order_interno['id']}:paid:tiny",)).fetchone()
|
||||
assert not c.execute('SELECT 1 FROM dtf_local.mail_queue WHERE to_addr=%s',
|
||||
(internal_customer['mail'],)).fetchone()
|
||||
|
||||
# Venda: a Tiny customer, origin atendimento, invoiced and sent to Tiny.
|
||||
venda_stamp = upload_stamp(seller)
|
||||
venda = {'kind': 'venda', 'customer': venda_customer, 'with_order': 4321,
|
||||
'items': [montador_item(venda_stamp)]}
|
||||
venda_body = {'request_key': str(uuid4()), **venda}
|
||||
order_venda = seller.call('/operator/montador/orders', venda_body)
|
||||
made_orders.append(UUID(order_venda['id']))
|
||||
made_quotes.append(UUID(order_venda['quote_id']))
|
||||
assert order_venda['state'] == 'rec' and order_venda['origin'] == 'atendimento', order_venda
|
||||
assert order_venda['snapshot']['with_order'] == 4321, order_venda['snapshot'].get('with_order')
|
||||
payment = order_venda['payment']
|
||||
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'faturado', 'paid'), payment
|
||||
with db.connect() as c:
|
||||
assert c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s AND provider=%s',
|
||||
(f"{order_venda['id']}:paid:tiny", 'tiny')).fetchone()
|
||||
assert not c.execute('SELECT 1 FROM dtf_local.mail_queue WHERE to_addr=%s',
|
||||
(venda_customer['mail'],)).fetchone()
|
||||
|
||||
# Números: both are counted apart from the money received.
|
||||
after_stats = manager.call('/operator/stats?days=30')
|
||||
after = price_table(after_stats)
|
||||
for method, order in (('interno', order_interno), ('faturado', order_venda)):
|
||||
assert after[method]['orders'] == before[method]['orders'] + 1, (method, before[method], after[method])
|
||||
assert after[method]['cents'] == before[method]['cents'] + order['snapshot']['total_cents'], (method, before[method], after[method])
|
||||
assert after[method]['metres'] > before[method]['metres'], (method, before[method], after[method])
|
||||
assert after_stats['cents'] == before_stats['cents'], (before_stats['cents'], after_stats['cents'])
|
||||
|
||||
# The same montagem cannot become a second order.
|
||||
refused = shipping.call('/operator/montador/orders', body, expected=409)
|
||||
assert refused['detail'] == f"Esta montagem já virou o pedido #{order['number']}.", refused
|
||||
# A designer does not use the montador, and only loose art becomes one.
|
||||
refused = seller.call('/operator/montador/orders', venda_body, expected=409)
|
||||
assert refused['detail'] == f"Esta montagem já virou o pedido #{order_venda['number']}.", refused
|
||||
# Each profile makes only its own kind, and only loose art becomes one.
|
||||
seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno}, expected=403)
|
||||
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **venda}, expected=403)
|
||||
designer.call('/operator/montador/uploads', {'name': 'ESTAMPA.png', 'size': 1}, expected=403)
|
||||
designer.call('/operator/montador/orders', body, expected=403)
|
||||
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'customer': customer,
|
||||
designer.call('/operator/montador/orders', {'request_key': str(uuid4()), **venda}, expected=403)
|
||||
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'interno',
|
||||
'items': [montador_item(stamp, 'file')]}, expected=422)
|
||||
print('PASS: Expedição reads the sizes, uploads a stamp and gets the invoiced montador card; '
|
||||
'Gestão edits the table; invalid rows, profiles and modes are refused')
|
||||
|
||||
# Venda with Envio: the Site's freight, re-quoted by the server.
|
||||
destination = {'recipient': 'Maria Souza', 'street': 'Rua das Flores', 'number': '100',
|
||||
'complement': 'Sala 2', 'district': 'Centro', 'city': 'Franca',
|
||||
'state': 'SP', 'postal_code': '14400000'}
|
||||
envio_stamp = upload_stamp(seller)
|
||||
envio = {'kind': 'venda', 'customer': envio_customer, 'items': [montador_item(envio_stamp)],
|
||||
'freight': {'service': 'mock-standard', 'postal_code': '14400000'},
|
||||
'destination': destination}
|
||||
order_envio = seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **envio})
|
||||
made_orders.append(UUID(order_envio['id']))
|
||||
made_quotes.append(UUID(order_envio['quote_id']))
|
||||
snapshot = order_envio['snapshot']
|
||||
assert snapshot['destination'] == destination, snapshot.get('destination')
|
||||
assert snapshot['freight']['service'] == 'mock-standard', snapshot.get('freight')
|
||||
assert snapshot['freight']['total_cents'] > 0, snapshot.get('freight')
|
||||
assert snapshot['total_cents'] == (sum(item['total_cents'] for item in snapshot['items']) +
|
||||
snapshot['freight']['total_cents']), snapshot['total_cents']
|
||||
with db.connect() as c:
|
||||
assert c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s AND provider=%s',
|
||||
(f"{order_envio['id']}:paid:tiny", 'tiny')).fetchone()
|
||||
# Envio needs the full address; an Interno order never ships.
|
||||
sem_destino = {key: value for key, value in envio.items() if key != 'destination'}
|
||||
seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **sem_destino}, expected=422)
|
||||
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'interno',
|
||||
'items': [montador_item(stamp)],
|
||||
'destination': destination}, expected=422)
|
||||
print('PASS: Expedição makes Interno and Vendedor makes Venda; the internal customer, the Tiny '
|
||||
'contacts, the stamp brand and the table price in Números work; a Venda with Envio carries '
|
||||
'the destination and the quoted freight; invalid profiles, modes and deliveries are refused')
|
||||
finally:
|
||||
with db.connect() as c:
|
||||
if made_orders:
|
||||
c.execute("DELETE FROM dtf_local.outbox WHERE payload->>'order_id' = ANY(%s::text[])",
|
||||
([str(oid) for oid in made_orders],))
|
||||
for oid in made_orders:
|
||||
c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (oid,))
|
||||
c.execute('DELETE FROM dtf_local.order_files WHERE order_id=%s', (oid,))
|
||||
@@ -139,8 +245,13 @@ def run():
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,))
|
||||
if made_quotes:
|
||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', (made_quotes,))
|
||||
c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr=%s', (customer['mail'],))
|
||||
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (identity,))
|
||||
c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr IN (%s,%s,%s)',
|
||||
(internal_customer['mail'], venda_customer['mail'], envio_customer['mail']))
|
||||
for identity in identities:
|
||||
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (identity,))
|
||||
c.execute('DELETE FROM dtf_local.stamps WHERE code=%s', (stamp_code,))
|
||||
c.execute('UPDATE dtf_local.internal_customer SET name=%s,cnpj=%s,zap=%s,mail=%s',
|
||||
(internal['name'], internal['cnpj'], internal['zap'], internal['mail']))
|
||||
c.execute('DELETE FROM dtf_local.stamp_sizes')
|
||||
c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES(%s,%s)', table)
|
||||
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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.')
|
||||
|
||||
|
||||
|
||||
26
tests/test_hotfolder.py
Normal file
26
tests/test_hotfolder.py
Normal file
@@ -0,0 +1,26 @@
|
||||
"""The machine hot folder class (Fase 2, front 3), without a database."""
|
||||
import unittest
|
||||
|
||||
from app.hotfolder import PREMIUM, contraction, folder_class
|
||||
|
||||
|
||||
def order(mode, stroke_class='C2', chosen=None):
|
||||
return {'snapshot': {'items': [{'mode': mode, 'stroke_class': stroke_class}]},
|
||||
'contraction': {'0': {'class': chosen}} if chosen else {}}
|
||||
|
||||
|
||||
class FolderClassTest(unittest.TestCase):
|
||||
def test_premium_always_goes_to_its_own_folder(self):
|
||||
# Marcus, 2026-11-10: every premium item, whatever its contraction class.
|
||||
self.assertEqual(folder_class(order('premium', 'C3'), 0), PREMIUM)
|
||||
self.assertEqual(folder_class(order('premium', 'C1', chosen='C2'), 0), PREMIUM)
|
||||
|
||||
def test_a_recorded_contraction_class_still_wins_for_other_products(self):
|
||||
self.assertEqual(folder_class(order('file', 'C1', chosen='C2'), 0), 'C2')
|
||||
self.assertEqual(folder_class(order('file'), 0), 'C2')
|
||||
self.assertIsNone(contraction(order('file', None), 0))
|
||||
self.assertIsNone(folder_class(order('file', None), 0))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
80
tests/test_label.py
Normal file
80
tests/test_label.py
Normal file
@@ -0,0 +1,80 @@
|
||||
"""The 10x15 label's fields and page (Fase 2, front 10), without a database."""
|
||||
import importlib.util
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.label import label_fields, label_html
|
||||
|
||||
HAS_SEGNO = importlib.util.find_spec('segno') is not None
|
||||
|
||||
|
||||
def order(**snapshot):
|
||||
content = {'customer': {'name': 'Cliente Etiqueta', 'mail': 'cliente@example.test'},
|
||||
'items': [{'billed_metres': '1.5'}, {'billed_metres': '1'}],
|
||||
'destination': {'recipient': 'Loja Etiqueta'},
|
||||
'freight': {'service': 'jadlog', 'description': 'Jadlog .Package'}}
|
||||
content.update(snapshot)
|
||||
return {'number': 42, 'snapshot': content}
|
||||
|
||||
|
||||
FINISHED = datetime(2026, 11, 11, 17, 32, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
class LabelFieldsTest(unittest.TestCase):
|
||||
def test_the_order_number_falls_back_to_dtf_when_tiny_did_not_answer(self):
|
||||
fields = label_fields(order(), None, FINISHED, 'Revisor Etiqueta')
|
||||
self.assertEqual(fields['code'], 'DTF-42')
|
||||
self.assertEqual(fields['qr'], 'DTF-42')
|
||||
fields = label_fields(order(), '98765', FINISHED, 'Revisor Etiqueta')
|
||||
self.assertEqual(fields['code'], '98765')
|
||||
self.assertEqual(fields['qr'], '98765')
|
||||
|
||||
def test_customer_sheets_and_billed_metres(self):
|
||||
fields = label_fields(order(), '98765', FINISHED, 'Revisor Etiqueta')
|
||||
self.assertEqual(fields['customer'], 'Cliente Etiqueta')
|
||||
self.assertEqual(fields['sheets'], 2)
|
||||
self.assertEqual(fields['metres'], '2,50')
|
||||
self.assertEqual(fields['finished_at'], '11/11/2026 14:32')
|
||||
self.assertEqual(fields['revisor'], 'Revisor Etiqueta')
|
||||
|
||||
def test_pickup_shipping_interno_and_junto_com_a_roupa(self):
|
||||
pickup = order(destination=None, freight={'service': 'pickup'})
|
||||
self.assertEqual(label_fields(pickup, None, FINISHED, None)['delivery'], 'Retirada')
|
||||
self.assertEqual(label_fields(order(), None, FINISHED, None)['delivery'],
|
||||
'Envio · Jadlog .Package')
|
||||
self.assertEqual(label_fields(order(kind='interno'), None, FINISHED, None)['delivery'], 'Interno')
|
||||
self.assertEqual(label_fields(order(with_order='4321'), None, FINISHED, None)['delivery'],
|
||||
'Junto com pedido de roupa nº 4321')
|
||||
# The internal customer's name is the one on the label.
|
||||
self.assertEqual(label_fields(order(kind='interno', destination=None), None, FINISHED, None)['customer'],
|
||||
'Cliente Etiqueta')
|
||||
|
||||
|
||||
class LabelHtmlTest(unittest.TestCase):
|
||||
@unittest.skipUnless(HAS_SEGNO, 'segno is installed with the API image')
|
||||
def test_the_page_is_sized_for_the_10x15_label(self):
|
||||
fields = label_fields(order(), '98765', FINISHED, 'Revisor Etiqueta')
|
||||
page = label_html(fields)
|
||||
self.assertIn('@page { size: 100mm 150mm; margin: 0 }', page)
|
||||
self.assertIn('98765', page)
|
||||
self.assertIn('Cliente Etiqueta', page)
|
||||
self.assertIn('DTF · 2 folhas · 2,50 m', page)
|
||||
self.assertIn('Envio · Jadlog .Package', page)
|
||||
self.assertIn('Finalizado em 11/11/2026 14:32', page)
|
||||
self.assertIn('Revisor: Revisor Etiqueta', page)
|
||||
self.assertIn('<svg', page)
|
||||
# The viewBox lets the CSS print the QR at 30 mm; a fixed pixel width
|
||||
# would leave the modules tiny.
|
||||
self.assertIn('viewBox=', page)
|
||||
|
||||
@unittest.skipUnless(HAS_SEGNO, 'segno is installed with the API image')
|
||||
def test_the_customer_name_is_escaped(self):
|
||||
fields = label_fields(order(customer={'name': '<b>Loja</b>', 'mail': 'x@example.test'}),
|
||||
None, FINISHED, None)
|
||||
page = label_html(fields)
|
||||
self.assertIn('<b>Loja</b>', page)
|
||||
self.assertNotIn('<b>Loja</b>', page)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -2,8 +2,8 @@
|
||||
import unittest
|
||||
from decimal import Decimal
|
||||
|
||||
from app.machine_log import (ALIGN_AFTER_FILM_METRES, CLEAN_EVERY_METRES, estimate,
|
||||
one_decimal, supply_low)
|
||||
from app.machine_log import (ALIGN_AFTER_FILM_METRES, CLEAN_EVERY_METRES, DEFAULT_MINIMUMS,
|
||||
estimate, minimum_for, one_decimal, supply_low)
|
||||
|
||||
|
||||
class EstimateTest(unittest.TestCase):
|
||||
@@ -38,6 +38,22 @@ class EstimateTest(unittest.TestCase):
|
||||
self.assertEqual(CLEAN_EVERY_METRES, Decimal('10'))
|
||||
self.assertEqual(ALIGN_AFTER_FILM_METRES, Decimal('20'))
|
||||
|
||||
def test_a_machine_without_typed_minimums_alerts_at_dropstars_defaults(self):
|
||||
# Marcus, 2026-11-10: 1 roll of film, 1 L of each ink, 5 kg of powder.
|
||||
self.assertEqual(DEFAULT_MINIMUMS, {'film': Decimal('1'), 'ink_c': Decimal('1'),
|
||||
'ink_m': Decimal('1'), 'ink_y': Decimal('1'),
|
||||
'ink_k': Decimal('1'), 'ink_w': Decimal('1'),
|
||||
'powder': Decimal('5')})
|
||||
for item, default in DEFAULT_MINIMUMS.items():
|
||||
with self.subTest(item=item):
|
||||
minimum = minimum_for({}, item)
|
||||
self.assertEqual(minimum, default)
|
||||
value = estimate([Decimal('1'), Decimal('1')], [Decimal('10')],
|
||||
Decimal('9'), minimum)
|
||||
self.assertTrue(supply_low(value))
|
||||
# A minimum Gestão typed still wins over the default.
|
||||
self.assertEqual(minimum_for({'film': Decimal('0')}, 'film'), Decimal('0'))
|
||||
|
||||
|
||||
class AlertTextTest(unittest.TestCase):
|
||||
def test_one_decimal_uses_a_comma(self):
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""Who moves which card on the Kanban: Dropstar's flow of 2026-10-23."""
|
||||
import os
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from app import payments
|
||||
from app import payments, tiny
|
||||
from app.core import auth
|
||||
from app.core.auth import CAPABILITIES, ROLES, may_move, may_reorder
|
||||
from app.runtime import BACK, STATES, TRANSITIONS
|
||||
@@ -55,6 +56,15 @@ class MovesTest(unittest.TestCase):
|
||||
self.assertEqual(CAPABILITIES['assemble'],
|
||||
{'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'})
|
||||
|
||||
def test_the_label_is_printed_by_these_profiles(self):
|
||||
# Marcus, 2026-11-10: the Revisor who releases the card, Expedição and
|
||||
# Gestão; the designer, the operator and the seller do not print it.
|
||||
self.assertEqual(CAPABILITIES['label'],
|
||||
{'superadmin', 'admin', 'gestao', 'revisor', 'expedicao'})
|
||||
for role in ROLES:
|
||||
self.assertEqual(role in CAPABILITIES['label'],
|
||||
role in ('superadmin', 'admin', 'gestao', 'revisor', 'expedicao'), role)
|
||||
|
||||
def test_a_column_is_ordered_by_whoever_takes_its_cards_forward(self):
|
||||
self.assertEqual([s for s in STATES if may_reorder('operador', s)], ['tra', 'imp'])
|
||||
self.assertEqual([s for s in STATES if may_reorder('designer', s)], ['rec', 'cor'])
|
||||
@@ -78,14 +88,31 @@ class CanAnyTest(unittest.TestCase):
|
||||
route(None)
|
||||
|
||||
|
||||
class InvoicedOrderTest(unittest.TestCase):
|
||||
def test_an_invoiced_montador_order_is_held_out_of_tiny(self):
|
||||
class MontadorPaymentTest(unittest.TestCase):
|
||||
def test_a_faturado_order_goes_to_tiny_and_an_internal_one_does_not(self):
|
||||
self.assertEqual(payments.INVOICED_METHOD, 'faturado')
|
||||
# It is not one of the Cotações "registrar" methods.
|
||||
self.assertEqual(payments.INTERNAL_METHOD, 'interno')
|
||||
# Neither is one of the Cotações "registrar" methods.
|
||||
self.assertNotIn(payments.INVOICED_METHOD, payments.OUTSIDE_METHODS)
|
||||
self.assertFalse(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'faturado'}}))
|
||||
self.assertNotIn(payments.INTERNAL_METHOD, payments.OUTSIDE_METHODS)
|
||||
self.assertTrue(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'faturado'}}))
|
||||
self.assertFalse(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'interno'}}))
|
||||
self.assertTrue(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'pix'}}))
|
||||
|
||||
|
||||
class InternalNoteTest(unittest.TestCase):
|
||||
payload = {'order_id': 'b6f1c0de-0000-4000-8000-000000000001', 'number': 42,
|
||||
'origin': 'atendimento', 'payment': {'method': 'faturado', 'outside': True},
|
||||
'order': {'with_order': 4321}}
|
||||
|
||||
def test_an_invoiced_order_says_how_it_is_received(self):
|
||||
with mock.patch.dict(os.environ, {'TINY_RECEIPT_BOLETO': ''}):
|
||||
note = tiny.internal_note(self.payload)
|
||||
self.assertIn('faturado: forma de recebimento a definir', note)
|
||||
self.assertIn('junto com o pedido de roupa nº 4321', note)
|
||||
with mock.patch.dict(os.environ, {'TINY_RECEIPT_BOLETO': '123456'}):
|
||||
self.assertIn('faturado (Boleto)', tiny.internal_note(self.payload))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
83
tests/test_observability.py
Normal file
83
tests/test_observability.py
Normal file
@@ -0,0 +1,83 @@
|
||||
"""Sentry's scrubbing rules and its off switch (note Sentry)."""
|
||||
import os
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
try:
|
||||
import sentry_sdk
|
||||
except ImportError: # pragma: no cover - the host may not have the dependency
|
||||
sentry_sdk = None
|
||||
|
||||
from app import observability
|
||||
|
||||
|
||||
@unittest.skipUnless(sentry_sdk, 'sentry-sdk is installed with the API image')
|
||||
class ScrubTest(unittest.TestCase):
|
||||
def test_request_credentials_tokens_and_bodies_are_removed(self):
|
||||
event = {'request': {
|
||||
'url': 'https://dtf.example/api/quotes?page=2&token=abc&X-Amz-Signature=def',
|
||||
'query_string': 'page=2&token=abc&X-Amz-Signature=def',
|
||||
'cookies': {'dtf_session': 'secret'},
|
||||
'data': '{"customer":{"mail":"maria@example.com"}}',
|
||||
'headers': {'Cookie': 'dtf_session=secret', 'Authorization': 'Bearer x',
|
||||
'X-Auth-Token': 'x', 'X-Amz-Security-Token': 'x',
|
||||
'X-Forwarded-For': '1.2.3.4'},
|
||||
}}
|
||||
observability.scrub(event)
|
||||
request = event['request']
|
||||
self.assertNotIn('cookies', request)
|
||||
self.assertNotIn('data', request)
|
||||
self.assertEqual(request['headers'], {'X-Forwarded-For': '1.2.3.4'})
|
||||
self.assertEqual(request['query_string'], 'page=2')
|
||||
self.assertEqual(request['url'], 'https://dtf.example/api/quotes?page=2')
|
||||
|
||||
def test_personal_data_in_messages_exceptions_and_breadcrumbs(self):
|
||||
event = {
|
||||
'message': 'Falha para maria@example.com, CPF 123.456.789-01, CNPJ 11.222.333/0001-81',
|
||||
'exception': {'values': [{'value': 'e-mail ana@example.com'}]},
|
||||
'breadcrumbs': [
|
||||
{'message': 'GET https://x/y?token=abc',
|
||||
'data': {'url': 'https://x/y?page=1&token=abc', 'note': 'CPF 12345678901'}},
|
||||
{'message': 'CNPJ 11222333000181'},
|
||||
],
|
||||
}
|
||||
observability.scrub(event)
|
||||
self.assertNotIn('maria@example.com', event['message'])
|
||||
self.assertNotIn('123.456.789-01', event['message'])
|
||||
self.assertNotIn('11.222.333/0001-81', event['message'])
|
||||
self.assertEqual(event['message'].count(observability.REDACTED), 3)
|
||||
self.assertNotIn('ana@example.com', event['exception']['values'][0]['value'])
|
||||
self.assertNotIn('token=abc', event['breadcrumbs'][0]['message'])
|
||||
self.assertNotIn('token=abc', event['breadcrumbs'][0]['data']['url'])
|
||||
self.assertNotIn('12345678901', event['breadcrumbs'][0]['data']['note'])
|
||||
self.assertNotIn('11222333000181', event['breadcrumbs'][1]['message'])
|
||||
|
||||
|
||||
@unittest.skipUnless(sentry_sdk, 'sentry-sdk is installed with the API image')
|
||||
class InitTest(unittest.TestCase):
|
||||
def test_no_dsn_does_nothing(self):
|
||||
with mock.patch.dict(os.environ, {'SENTRY_DSN_API': ''}):
|
||||
with mock.patch.object(sentry_sdk, 'init') as init:
|
||||
self.assertFalse(observability.init('api'))
|
||||
init.assert_not_called()
|
||||
|
||||
def test_a_dsn_initialises_without_pii_and_scrubs(self):
|
||||
env = {'SENTRY_DSN_API': 'https://key@o1.ingest.sentry.io/1',
|
||||
'SENTRY_ENVIRONMENT': 'test', 'IMAGE_TAG': 'abc123',
|
||||
'SENTRY_TRACES': '0.2'}
|
||||
with mock.patch.dict(os.environ, env):
|
||||
with mock.patch.object(sentry_sdk, 'init') as init, \
|
||||
mock.patch.object(sentry_sdk, 'set_tag') as set_tag:
|
||||
self.assertTrue(observability.init('api'))
|
||||
options = init.call_args.kwargs
|
||||
self.assertEqual(options['dsn'], env['SENTRY_DSN_API'])
|
||||
self.assertEqual(options['environment'], 'test')
|
||||
self.assertEqual(options['release'], 'abc123')
|
||||
self.assertIs(options['send_default_pii'], False)
|
||||
self.assertEqual(options['traces_sample_rate'], 0.2)
|
||||
self.assertIs(options['before_send'], observability.scrub)
|
||||
set_tag.assert_called_once_with('component', 'api')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -34,8 +34,9 @@ class PricingTests(unittest.TestCase):
|
||||
|
||||
def test_one_price_per_product(self):
|
||||
# Dropstar, 2026-10-23: textile R$ 19,90 ready sheet and R$ 21,90 loose
|
||||
# art; UV R$ 79,90 and R$ 89,90.
|
||||
self.assertEqual(PRICES, {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990})
|
||||
# art; UV R$ 79,90 and R$ 89,90. Premium R$ 39,90 (2026-11-10).
|
||||
self.assertEqual(PRICES, {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990,
|
||||
'premium': 3990})
|
||||
self.assertEqual(price('avulsa', '2.75', 90)['total_cents'], 6132)
|
||||
|
||||
def test_the_grade_never_changes_the_price(self):
|
||||
@@ -132,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}]}}
|
||||
|
||||
@@ -24,7 +24,8 @@ PAID = {'order_id': 'b6f1c0de-0000-4000-8000-000000000001', 'number': 42, 'event
|
||||
'state': 'SP', 'postal_code': '14400000'},
|
||||
'total_cents': 8472}}
|
||||
PRODUCTS = {'TINY_PRODUCT_TEXTIL_FOLHA': '101', 'TINY_PRODUCT_TEXTIL_AVULSA': '102',
|
||||
'TINY_PRODUCT_UV_FOLHA': '103', 'TINY_PRODUCT_UV_AVULSA': '104', 'TINY_FORMA_ENVIO_RETIRADA': '77'}
|
||||
'TINY_PRODUCT_UV_FOLHA': '103', 'TINY_PRODUCT_UV_AVULSA': '104',
|
||||
'TINY_PRODUCT_TEXTIL_PREMIUM': '105', 'TINY_FORMA_ENVIO_RETIRADA': '77'}
|
||||
PICKUP = {**PAID, 'order': {**PAID['order'], 'destination': None, 'freight': {'service': 'pickup', 'total_cents': 0}}}
|
||||
READY = {'order_id': PAID['order_id'], 'number': 42, 'event': 'ready', 'reason': '', 'order': PICKUP['order']}
|
||||
|
||||
@@ -159,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)
|
||||
@@ -221,7 +231,7 @@ class TinyTests(FakeTinyCase):
|
||||
from app.tiny import check
|
||||
results = check(auth=FakeAuth(), transport=httpx.MockTransport(self.handler))
|
||||
self.assertEqual(set(results.values()), {'ok'})
|
||||
self.assertEqual(len(results), 7)
|
||||
self.assertEqual(len(results), 8)
|
||||
self.assertTrue(all(method == 'GET' for method, _ in self.calls))
|
||||
self.products['103']['situacao'] = 'I'
|
||||
with mock.patch.dict(os.environ, {'TINY_PRODUCT_UV_AVULSA': ''}):
|
||||
@@ -794,6 +804,9 @@ class DefaultSkuTests(unittest.TestCase):
|
||||
self.assertEqual(tiny.mode_codes('file'), tiny.sku_codes('DTFIMP.TX'))
|
||||
self.assertEqual(tiny.mode_codes('avulsa'), tiny.sku_codes('DTFIMP.TX'))
|
||||
self.assertEqual(tiny.mode_codes('uv'), ['DTFIMP.UV.1MT', 'DTFIMP.UV.010CM'])
|
||||
# Premium's own catalogue: DTFIMP.TXP.100CM per metre and DTFIMP.TXP.0010CM to 0090CM (Marcus, 2026-11-11).
|
||||
self.assertEqual(tiny.mode_codes('premium'), tiny.sku_codes('DTFIMP.TXP'))
|
||||
self.assertIn('DTFIMP.TXP.0010CM', tiny.mode_codes('premium'))
|
||||
self.assertEqual(tiny.required_settings(), ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'])
|
||||
with mock.patch.dict(os.environ, {'TINY_SKU10_UV_FOLHA': 'UV.X'}):
|
||||
self.assertEqual(tiny.mode_codes('uvfile'), ['UV.X'])
|
||||
|
||||
@@ -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__':
|
||||
|
||||
40
tests/upload_limits_test.py
Normal file
40
tests/upload_limits_test.py
Normal file
@@ -0,0 +1,40 @@
|
||||
"""The upload start limit: a large cart fits, and the per-source bucket
|
||||
still refuses above its own limit (Marcus's bugs of 2026-11-11, B1).
|
||||
|
||||
Run against the local stack: python -m tests.upload_limits_test
|
||||
"""
|
||||
import secrets
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.api.uploads import UPLOAD_START_IP_LIMIT, UPLOAD_START_LIMIT
|
||||
from app.core.auth import rate_limit
|
||||
from tests.smoke_test import Client
|
||||
|
||||
|
||||
def run():
|
||||
assert (UPLOAD_START_LIMIT, UPLOAD_START_IP_LIMIT) == (1000, 3000)
|
||||
client = Client()
|
||||
client.call('/session')
|
||||
# A 66-file cart, with retries, fits in one session. Each reservation is
|
||||
# cancelled so the pending-upload quota (unchanged) does not stop the test.
|
||||
for index in range(70):
|
||||
uid = client.call('/uploads', {'name': f'LIMIT-{index}.png', 'size': 1})['id']
|
||||
client.call(f'/uploads/{uid}', expected=200, method='DELETE')
|
||||
# The per-source bucket, exercised directly with a small limit: 3000 real
|
||||
# starts would only slow CI. A unique key keeps other suites out of it.
|
||||
key = 'upload-start-ip-test-' + secrets.token_hex(8)
|
||||
for _ in range(3):
|
||||
rate_limit('upload-start-ip', key, 3, 900)
|
||||
try:
|
||||
rate_limit('upload-start-ip', key, 3, 900)
|
||||
except HTTPException as error:
|
||||
assert error.status_code == 429, error
|
||||
assert error.headers.get('Retry-After') == '900', error.headers
|
||||
else:
|
||||
raise AssertionError('the per-source upload bucket accepted above its limit')
|
||||
print('PASS: 70 upload starts in one session; the per-source bucket refuses above its limit')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run()
|
||||
@@ -203,7 +203,7 @@ def run():
|
||||
'password': PASSWORD})
|
||||
reviewer = signed_in(emails['revisor'])
|
||||
me = reviewer.call('/operator/me')
|
||||
assert me['can'] == ['deliver', 'inspect', 'view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me
|
||||
assert me['can'] == ['deliver', 'inspect', 'label', 'view'] and sorted(me['moves']) == [['fin', 'rev'], ['rev', 'fin']] and me['reorder'] == ['rev'], me
|
||||
reviewer.call(f'/operator/orders/{textil_o}/move', {'state': 'tra', 'version': 0, 'reason': ''}, expected=403)
|
||||
assert reviewer.call(f'/operator/orders/{uv_o}/move', {'state': 'fin', 'version': printed['version'],
|
||||
'reason': ''})['state'] == 'fin'
|
||||
|
||||
Reference in New Issue
Block a user