diff --git a/app/core/models.py b/app/core/models.py index 4026a25..66268d1 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -129,7 +129,7 @@ class ProductionSource(StrictModel): measurement: Literal['file', 'customer'] class ProductionPlacement(StrictModel): - source_index: int = Field(ge=0, le=19, strict=True) + source_index: int = Field(ge=0, le=199, strict=True) copy_index: int = Field(ge=0, le=199, strict=True) x_cm: Decimal = Field(ge=0, le=57) y_cm: Decimal = Field(ge=0, le=1200000) @@ -148,7 +148,7 @@ class ProductionSpec(StrictModel): version: Literal[2, 3] film_width_cm: Decimal height_cm: Decimal = Field(gt=0, le=1200000) - sources: list[ProductionSource] = Field(min_length=1, max_length=20) + sources: list[ProductionSource] = Field(min_length=1, max_length=200) placements: list[ProductionPlacement] = Field(min_length=1, max_length=4000) class Split(StrictModel): @@ -177,7 +177,7 @@ class Item(StrictModel): mode: Literal['file','avulsa','uvfile','uv','premium'] metres: Decimal = Field(gt=0, le=12000) grade: int = Field(ge=0, le=100, strict=True) - uploads: list[UUID] = Field(min_length=1, max_length=20) + uploads: list[UUID] = Field(min_length=1, max_length=200) production: ProductionSpec quality_status: Literal['ok', 'warning', 'unverified'] quality_acknowledged: bool @@ -199,6 +199,15 @@ class Item(StrictModel): source_dpi: int | None = Field(default=None, ge=0, le=1000000) split: Split | None = None + @field_validator('uploads', mode='before') + @classmethod + def uploads_cap(cls, value): + # The Site shows a "Value error, ..." message as it is (web/checkout.js + # problem()); the Field cap alone would give the generic sentence. + if isinstance(value, list) and len(value) > 200: + raise ValueError('Este item tem mais de 200 arquivos. Divida em dois itens.') + return value + @model_validator(mode='after') def production_matches_uploads(self): if self.split and (self.mode not in ('avulsa', 'uv') or self.split.part > self.split.of): diff --git a/tests/upload_limits_test.py b/tests/upload_limits_test.py index b5285ee..4acb857 100644 --- a/tests/upload_limits_test.py +++ b/tests/upload_limits_test.py @@ -1,39 +1,87 @@ -"""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). +"""The upload limits: a 66-file cart fits, the per-source bucket still +refuses above its own limit (Marcus's bugs of 2026-11-11, B1), and a quote +takes up to 200 files per item (Sentry DTF-WEB-1). Run against the local stack: python -m tests.upload_limits_test """ import secrets +from pathlib import Path +from uuid import UUID, uuid4 from fastapi import HTTPException from app.api.uploads import UPLOAD_START_IP_LIMIT, UPLOAD_START_LIMIT +from app.core import db from app.core.auth import rate_limit -from tests.smoke_test import Client +from tests.smoke_test import Client, upload_bytes + +PNG = (Path(__file__).resolve().parent / 'fixtures' / 'final-300.png').read_bytes() +TOO_MANY = 'Este item tem mais de 200 arquivos. Divida em dois itens.' + + +def item_with(uploads): + """One ready-sheet item: one source per upload, stacked in a row.""" + count = len(uploads) + height = count * 0.3 + return { + 'mode': 'file', 'metres': round(height / 100, 4), 'grade': 100, 'uploads': uploads, + 'production': { + 'version': 3, 'film_width_cm': 57, 'height_cm': height, + 'sources': [{'upload_id': uid, 'kind': 'sheet', 'width_cm': 0.5, 'length_cm': 0.25, + 'copies': 1, 'rotation_degrees': 0, 'mirrored': False, + 'measurement': 'file'} for uid in uploads], + 'placements': [{'source_index': index, 'copy_index': 0, 'x_cm': 0, + 'y_cm': round(index * 0.3, 4), 'width_cm': 0.5, 'length_cm': 0.25, + 'rotation_degrees': 0, 'mirrored': False} for index in range(count)]}, + 'quality_status': 'ok', 'quality_acknowledged': False, 'residue_accepted': 0} 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) + scope = client.call('/session')['cart_scope'] 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') + # 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') + + # Sentry DTF-WEB-1: 66 sheets in one ready-sheet item is quoted and + # approved; the old cap of 20 refused it with a generic 422. + uploads = [upload_bytes(client, PNG, name=f'SHEET66-{index}.png') for index in range(66)] + body = {'request_key': str(uuid4()), 'customer': {'name': 'Carrinho Grande', + 'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'sheet66@example.test'}, + 'items': [item_with(uploads)], 'freight': {'service': 'pickup'}} + quote = client.call('/quotes', body) + assert quote['status'] == 'approved', quote + approved = client.call('/quotes/' + quote['id'])['approved']['items'][0] + assert (len(approved['uploads']), len(approved['production']['sources']), + len(approved['production']['placements'])) == (66, 66, 66), approved + # The old cap's message: one more file is refused with a readable text. + too_many = {**body, 'request_key': str(uuid4()), + 'items': [{**item_with(uploads), 'uploads': [str(uuid4()) for _ in range(201)]}]} + detail = client.call('/quotes', too_many, expected=422)['detail'] + messages = [entry.get('msg', '') for entry in detail if isinstance(entry, dict)] + assert any(TOO_MANY in message for message in messages), detail + print('PASS: 70 upload starts in one session; the per-source bucket refuses above its limit; ' + 'a 66-sheet item is quoted and 201 is refused with the readable message') + finally: + with db.connect() as c: + c.execute('DELETE FROM dtf_local.quotes WHERE owner=%s', (UUID(scope),)) + c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (UUID(scope),)) if __name__ == '__main__': diff --git a/web/checkout.js b/web/checkout.js index 0be9814..61b274b 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -447,6 +447,11 @@ if (semArquivo) return message(semArquivo+'.','error'); const cart = itensAPagar(); if (!cart.length) return message('Adicione um item ao pedido.','error'); + // One item carries at most 200 files (app/core/models.py); a bigger cart + // line is refused here, with the reason, never by the generic 422. + const semCap=cart.flatMap(line=>line.partes?.length?line.partes:[line]); + if (semCap.some(item=>(item.localFiles||[]).length>200)) + return message('Este item tem mais de 200 arquivos. Divida em dois itens.','error'); const initialCart=cartSnapshot(); busy = true; $('bPagar').disabled = true;