diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index c9a9293..6adb633 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -24,6 +24,7 @@ jobs: tests.test_pricing \ tests.test_coupons \ tests.test_grade_rules \ + tests.test_migrate \ tests.test_secrets -v sh -n infra/lock_dependencies.sh @@ -68,6 +69,12 @@ jobs: $COMPOSE up --build -d --wait --wait-timeout 600 $COMPOSE ps + # The database never blocks a rollback. Runs in db-init, the only job + # with the administrator connection; the whole test is rolled back, so + # nothing it inserts or alters remains. + - name: Rollback and migrations + run: $COMPOSE run --rm --no-deps db-init python -m tests.migrations_test + # Run inside the stack's own network. The runner is itself a container, so # ports published on the host's loopback are in a different namespace and # unreachable from here. SITE_HOST_HEADER keeps the Host the gateway and @@ -75,7 +82,7 @@ jobs: # one a developer exercises on localhost. - name: API and workflow regressions run: | - for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test grade_rules_test; do + for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test; do echo "--- $suite" $COMPOSE exec -T \ -e SITE_BASE_URL=http://site \ @@ -88,7 +95,7 @@ jobs: # the generator's geometry. The provider suites use a fake transport: they # prove the documented contract, not the integration. - name: Print-file geometry and provider adapters - run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats -v + run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_worker_drain -v - name: Runtime and retention regressions run: | diff --git a/app/api/artwork.py b/app/api/artwork.py index 4941a03..9db788a 100644 --- a/app/api/artwork.py +++ b/app/api/artwork.py @@ -10,7 +10,7 @@ from fastapi import APIRouter, Depends, HTTPException from ..core import db from .. import proof from ..artwork import submit_files -from ..core.auth import can, operator +from ..core.auth import can, can_any, operator from ..core.models import ArtworkSubmission, UploadStart from ..runtime import file_rows, operator_identity from .uploads import begin_upload, cancel_upload, complete_upload, part_url, upload_status @@ -38,15 +38,15 @@ def final_status(uid: UUID, user=Depends(operator)): # The parts of an upload its operator started: a final (produce) or the # photo of a signed pickup receipt (deliver, which includes produce). @router.post('/api/operator/uploads/{uid}/parts/{number}') -def final_part(uid: UUID, number: int, user=Depends(can('deliver'))): +def final_part(uid: UUID, number: int, user=Depends(can_any('deliver', 'assemble'))): return part_url(uid,number,session_id=operator_identity(user)) @router.post('/api/operator/uploads/{uid}/complete') -def final_complete(uid: UUID, user=Depends(can('deliver'))): +def final_complete(uid: UUID, user=Depends(can_any('deliver', 'assemble'))): return complete_upload(uid,session_id=operator_identity(user)) @router.delete('/api/operator/uploads/{uid}') -def final_cancel(uid: UUID, user=Depends(can('deliver'))): +def final_cancel(uid: UUID, user=Depends(can_any('deliver', 'assemble'))): return cancel_upload(uid,session_id=operator_identity(user)) @router.get('/api/operator/orders/{oid}/files') diff --git a/app/api/site_videos.py b/app/api/site_videos.py index c319a60..ad1ab50 100644 --- a/app/api/site_videos.py +++ b/app/api/site_videos.py @@ -22,7 +22,7 @@ CATALOG = { 'retirada': 'Retirada em Franca em 24 h', 'sala': 'A sala às 3 da manhã', } -VIDEO_MAX = 100 * 1024 * 1024 +VIDEO_MAX = 500 * 1024 * 1024 CAPTIONS_MAX = 1024 * 1024 @@ -46,7 +46,7 @@ def _kind(upload): return 'video/webm', b'\x1a\x45\xdf\xa3', 0 if name.endswith('.vtt') and upload['size'] <= CAPTIONS_MAX: return 'text/vtt', b'WEBVTT', 0 - raise HTTPException(422, 'Use MP4/WebM de até 100 MB ou legenda VTT de até 1 MB.') + raise HTTPException(422, 'Use MP4/WebM de até 500 MB ou legenda VTT de até 1 MB.') def _checked_upload(c, uid, identity, expected): diff --git a/app/api/stamps.py b/app/api/stamps.py new file mode 100644 index 0000000..712ea9c --- /dev/null +++ b/app/api/stamps.py @@ -0,0 +1,71 @@ +"""The montador's stamp sizes and its invoiced orders (Fase 2, front 7).""" +import hashlib +import json +from uuid import uuid4 + +from fastapi import APIRouter, Depends, HTTPException, Request +from psycopg.types.json import Jsonb + +from .. import payments, quote_review +from ..core import db +from ..core.auth import audit, can +from ..core.models import Freight, MontadorOrder, QuoteRequest, StampSizeTable, UploadStart +from ..runtime import operator_identity +from .uploads import begin_upload + +router = APIRouter() + + +@router.get('/api/operator/stamp-sizes') +def stamp_sizes(user=Depends(can('assemble'))): + with db.connect() as c: + rows = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall() + return {'sizes': rows} + + +@router.post('/api/operator/stamp-sizes') +def save_stamp_sizes(body: StampSizeTable, user=Depends(can('manage'))): + with db.connect() as c: + c.execute('DELETE FROM dtf_local.stamp_sizes') + c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm,updated_by) VALUES(%s,%s,%s)', + [(row.letter, row.width_cm, user) for row in body.sizes]) + audit('stamp_sizes_changed', operator=user, sizes=len(body.sizes)) + return {'ok': True} + + +@router.post('/api/operator/montador/uploads') +def montador_upload(body: UploadStart, user=Depends(can('assemble'))): + if not body.name.lower().endswith('.png'): + raise HTTPException(422, 'A estampa precisa ser um PNG.') + return begin_upload(body, session_id=operator_identity(user)) + + +@router.post('/api/operator/montador/orders') +def montador_order(body: MontadorOrder, request: Request, user=Depends(can('assemble'))): + """The order a montador sheet becomes, already invoiced (front 7a.2b): + typed customer, pickup, the Site's table price, and held out of Tiny until + Dropstar decides how it is invoiced there.""" + origin = 'dropflow' if request.state.operator['role'] == 'expedicao' else 'atendimento' + draft = QuoteRequest(request_key=body.request_key, customer=body.customer, items=body.items, + freight=Freight(service='pickup')).model_dump(mode='json', exclude={'request_key'}) + draft['montador'] = True + digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest() + owner = operator_identity(user) + with db.connect() as c: + c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft) + VALUES(%s,%s,%s,%s,%s) ON CONFLICT(owner,request_key) DO NOTHING''', + (uuid4(), owner, body.request_key, digest, Jsonb(draft))) + quote = c.execute('SELECT * FROM dtf_local.quotes WHERE owner=%s AND request_key=%s FOR UPDATE', + (owner, body.request_key)).fetchone() + if quote['request_hash'] != digest: + raise HTTPException(409, 'A montagem mudou durante o envio. Tente de novo.') + if not quote['approved']: + quote_review.approve(c, quote, body.items, user) + quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (quote['id'],)).fetchone() + receipt = {'provider': payments.MANUAL_PROVIDER, 'method': payments.INVOICED_METHOD, 'note': '', + 'status': 'paid', 'total_cents': quote['approved']['total_cents'], 'operator': user} + order, created = payments.create_order(c, quote, receipt, origin) + if not created: + raise HTTPException(409, f"Esta montagem já virou o pedido #{order['number']}.") + audit('montador_order_created', order=str(order['id']), origin=origin, operator=user) + return order diff --git a/app/api/users.py b/app/api/users.py index 16eb4d0..e0c3b93 100644 --- a/app/api/users.py +++ b/app/api/users.py @@ -26,7 +26,7 @@ class UserIn(StrictModel): # The profiles an administrator may give; superadmin only comes from the console. name: str = Field(min_length=1, max_length=80) email: str = Field(min_length=3, max_length=254) - role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro'] + role: Literal['admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao'] password: str | None = Field(default=None, min_length=8, max_length=128) active: bool = True # No longer used: an operator's machine is the one chosen after signing in diff --git a/app/app.py b/app/app.py index fe00542..31e8b87 100644 --- a/app/app.py +++ b/app/app.py @@ -13,7 +13,7 @@ from starlette.middleware.trustedhost import TrustedHostMiddleware from .core import db from .core.auth import audit, client_ip from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage -from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, uploads, users +from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, stamps, uploads, users @asynccontextmanager @@ -45,5 +45,5 @@ async def safe_headers(request, call_next): # Order is not significant: no two routers declare the same path. -for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, site_admin, reviews, machine_log): +for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, site_admin, reviews, machine_log, stamps): app.include_router(module.router) diff --git a/app/bootstrap.py b/app/bootstrap.py index 4150df2..f353be7 100644 --- a/app/bootstrap.py +++ b/app/bootstrap.py @@ -4,6 +4,7 @@ from pathlib import Path from urllib.parse import urlparse import psycopg from psycopg import sql +from . import migrate from .core.secrets import load as load_secret_files from .operators import seed_from_environment @@ -41,6 +42,7 @@ def main(): c.execute(sql.SQL('ALTER ROLE {} NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD {}').format( sql.Identifier(role), sql.Literal(password))) c.execute(Path(__file__).with_name('schema.sql').read_text()) + applied = migrate.apply(c) c.execute(sql.SQL('REVOKE CREATE ON SCHEMA public FROM PUBLIC')) c.execute(sql.SQL('GRANT CONNECT ON DATABASE {} TO {}').format(sql.Identifier(database),sql.Identifier(role))) c.execute(sql.SQL('GRANT USAGE ON SCHEMA dtf_local TO {}').format(sql.Identifier(role))) @@ -54,6 +56,8 @@ def main(): # reverted by a stale environment variable on the next deploy. seeded = seed_from_environment(c) print('Local schema migrated; runtime role has DML only.') + if applied: + print(f'Schema migrations applied: {", ".join(applied)}') if seeded: print(f'Seeded operator account {seeded} from OPERATOR_EMAIL.') diff --git a/app/core/auth.py b/app/core/auth.py index 032b297..5ce4c6c 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -125,7 +125,7 @@ def login_failed(email): # backup, the Tiny log): the others see there only what is on and off. # The designer approves and refuses artwork and asks for corrections, on every # order whatever its machine. Which cards each profile moves is MOVES. -ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro') +ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao') CAPABILITIES = { 'view': set(ROLES), 'produce': {'superadmin', 'admin', 'gestao', 'designer'}, @@ -155,6 +155,9 @@ CAPABILITIES = { # The photo or video of the printed sheet in Revisão (Fase 2, front 2): who # releases to Finalizado, and Gestão, which may stand in for them. 'inspect': {'superadmin', 'admin', 'gestao', 'revisor'}, + # Montar folha (Fase 2, front 7): the new Expedição profile and the seller, + # who gets this one action although otherwise view-only (D-30). + 'assemble': {'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'}, } # Who moves which card (Dropstar's flow, 2026-10-23, and their rules of @@ -238,4 +241,15 @@ def can(capability): return check +def can_any(*capabilities): + """A dependency that lets through a profile with any of these capabilities, + and returns the operator's e-mail, as the routes record it.""" + def check(request: Request): + account = signed_in(request) + if not any(account['role'] in CAPABILITIES[capability] for capability in capabilities): + raise HTTPException(403, 'Seu perfil não permite esta ação.') + return account['email'] + return check + + operator = can('view') diff --git a/app/core/db.py b/app/core/db.py index 46ff4b7..ce049e0 100644 --- a/app/core/db.py +++ b/app/core/db.py @@ -3,6 +3,8 @@ from pathlib import Path import psycopg from psycopg.rows import dict_row +from .. import migrate + def connect(): # Production passes credentials as discrete libpq fields. This avoids # treating characters in a generated password as URL syntax. Local and @@ -21,3 +23,4 @@ def initialize(): with connect() as c: # The schema lives at the package root, one level up from core/. c.execute((Path(__file__).resolve().parent.parent / 'schema.sql').read_text()) + migrate.apply(c) diff --git a/app/core/models.py b/app/core/models.py index d1a2624..e534eb0 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -288,6 +288,19 @@ class QuoteRequest(StrictModel): raise ValueError('The delivery address CEP must be the CEP freight was quoted for') return self +class MontadorOrder(StrictModel): + """What the montador sends (front 7a.2b): the typed customer, pickup only + and loose artwork only; the server prices and approves it as a quote.""" + request_key: UUID + customer: Customer + items: list[Item] = Field(min_length=1, max_length=30) + + @model_validator(mode='after') + def loose_art_only(self): + if any(item.mode != 'avulsa' for item in self.items): + raise ValueError('O montador só monta artes avulsas.') + return self + class Review(StrictModel): items: list[Item] = Field(min_length=1, max_length=30) @@ -499,3 +512,19 @@ class ArtworkSubmission(StrictModel): version: int = Field(ge=0, strict=True) files: list[FileReference] = Field(min_length=1, max_length=60) note: str = Field(min_length=1, max_length=1000) + +class StampSize(StrictModel): + """One row of the montador's size table (Fase 2, front 7).""" + letter: str = Field(pattern=r'^[A-Z]{1,2}$') + width_cm: Decimal = Field(gt=0, le=56, decimal_places=2) + +class StampSizeTable(StrictModel): + """The whole table, replaced in one go by Gestão.""" + sizes: list[StampSize] = Field(min_length=1, max_length=26) + + @model_validator(mode='after') + def letters_unique(self): + letters = [row.letter for row in self.sizes] + if len(letters) != len(set(letters)): + raise ValueError('Cada tamanho tem uma letra própria.') + return self diff --git a/app/migrate.py b/app/migrate.py new file mode 100644 index 0000000..f537acf --- /dev/null +++ b/app/migrate.py @@ -0,0 +1,34 @@ +"""Timestamped schema migrations, applied once by the database initializer. + +schema.sql is the frozen baseline and runs on every start; a change after it is +a file in app/migrations/, named YYYYMMDDHHMM_slug.sql. The name is the +migration's identity and is recorded in dtf_local.migrations, so a deploy never +applies one twice and an older image skips names it does not know. +""" +import re +from pathlib import Path + +MIGRATIONS = Path(__file__).resolve().with_name('migrations') +LOCK = 804209 +NAME = re.compile(r'\d{12}_[a-z0-9-]+\.sql') + + +def apply(c, directory=MIGRATIONS) -> list[str]: + """Run, in name order, every migration file not yet recorded in + dtf_local.migrations, each recorded in the same transaction. A name in + the table that has no file (written by a newer image) is ignored, so an + older image still starts.""" + c.execute('SELECT pg_advisory_xact_lock(%s)', (LOCK,)) + files = {} + for path in Path(directory).iterdir(): + if not path.is_file() or not NAME.fullmatch(path.name): + raise ValueError(f'Unexpected file in {directory}: {path.name}') + files[path.name] = path + applied = [] + for name in sorted(files): + if c.execute('SELECT 1 FROM dtf_local.migrations WHERE name=%s', (name,)).fetchone(): + continue + c.execute(files[name].read_text()) + c.execute('INSERT INTO dtf_local.migrations(name) VALUES(%s)', (name,)) + applied.append(name) + return applied diff --git a/app/migrations/202611091607_checks-current-lists.sql b/app/migrations/202611091607_checks-current-lists.sql new file mode 100644 index 0000000..463169b --- /dev/null +++ b/app/migrations/202611091607_checks-current-lists.sql @@ -0,0 +1,14 @@ +-- The current lists of the three CHECK constraints whose values have grown +-- over time, applied once to every database, including one whose copy is older +-- (an image before front 7a lacks 'expedicao', for example). From now on, +-- widening a list is a new migration that drops and adds that one constraint. +ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role; +ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role + CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao')); + +ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check; +ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check + CHECK(kind IN ('reset','code','account','notice','order','alert','test')); + +ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check; +ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento')); diff --git a/app/migrations/202611092000_grade-rules.sql b/app/migrations/202611092000_grade-rules.sql new file mode 100644 index 0000000..6efacae --- /dev/null +++ b/app/migrations/202611092000_grade-rules.sql @@ -0,0 +1,7 @@ +-- Front 8.5: what the art grade decides, set in the Kanban's Site tab. No row +-- means no rule, and nothing changes; each action has at most one threshold. +CREATE TABLE IF NOT EXISTS dtf_local.grade_rules ( + action text PRIMARY KEY CHECK (action IN ('aviso','tratamento')), + below integer NOT NULL CHECK (below BETWEEN 1 AND 100), + updated_by text NOT NULL, updated_at timestamptz NOT NULL DEFAULT now() +); diff --git a/app/payments.py b/app/payments.py index 0fa1aec..ff182c3 100644 --- a/app/payments.py +++ b/app/payments.py @@ -60,12 +60,19 @@ def is_test(order): # (Dropstar's rule D-35, 2026-10-26; the user's answers of 2026-10-27). MANUAL_PROVIDER = 'manual' OUTSIDE_METHODS = ('pix', 'card', 'cash', 'credit') +# A montador order is invoiced, not paid at the counter: it is not one of the +# Cotações "registrar" methods. +INVOICED_METHOD = 'faturado' def in_tiny(order): """Whether the order goes to Tiny: every order but a test or a proof card (app/proof.py), which is no sale. A Dropflow order goes in its own revenue category (app/tiny.py, CATEGORIES).""" + if (order.get('payment') or {}).get('method') == INVOICED_METHOD: + # Held until Dropstar decides how invoiced montador orders reach Tiny + # (asked 2026-11-09). + return False return not is_test(order) and not order.get('parent_id') @@ -146,7 +153,10 @@ def create_order(c, quote, payment, origin): proof.create_child(c, order) if is_test(order): return order, True - mail.order_paid(c, order, PUBLIC_ORIGIN) + # An invoiced montador order was not paid: no "pedido pago" e-mail until + # Dropstar says what the customer hears (asked 2026-11-09). + if payment.get('method') != INVOICED_METHOD: + mail.order_paid(c, order, PUBLIC_ORIGIN) if not in_tiny(order): return order, True # How it was paid, for the order's payment in Tiny. diff --git a/app/quote_review.py b/app/quote_review.py index 76369ff..5d47771 100644 --- a/app/quote_review.py +++ b/app/quote_review.py @@ -108,6 +108,10 @@ def approve(c, row, items, reviewer): offer = catalog.current(c)['tratamento'] offered = bool(offer['enabled'] and offer['unit_cents'] > 0) flags = grade_rules.triggered(grade_rules.current_rules(c), priced, offered) + # A montador sheet (front 7a) is assembled by the team from Estampas/, not + # sent by a customer: the treatment rule does not apply to it. + if draft.get('montador'): + flags.pop('tratamento', None) if 'tratamento' in flags and not draft.get('treatment'): raise HTTPException(422, grade_rules.treatment_message(flags['tratamento'])) items_total = sum(i['total_cents'] for i in priced) diff --git a/app/schema.sql b/app/schema.sql index f31085b..b4b4cd7 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -284,11 +284,18 @@ CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names ( -- from the console); administrators manage users and machines; gestão runs -- the business; designers approve artwork; operadores print; revisores check -- the printed sheet and are the only ones to release it to Finalizado; --- vendedores only read. +-- vendedores only read; expedição assembles sheets in the Kanban's montador. ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin'; -ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role; -ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role - CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro')); +-- Created once, and widened only by a migration: re-adding it on every start +-- would let an older image narrow the list and refuse rows written under a +-- later one, and the database would not finish starting. +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='operators_role' + AND conrelid='dtf_local.operators'::regclass) THEN + ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role + CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao')); + END IF; +END $$; -- Print machines and which products each prints. An order gets its machine -- when someone pulls it into Imprimindo; no machine is assigned at payment. -- limit_metres remains the load shown for a machine. @@ -410,11 +417,16 @@ UPDATE dtf_local.accounts a SET email_verified=true WHERE NOT a.email_verified A -- E-mail kinds: a password-recovery link, a code, the notice that an account -- already exists, the notice of a changed e-mail, a customer's paid order, -- the team's alerts and a test. --- Defined once, here: the schema runs on every start, and an earlier, narrower --- copy would refuse the rows of the kinds added after it. -ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check; -ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check - CHECK(kind IN ('reset','code','account','notice','order','alert','test')); +-- Created once, and widened only by a migration: the schema runs on every +-- start, and re-adding an earlier, narrower copy would refuse the rows of the +-- kinds added after it. +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='mail_queue_kind_check' + AND conrelid='dtf_local.mail_queue'::regclass) THEN + ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check + CHECK(kind IN ('reset','code','account','notice','order','alert','test')); + END IF; +END $$; -- The print proof (Dropstar, 2026-10-21): an order above 10 m, or one whose -- customer asked for a proof at checkout, prints 20 cm first; the room marks @@ -452,8 +464,13 @@ WHERE o.contact_since IS NOT NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.contac ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS origin text; UPDATE dtf_local.orders SET origin='site' WHERE origin IS NULL; ALTER TABLE dtf_local.orders ALTER COLUMN origin SET NOT NULL; -ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check; -ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento')); +-- Created once, and widened only by a migration; never re-added on start. +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='orders_origin_check' + AND conrelid='dtf_local.orders'::regclass) THEN + ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento')); + END IF; +END $$; -- Rework (Dropstar's rules D-02 to D-04, 2026-10-26; the user's answers of -- 2026-10-27). Gestão opens it with its cause, and the cause never changes @@ -618,6 +635,15 @@ CREATE TABLE IF NOT EXISTS dtf_local.product_prices ( ); CREATE INDEX IF NOT EXISTS product_prices_current ON dtf_local.product_prices(product, starts_at DESC); +-- Front 7a: the stamp sizes of the Kanban's montador; Gestão edits them. +CREATE TABLE IF NOT EXISTS dtf_local.stamp_sizes ( + letter text PRIMARY KEY CHECK (letter ~ '^[A-Z]{1,2}$'), + width_cm numeric(5,2) NOT NULL CHECK (width_cm > 0 AND width_cm <= 56), + updated_by text NOT NULL DEFAULT 'sistema', + updated_at timestamptz NOT NULL DEFAULT now() +); +INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES ('A',20),('B',24),('C',27),('D',30) +ON CONFLICT (letter) DO NOTHING; -- Front 8.2: a price may also have bands by the order's total metres of that -- product: base price, then "from 5 m R$ Y", "from 20 m R$ Z" (jsonb list of -- {"from_metres": "5", "unit_cents": 1990}, strictly increasing, at most 5). @@ -644,11 +670,3 @@ CREATE TABLE IF NOT EXISTS dtf_local.coupons ( created_at timestamptz NOT NULL DEFAULT now() ); CREATE UNIQUE INDEX IF NOT EXISTS coupons_live_code ON dtf_local.coupons(code) WHERE deleted_at IS NULL; - --- Front 8.5: what the art grade decides, set in the Kanban's Site tab. No row --- means no rule, and nothing changes; each action has at most one threshold. -CREATE TABLE IF NOT EXISTS dtf_local.grade_rules ( - action text PRIMARY KEY CHECK (action IN ('aviso','tratamento')), - below integer NOT NULL CHECK (below BETWEEN 1 AND 100), - updated_by text NOT NULL, updated_at timestamptz NOT NULL DEFAULT now() -); diff --git a/app/worker.py b/app/worker.py index df9f78d..d72cbf9 100644 --- a/app/worker.py +++ b/app/worker.py @@ -53,10 +53,13 @@ def cleanup(): c.execute("DELETE FROM dtf_local.security_events WHERE created_at 60: cleanup() # Approved quotes unpaid for 24 h expire on their own (front 9). diff --git a/deploy/portainer.env.example b/deploy/portainer.env.example index 8a13afd..74814ee 100644 --- a/deploy/portainer.env.example +++ b/deploy/portainer.env.example @@ -15,6 +15,8 @@ PUBLIC_HOST=dtf.example.invalid KANBAN_HOST=kanban-dtf.example.invalid SITE_PORT=8080 KANBAN_PORT=8081 +# API processes: 2 by default; 1 runs one process, as before. API only. +API_WORKERS=2 R2_ENDPOINT=TBD R2_PUBLIC_ENDPOINT=TBD diff --git a/docker-compose.yml b/docker-compose.yml index cb57a23..f64fdf8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -213,13 +213,20 @@ services: api: image: ${API_IMAGE:-gitea.blyzer.com.br/blyzer/dtf-api}:${IMAGE_TAG:-latest} - environment: *app-environment + environment: + <<: *app-environment + # Two uvicorn processes by default (Critical Corrections item 2, step 1): + # a slow 150 MB PDF check no longer holds every request in the only one. + # API_WORKERS=1 restores one process without a new image. + WEB_CONCURRENCY: "${API_WORKERS:-2}" networks: [backend, egress] read_only: true # Swarm ignores the short `tmpfs:` key: a read-only container then has no # writable /tmp at all. The long volume syntax is what a stack honours. + # 512 MiB, not 256: with two processes each may write a 150 MB PDF from the + # grade check at the same time. volumes: - - {type: tmpfs, target: /tmp, tmpfs: {size: 268435456}} + - {type: tmpfs, target: /tmp, tmpfs: {size: 536870912}} healthcheck: test: [CMD-SHELL, 'python -c "import os,urllib.request; r=urllib.request.Request(\"http://localhost:8000/health\",headers={\"Host\":os.environ[\"PUBLIC_HOST\"]}); urllib.request.urlopen(r,timeout=3)"'] interval: 15s diff --git a/docs/LOCAL_SETUP.md b/docs/LOCAL_SETUP.md index bb88ce1..d1194c2 100644 --- a/docs/LOCAL_SETUP.md +++ b/docs/LOCAL_SETUP.md @@ -238,6 +238,24 @@ storage permits; otherwise reselect them. Saved quote IDs also survive reloads. Clearing cookies loses a guest session, while registered customers can sign in again. The operator can still inspect order records. +## Schema changes + +`app/schema.sql` is the frozen baseline: every start runs it, and nothing new +is added to it. A schema change is a new file in `app/migrations/`, named with +a timestamp and a short slug, `YYYYMMDDHHMM_description.sql` (for example +`202611091607_checks-current-lists.sql`). `app/migrate.py` runs every file not +yet recorded in `dtf_local.migrations`, in name order, each recorded in the +same transaction and under an advisory lock; `app/bootstrap.py` and +`app/core/db.py` call it right after the schema and before the grants, so a +table a migration creates is granted to the runtime role. Never edit an applied +migration: add a new one instead. Any file in that folder whose name does not +match `^\d{12}_[a-z0-9-]+\.sql$` stops the start, so a typo is never skipped. + +Widening a CHECK constraint is a DROP + ADD in a migration, with the full list; +`app/schema.sql` only creates the three initial ones when missing. A rollback +to an image at or after this change is safe: an older image ignores migration +names it does not know. + ## Print files Every paid order queues one print-file job per item. The worker renders a PDF diff --git a/docs/PORTAINER.md b/docs/PORTAINER.md index 893fe4a..4f202bb 100644 --- a/docs/PORTAINER.md +++ b/docs/PORTAINER.md @@ -173,7 +173,10 @@ affect stored data or retention. In the Portainer stack variables, change `IMAGE_TAG` from `latest` to the full SHA of the last known-good Gitea commit and redeploy. This rolls back Site, API, Kanban, and worker code; it does not undo database migrations or restore data. -After recovery and a corrected release, return `IMAGE_TAG` to `latest`. +Rolling back to an image from before the timestamped migrations can still fail +if the data uses newer values; images from that change on ignore migration +names they do not know, so a rollback is safe. After recovery and a corrected +release, return `IMAGE_TAG` to `latest`. ## 6. Before opening to customers @@ -223,6 +226,15 @@ If a service is refused, the contract uses other codes: set `CORREIOS_COD_PAC` or `CORREIOS_COD_SEDEX`. Correios price by the box, so `JADLOG_CAIXA_CM` and the package weights must be set (they already are for Jadlog). +## 9. API processes + +`API_WORKERS` is how many uvicorn processes the API container runs (default 2; +`1` runs one process, as before). More than one keeps a slow checkout, such as +a PDF of up to 150 MB being checked, from holding every other request in the +only process; the API's `/tmp` is sized for two such checks at once. It applies +to the API only, never to the worker. Set it in the stack's environment and +redeploy. + ## Current blocker This is the final deployment shape, but it is not authorized for production diff --git a/tests/migrations_test.py b/tests/migrations_test.py new file mode 100644 index 0000000..8a3af12 --- /dev/null +++ b/tests/migrations_test.py @@ -0,0 +1,59 @@ +"""Rollback safety on the real database: an image at or after the timestamped +migrations starts on data written under a newer, wider CHECK list. + +Uses the database administrator's connection, so it runs in the db-init +container: docker compose -f compose.local.yaml run --rm --no-deps db-init \ +python -m tests.migrations_test + +Everything happens in one transaction that is rolled back at the end, so the +widening, its migration record and the test operator never remain. +""" +import tempfile +from pathlib import Path +from uuid import uuid4 + +from app import migrate +from app.bootstrap import admin_connect + +SCHEMA = Path(__file__).resolve().parent.parent.joinpath('app', 'schema.sql') +WIDEN = """ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role; +ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role + CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao','tester')); +""" + + +def check(condition, message): + if not condition: + raise AssertionError(message) + print('PASS:', message) + + +def main(): + c = admin_connect() + try: + c.execute(SCHEMA.read_text()) + migrated = migrate.apply(c) + check(True, f'the real schema and migrations run ({", ".join(migrated) or "none pending"})') + with tempfile.TemporaryDirectory() as folder: + name = '209901010000_widen-operators-role.sql' + Path(folder, name).write_text(WIDEN) + applied = migrate.apply(c, folder) + check(applied == [name], 'a temporary migration widens operators_role') + email = f'tester-{uuid4().hex[:8]}@example.test' + c.execute("INSERT INTO dtf_local.operators(id,email,password_hash,role) VALUES(%s,%s,'test','tester')", + (uuid4(), email)) + check(True, 'an operator with the newer role is accepted') + # The rollback rehearsal: an older image at or after the migrations + # change runs its schema.sql and its own folder, with no later file, + # and must start on the current data without narrowing the list. + c.execute(SCHEMA.read_text()) + migrate.apply(c) + check(True, 'the older image starts and leaves the widened list alone') + finally: + c.rollback() + c.close() + print('migrations_test OK') + + +if __name__ == '__main__': + main() diff --git a/tests/stamps_test.py b/tests/stamps_test.py new file mode 100644 index 0000000..0eb41f3 --- /dev/null +++ b/tests/stamps_test.py @@ -0,0 +1,150 @@ +"""The montador: stamp sizes, and the invoiced order a sheet becomes. + +Run against the local stack: python -m tests.stamps_test +""" +import secrets +import time +from pathlib import Path +from urllib.request import Request, urlopen +from uuid import UUID, uuid4 + +from app.core import db +from app.runtime import operator_identity +from tests.smoke_test import Client + +PASSWORD = 'senha-de-teste-123' +PNG = (Path(__file__).resolve().parent / 'fixtures' / 'final-300.png').read_bytes() + + +def signed_in(email, password=PASSWORD): + client = Client() + client.call('/session') + client.call('/operator/login', {'email': email, 'password': password}) + return client + + +def upload_stamp(client, name='LOCAL-ESTAMP.png'): + start = client.call('/operator/montador/uploads', {'name': name, 'size': len(PNG)}) + uid = start['id'] + url = client.call(f'/operator/uploads/{uid}/parts/1', {})['url'] + with urlopen(Request(url, data=PNG, method='PUT'), timeout=30) as response: + assert response.status == 200 + client.call(f'/operator/uploads/{uid}/complete', {}) + deadline = time.monotonic() + 150 + while client.call(f'/operator/uploads/{uid}')['scan_state'] != 'clean': + assert time.monotonic() < deadline, 'stamp scan did not finish' + time.sleep(0.5) + return uid + + +def montador_item(uid, mode='avulsa'): + """One source, 3 copies in a row: a valid Item for the montador route.""" + sheet = mode == 'file' + height = 1.75 if sheet else 1.25 + return { + 'mode': mode, 'metres': height / 100, 'grade': 100, 'uploads': [uid], + 'production': { + 'version': 3, 'film_width_cm': 57, 'height_cm': height, + 'sources': [{'upload_id': uid, 'kind': 'sheet' if sheet else 'artwork', + 'width_cm': 0.5, 'length_cm': 0.25, 'copies': 3, + 'rotation_degrees': 0, 'mirrored': False, 'measurement': 'file'}], + 'placements': [{'source_index': 0, 'copy_index': copy, + 'x_cm': 0 if sheet else 0.5 + copy * 1.0, 'y_cm': 0.5 + copy * 0.5 if sheet else 0.5, + 'width_cm': 0.5, 'length_cm': 0.25, + 'rotation_degrees': 0, 'mirrored': False} for copy in range(3)]}, + 'quality_status': 'ok', 'quality_acknowledged': False, 'residue_accepted': 0} + + +def run(): + tag = secrets.token_hex(3) + su = Client() + su.call('/session') + 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')} + 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']) + made_orders, made_quotes = [], [] + 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']) + me = shipping.call('/operator/me') + assert me['role'] == 'expedicao' and me['can'] == ['assemble', '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}]}) + 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 + # A repeated letter and a width out of range are refused. + manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 20}, + {'letter': 'A', 'width_cm': 24}]}, + expected=422) + manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 0}]}, + expected=422) + manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 57}]}, + expected=422) + # Expedição only reads them; saving stays with Gestão. + shipping.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 20}]}, + expected=403) + 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. + 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 + with db.connect() as c: + assert c.execute('SELECT 1 FROM dtf_local.print_files WHERE order_id=%s', + (UUID(order['id']),)).fetchone() + assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s', + (f"{order['id']}:paid:tiny",)).fetchone() + # 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. + 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, + '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') + finally: + with db.connect() as c: + 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,)) + c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (oid,)) + c.execute('DELETE FROM dtf_local.contact_waits WHERE order_id=%s', (oid,)) + 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.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',)) + + +if __name__ == '__main__': + run() diff --git a/tests/test_migrate.py b/tests/test_migrate.py new file mode 100644 index 0000000..63f60cc --- /dev/null +++ b/tests/test_migrate.py @@ -0,0 +1,76 @@ +"""The migration runner: file names, order and recorded names. + +Run from the repository root: python3 -m unittest tests.test_migrate +""" +import tempfile +import unittest +from pathlib import Path + +from app import migrate + + +class Cursor: + def __init__(self, row=None): + self.row = row + + def fetchone(self): + return self.row + + +class FakeConnection: + """Records the SQL it is asked to run and the names already recorded.""" + + def __init__(self, recorded=()): + self.recorded = set(recorded) + self.calls = [] + + def execute(self, query, params=()): + self.calls.append((query, params)) + if query.startswith('SELECT 1 FROM dtf_local.migrations'): + return Cursor((1,) if params[0] in self.recorded else None) + if query.startswith('INSERT INTO dtf_local.migrations'): + self.recorded.add(params[0]) + return Cursor() + + @property + def queries(self): + return [query for query, _ in self.calls] + + +class MigrateTest(unittest.TestCase): + def folder(self, names): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + for name in names: + Path(temp.name, name).write_text(f'-- {name}\n') + return temp.name + + def test_runs_new_files_in_name_order(self): + directory = self.folder(['202611091202_b.sql', '202611091201_a.sql']) + c = FakeConnection() + self.assertEqual(migrate.apply(c, directory), ['202611091201_a.sql', '202611091202_b.sql']) + self.assertEqual(c.queries[0], 'SELECT pg_advisory_xact_lock(%s)') + ran = [query for query in c.queries if query.startswith('-- ')] + self.assertEqual(ran, ['-- 202611091201_a.sql\n', '-- 202611091202_b.sql\n']) + + def test_recorded_files_are_skipped(self): + directory = self.folder(['202611091201_a.sql', '202611091202_b.sql']) + c = FakeConnection({'202611091201_a.sql'}) + self.assertEqual(migrate.apply(c, directory), ['202611091202_b.sql']) + self.assertNotIn('-- 202611091201_a.sql\n', c.queries) + + def test_a_recorded_name_without_a_file_is_ignored(self): + directory = self.folder(['202611091201_a.sql']) + c = FakeConnection({'209901010000_from-a-newer-image.sql'}) + self.assertEqual(migrate.apply(c, directory), ['202611091201_a.sql']) + + def test_an_unexpected_file_raises(self): + # A typo must stop the start, never be skipped as if it were applied. + for name in ('notes.txt', '20261109120_short.sql', '202611091201_Two-words.sql'): + with self.subTest(name=name): + with self.assertRaises(ValueError): + migrate.apply(FakeConnection(), self.folder([name])) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_moves.py b/tests/test_moves.py index 4762216..f2cc637 100644 --- a/tests/test_moves.py +++ b/tests/test_moves.py @@ -1,7 +1,10 @@ """Who moves which card on the Kanban: Dropstar's flow of 2026-10-23.""" import unittest +from unittest import mock -from app.core.auth import ROLES, may_move, may_reorder +from app import payments +from app.core import auth +from app.core.auth import CAPABILITIES, ROLES, may_move, may_reorder from app.runtime import BACK, STATES, TRANSITIONS @@ -41,6 +44,17 @@ class MovesTest(unittest.TestCase): self.assertTrue(may_move('gestao', 'fin', 'rev', back=True)) self.assertFalse(may_move('vendedor', 'tra', 'rec', back=True)) + def test_expedicao_moves_nothing(self): + # The new shipping profile assembles sheets (Fase 2, front 7) and reads + # the board; it moves no card and orders no column. + self.assertIn('expedicao', ROLES) + self.assertEqual(moves('expedicao'), set()) + self.assertEqual([s for s in STATES if may_reorder('expedicao', s)], []) + + def test_the_montador_is_open_to_exactly_five_profiles(self): + self.assertEqual(CAPABILITIES['assemble'], + {'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'}) + 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']) @@ -49,5 +63,29 @@ class MovesTest(unittest.TestCase): self.assertTrue(all(may_reorder('gestao', s) for s in STATES)) +class CanAnyTest(unittest.TestCase): + def test_a_profile_with_any_of_the_capabilities_gets_through(self): + # The montador's stamp uploads: deliver or assemble (Fase 2, front 7). + for role, allowed in (('operador', True), ('expedicao', True), ('vendedor', True), + ('designer', True), ('financeiro', False)): + with mock.patch.object(auth, 'signed_in', + return_value={'role': role, 'email': role + '@example.test'}): + route = auth.can_any('deliver', 'assemble') + if allowed: + self.assertEqual(route(None), role + '@example.test') + else: + with self.assertRaises(auth.HTTPException): + route(None) + + +class InvoicedOrderTest(unittest.TestCase): + def test_an_invoiced_montador_order_is_held_out_of_tiny(self): + self.assertEqual(payments.INVOICED_METHOD, 'faturado') + # It is not 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.assertTrue(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'pix'}})) + + if __name__ == '__main__': unittest.main() diff --git a/tests/test_schema.py b/tests/test_schema.py index 04a6893..051530f 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -8,13 +8,44 @@ import unittest from collections import Counter from pathlib import Path +ROOT = Path(__file__).resolve().parent.parent +CONSTRAINTS = ('operators_role', 'mail_queue_kind_check', 'orders_origin_check') + + +def check_lists(text): + """Each constraint's CHECK (column IN (...)) values, by constraint name.""" + found = {} + for name in CONSTRAINTS: + match = re.search(r'ADD CONSTRAINT\s+' + name + r'\s+CHECK\s*\([^()]*\bIN\s*\(([^)]*)\)', + text, re.I | re.S) + if match: + found[name] = tuple(value.strip().strip("'") for value in match.group(1).split(',')) + return found + class SchemaTest(unittest.TestCase): def test_each_constraint_is_added_once(self): - schema = Path(__file__).resolve().parent.parent.joinpath('app', 'schema.sql').read_text() + schema = ROOT.joinpath('app', 'schema.sql').read_text() added = Counter(re.findall(r'ADD CONSTRAINT\s+(\w+)', schema, re.I)) self.assertEqual([name for name, count in added.items() if count > 1], []) + def test_only_the_foreign_key_loop_drops_a_constraint(self): + # An image never lowers a CHECK on start. The FK loop rebuilds a + # foreign key only to add ON DELETE CASCADE, so it never narrows one. + schema = ROOT.joinpath('app', 'schema.sql').read_text() + loop = re.search(r'DO \$\$\nDECLARE r record;.*?\nEND \$\$;', schema, re.S) + self.assertIsNotNone(loop) + rest = schema[:loop.start()] + schema[loop.end():] + self.assertNotIn('DROP CONSTRAINT', rest) + + def test_the_first_migration_has_the_current_lists(self): + schema = ROOT.joinpath('app', 'schema.sql').read_text() + files = list(ROOT.joinpath('app', 'migrations').glob('*_checks-current-lists.sql')) + self.assertEqual(len(files), 1) + migration = files[0].read_text() + self.assertEqual(check_lists(schema), check_lists(migration)) + self.assertEqual(set(check_lists(schema)), set(CONSTRAINTS)) + if __name__ == '__main__': unittest.main() diff --git a/tests/test_worker_drain.py b/tests/test_worker_drain.py new file mode 100644 index 0000000..4dfef87 --- /dev/null +++ b/tests/test_worker_drain.py @@ -0,0 +1,27 @@ +"""The outbox worker drains a backlog instead of one job per second (item 9). + +Run from the repository root: python3 -m unittest tests.test_worker_drain -v. +The worker imports psycopg and boto3, so a host without the API image's +dependencies cannot import it; CI runs this in the api container. +""" +import unittest +from unittest import mock + +from app import worker + + +class WorkerDrainTest(unittest.TestCase): + def test_drain_stops_when_the_queue_is_empty(self): + with mock.patch.object(worker, 'tick', + side_effect=[True, True, True, False]) as tick: + worker.drain() + self.assertEqual(tick.call_count, 4) + + def test_drain_stops_at_the_limit(self): + with mock.patch.object(worker, 'tick', return_value=True) as tick: + worker.drain() + self.assertEqual(tick.call_count, 50) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/users_test.py b/tests/users_test.py index 5ee59a6..dfc6ed2 100644 --- a/tests/users_test.py +++ b/tests/users_test.py @@ -174,7 +174,7 @@ def run(): seller.call(f'/operator/orders/{textil_o}/contact', {'waiting': True, 'note': 'Ligar'}, expected=403) # The seller only views the board (D-30): no order registered by hand either. # The seller only views, but answers a proof card (Dropstar, 2026-11-03). - assert seller.call('/operator/me')['can'] == ['proof', 'view'] + assert seller.call('/operator/me')['can'] == ['assemble', 'proof', 'view'] seller.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=403) # Financeiro (Dropstar, 2026-10-30): the board, Pagamentos, Números and # Cotações, and cancels an order with its reason; moves nothing. diff --git a/web/index.html b/web/index.html index 308f662..71a0f50 100644 --- a/web/index.html +++ b/web/index.html @@ -1219,6 +1219,7 @@ h2 em{font-style:normal;color:var(--laranja)} + diff --git a/web/kanban-montador.js b/web/kanban-montador.js new file mode 100644 index 0000000..9ab4e73 --- /dev/null +++ b/web/kanban-montador.js @@ -0,0 +1,435 @@ +/* Kanban DTF: "Montar folha" (Fase 2, front 7). The stamps are the PNG files + in Estampas/ inside the folder chosen in Integrações; the sizes are the + table Gestão edits. The packing is the Site's own engine (web/packing.js). + Montar, which creates the card, is slice 2b. Uses the globals of kanban.js + and packing.js, loaded first. */ +const MONTAR_CODE=/^[A-Za-z0-9_-]{1,40}$/; +// The Site's ruler (web/site-config.js): the same numbers, copied there too. +const MONTAR_DPI_REFUSE=96, MONTAR_DPI_WARN=200; +const MONTAR_FILM_CM=57, MONTAR_GAP_CM=0.5; +const MONTAR={sizes:[],lines:[],seq:0,preview:null,timer:null,dirty:false,token:0, + layout:null,layoutTimer:null,layoutToken:0,layoutPending:false,creating:false,requestKey:null}; + +const montarFolderReady=()=>!!FOLDER.handle&&!!FOLDER.granted; +const montarDpi=found=>found.width/(found.widthCm/2.54); +const montarHeight=found=>found.widthCm*(found.height/found.width); +const montarSelected=()=>MONTAR.sizes.find(size=>size.letter===$('montar-size').value)||null; + +// Without the folder there is no Estampas/ to read: only the size table works. +function montarPaintFolder(){ + const ok=montarFolderReady(); + $('montar-nofolder').hidden=ok; + $('montar-setup').querySelector('.montar-add').hidden=!ok; + $('montar-preview').hidden=!ok; + $('montar-sheet').hidden=!ok; + $('montar-folder').textContent=ok?'Pasta “'+FOLDER.handle.name+'” · Estampas/':''; + if(!ok){montarDropPreview();$('montar-preview').replaceChildren();} +} +function montarFolderError(error){ + if(error&&['NotAllowedError','SecurityError'].includes(error.name)){ + say('Para ler as estampas, escolha a pasta dos pedidos em Integrações neste computador.',true); + return true; + } + return false; +} + +// -.png wins over .png; only PNG. +async function montarRead(code,size){ + const dir=await FOLDER.handle.getDirectoryHandle('Estampas',{create:true}); + for(const name of [code+'-'+size.letter+'.png',code+'.png']){ + let handle; + try{handle=await dir.getFileHandle(name);} + catch(e){if(e.name==='NotFoundError')continue;throw e;} + const file=await handle.getFile(),url=URL.createObjectURL(file); + try{const dim=await montarPicture(url);return {code,letter:size.letter,widthCm:Number(size.width_cm),file,name,url,width:dim.width,height:dim.height};} + catch(e){URL.revokeObjectURL(url);throw e;} + } + return null; +} +function montarPicture(url){ + return new Promise((ok,fail)=>{ + const img=new Image(); + img.onload=()=>ok({width:img.naturalWidth,height:img.naturalHeight}); + img.onerror=()=>fail(new Error('A estampa não pôde ser lida.')); + img.src=url; + }); +} + +function montarDropPreview(){ + if(MONTAR.preview)URL.revokeObjectURL(MONTAR.preview.url); + MONTAR.preview=null; +} +function montarPaintPreview(found){ + montarDropPreview(); + MONTAR.preview=found; + const words=node('span',undefined,'montar-stampinfo'); + words.append(node('b',found.code), + node('span',cm(found.widthCm)+' cm de largura · '+cm(montarHeight(found))+' cm de altura · '+Math.floor(montarDpi(found))+' DPI')); + const img=node('img');img.src=found.url;img.alt='Estampa '+found.code; + const wrap=node('div',undefined,'montar-stamp');wrap.append(img,words); + $('montar-preview').replaceChildren(wrap); +} +function montarPaintNotFound(){ + montarDropPreview(); + $('montar-preview').replaceChildren(node('p','Código não existe em Estampas/.','montar-missing')); +} +function montarPaintHint(){ + montarDropPreview(); + $('montar-preview').replaceChildren(node('p','Digite o código e escolha o tamanho para ver a estampa.','montar-hint')); +} + +async function montarPreview(){ + const token=++MONTAR.token; + const code=$('montar-code').value.trim(),size=montarSelected(); + if(!montarFolderReady())return; + if(!code){montarPaintHint();return;} + if(!MONTAR_CODE.test(code)||!size){montarDropPreview();$('montar-preview').replaceChildren();return;} + let found; + try{found=await montarRead(code,size);} + catch(e){if(token===MONTAR.token&&!montarFolderError(e))say(e.message,true);return;} + if(token!==MONTAR.token){if(found)URL.revokeObjectURL(found.url);return;} + if(found)montarPaintPreview(found);else montarPaintNotFound(); +} +function montarQueuePreview(){ + clearTimeout(MONTAR.timer); + MONTAR.timer=setTimeout(()=>montarPreview().catch(e=>say(e.message,true)),250); +} + +function montarEstimate(){ + if(!MONTAR.lines.length)return 0; + let total=0; + for(const line of MONTAR.lines){ + const perRow=Math.max(1,Math.floor((MONTAR_FILM_CM-MONTAR_GAP_CM)/(line.widthCm+MONTAR_GAP_CM))); + const rows=Math.ceil(line.qty/perRow); + total+=rows*(line.heightCm+MONTAR_GAP_CM); + } + return (MONTAR_GAP_CM+total)/100; +} +function montarPaintTotals(){ + const done=MONTAR.layout&&!MONTAR.layoutPending; + $('montar-total').textContent=done + ? 'Montagem: '+metres(MONTAR.layout.altura/100) + : 'Estimativa: '+metres(montarEstimate())+(MONTAR.layoutPending?' · montando…':''); + $('montar-count').textContent=MONTAR.lines.length?plural(MONTAR.lines.length,'estampa','estampas'):''; + $('montar-clear').disabled=!MONTAR.lines.length; + $('montar-warning').hidden=!(MONTAR.lines.length>20||MONTAR.lines.some(line=>line.qty>200)); + montarPaintActions(); +} +// The line's image, loaded once and kept for the packing and the preview. +function montarStampImage(url){ + const img=new Image(); + const loading=new Promise(ok=>{img.onload=()=>ok(img);img.onerror=()=>ok(null);}); + img.src=url; + return {img,loading}; +} +// Every list change shows the estimate at once and schedules the real packing, +// 300 ms later; a run that finishes after a newer change is thrown away. +function montarChanged(){ + MONTAR.layoutToken+=1; + MONTAR.layout=null; + MONTAR.layoutPending=true; + MONTAR.requestKey=null; + montarPaintLines(); + if(!MONTAR.lines.length)montarDrawPreview(null); + clearTimeout(MONTAR.layoutTimer); + MONTAR.layoutTimer=setTimeout(()=>montarLayout(MONTAR.layoutToken).catch(e=>say(e.message,true)),300); +} +async function montarLayout(token){ + if(token!==MONTAR.layoutToken)return; + const lines=[...MONTAR.lines]; + if(!lines.length){MONTAR.layout=null;MONTAR.layoutPending=false;montarPaintTotals();montarDrawPreview(null);return;} + const images=await Promise.all(lines.map(line=>line.loading)); + if(token!==MONTAR.layoutToken)return; + if(images.some(image=>!image)){ + MONTAR.layoutPending=false;montarPaintTotals(); + say('A estampa não pôde ser lida.',true);return; + } + const cargas=lines.flatMap((line,sourceIndex)=>Array.from({length:line.qty},(_,copyIndex)=>({ + a:{sourceIndex,giro:0,esp:false},img:line.img,copyIndex,w:line.widthCm,h:line.heightCm,travado:false}))); + let enc; + try{enc=encaixar(cargas,MONTAR_FILM_CM);} + catch(e){ + if(token!==MONTAR.layoutToken)return; + MONTAR.layoutPending=false;montarPaintTotals();say(e.message,true);return; + } + if(token!==MONTAR.layoutToken)return; + MONTAR.layout={token,altura:enc.altura,pos:enc.pos}; + MONTAR.layoutPending=false; + montarPaintTotals(); + montarDrawPreview(MONTAR.layout); +} +// The sheet's preview: 57 cm across the panel, white film and the outline. +function montarDrawPreview(layout){ + const box=$('montar-layout'),canvas=$('montar-canvas'); + if(!layout){box.hidden=true;return;} + box.hidden=false; + const width=box.clientWidth-24; // the box's padding + if(width<60)return; + const px=width/MONTAR_FILM_CM; + const height=Math.max(20,layout.altura*px); + const dpr=Math.min(2,window.devicePixelRatio||1); + canvas.width=Math.round(width*dpr);canvas.height=Math.round(height*dpr); + canvas.style.width=width+'px';canvas.style.height=height+'px'; + const ctx=canvas.getContext('2d'); + ctx.setTransform(dpr,0,0,dpr,0,0); + ctx.fillStyle='#fff';ctx.fillRect(0,0,width,height); + ctx.strokeStyle='#B4BAC5';ctx.lineWidth=1; + ctx.strokeRect(.5,.5,width-1,height-1); + for(const p of layout.pos){ + const c=p.ref; + const giro=(p.rot===90?90:0)+(c.a&&c.a.giro?90:0); + ctx.save(); + ctx.translate((p.x+p.w/2)*px,(p.y+p.h/2)*px); + ctx.rotate(giro*Math.PI/180); + if(c.a&&c.a.esp)ctx.scale(-1,1); + const dw=((giro%180===90)?p.h:p.w)*px, dh=((giro%180===90)?p.w:p.h)*px; + if(c.img)ctx.drawImage(c.img,-dw/2,-dh/2,dw,dh); + else{ctx.fillStyle='#E7E7E3';ctx.fillRect(-dw/2,-dh/2,dw,dh);} + ctx.restore(); + } +} +// ---- Criar o pedido ------------------------------------------------------- +// The typed customer, as the Site's own Customer model validates it. +const MONTAR_CUSTOMER=['montar-name','montar-doc','montar-zap','montar-mail']; +function montarCustomer(){ + return {name:$('montar-name').value.trim(),cnpj:$('montar-doc').value.trim(), + zap:$('montar-zap').value.trim(),mail:$('montar-mail').value.trim()}; +} +const montarCustomerFilled=()=>MONTAR_CUSTOMER.every(id=>$(id).value.trim()); +function montarClearCustomer(){ + for(const id of MONTAR_CUSTOMER)$(id).value=''; + MONTAR.requestKey=null; +} +// Montar is the real thing now: a sheet, its layout and the customer. +function montarPaintActions(){ + const build=$('montar-build'); + const ready=!!(MONTAR.lines.length&&MONTAR.layout&&!MONTAR.layoutPending&& + montarCustomerFilled()&&!MONTAR.creating); + build.disabled=!ready; + build.title=ready?'':(MONTAR.lines.length?'Aguarde a montagem e preencha o cliente.':'Monte a folha primeiro.'); +} +// The Site's grade for loose art (web/site-quality.js): each stamp's DPI over +// the ideal 200, from 6 to 100; the item's is the average of its stamps'. +const montarGrade=dpi=>Math.max(6,Math.min(100,Math.round(dpi/200*100))); +function montarItem(sources){ + const cargas=[]; + sources.forEach((source,sourceIndex)=>{ + for(let copyIndex=0;copyIndexmontarGrade(source.line.dpi)); + const warning=sources.some(source=>source.line.dpisum+n,0)/grades.length), + uploads:sources.map(source=>source.uploadId), + production:{version:3,film_width_cm:MONTAR_FILM_CM,height_cm:height, + sources:sources.map(source=>({upload_id:source.uploadId,kind:'artwork', + width_cm:source.line.widthCm,length_cm:+source.line.heightCm.toFixed(4), + copies:source.copies,rotation_degrees:0,mirrored:false,measurement:'file'})), + placements:placementsDe(enc.pos)}, + quality_status:warning?'warning':'ok',quality_acknowledged:warning,residue_accepted:0}; +} +// 20 sources and 4000 copies per item; a stamp above 200 copies becomes +// several sources of the same upload, 200 each; items in list order. +function montarItems(lines,uploads){ + const pool=[]; + for(const line of lines){ + const uploadId=uploads.get(line.id); + for(let left=line.qty;left>0;left-=200) + pool.push({line,uploadId,copies:Math.min(200,left)}); + } + const groups=[];let current=null; + for(const source of pool){ + if(!current||current.sources.length>=20||current.copies+source.copies>4000){ + current={sources:[],copies:0};groups.push(current); + } + current.sources.push(source);current.copies+=source.copies; + } + return groups.map(group=>montarItem(group.sources)); +} +async function montarCreate(){ + if(MONTAR.creating)return; + const customer=montarCustomer(); + if(!montarCustomerFilled())return say('Preencha os dados do cliente.',true); + if(!MONTAR.lines.length)return say('Monte a folha primeiro.',true); + if(!MONTAR.layout||MONTAR.layoutPending)return say('A montagem ainda está sendo calculada.',true); + const lines=[...MONTAR.lines]; + if(!await ask('Criar pedido','Criar o pedido com '+plural(lines.reduce((t,line)=>t+line.qty,0),'estampa','estampas')+ + ', '+metres(MONTAR.layout.altura/100)+', para '+customer.name+'?','Criar pedido'))return; + MONTAR.creating=true;montarPaintActions(); + try{ + const uploads=new Map(); + for(let index=0;index{}); + }catch(e){say(e.message,true);} + finally{MONTAR.creating=false;montarPaintActions();} +} + +function montarLine(line){ + const row=node('div',undefined,'montar-line'); + const img=node('img',undefined,'montar-thumb');img.src=line.url;img.alt=''; + const words=node('span',undefined,'montar-linemeta'); + words.append(node('b',line.code),node('span',line.letter+' · '+cm(line.widthCm)+' cm')); + const qty=node('input',undefined,'montar-qty');qty.type='number';qty.min='1';qty.max='9999';qty.step='1'; + qty.value=String(line.qty);qty.setAttribute('aria-label','Quantidade de '+line.code+' '+line.letter); + qty.onchange=()=>{ + const value=Math.round(Number(qty.value)); + if(!Number.isInteger(value)||value<1||value>9999){qty.value=String(line.qty);return;} + line.qty=value;qty.value=String(value);montarChanged(); + }; + const dpi=node('span',undefined,'montar-dpi'); + if(line.dpimontarRemoveLine(line))); + return row; +} +function montarPaintLines(){ + const box=$('montar-lines'); + box.replaceChildren(...(MONTAR.lines.length?MONTAR.lines.map(montarLine) + :[emptyState(IC.box,'Nenhuma estampa na folha','Digite o código, escolha o tamanho e Adicionar.')])); + montarPaintTotals(); +} +function montarRemoveLine(line){ + URL.revokeObjectURL(line.url); + MONTAR.lines=MONTAR.lines.filter(other=>other!==line); + montarChanged(); +} +function montarClear(){ + for(const line of MONTAR.lines)URL.revokeObjectURL(line.url); + MONTAR.lines=[]; + montarChanged(); +} + +async function montarAdd(){ + const code=$('montar-code').value.trim(),size=montarSelected(); + if(!MONTAR_CODE.test(code))return say('Código inválido: use letras, números, hífen ou sublinhado, até 40.',true); + if(!size)return say('Nenhum tamanho na tabela. Peça à Gestão para cadastrar.',true); + const qty=Number($('montar-qty').value); + if(!Number.isInteger(qty)||qty<1||qty>9999)return say('A quantidade vai de 1 a 9999.',true); + if(!montarFolderReady())return; + let found; + try{found=await montarRead(code,size);} + catch(e){if(!montarFolderError(e))say(e.message,true);return;} + if(!found){montarPaintNotFound();return say('Código não existe em Estampas/.',true);} + montarPaintPreview(found); + if(found.widthCm>56)return say('A estampa tem '+cm(found.widthCm)+' cm de largura: o máximo é 56 cm.',true); + const dpi=montarDpi(found); + if(dpiline.code===code&&line.letter===size.letter); + if(existing){existing.qty=Math.min(9999,existing.qty+qty);montarChanged();return;} + const url=URL.createObjectURL(found.file),picture=montarStampImage(url); + MONTAR.lines.push({id:++MONTAR.seq,code,letter:size.letter,widthCm:found.widthCm,qty, + heightCm:montarHeight(found),dpi,url,img:picture.img,loading:picture.loading,file:found.file}); + montarChanged(); +} + +function montarPaintSelect(){ + const select=$('montar-size'),current=select.value; + select.replaceChildren(...MONTAR.sizes.map(size=>{ + const option=node('option',size.letter+' · '+cm(size.width_cm)+' cm');option.value=size.letter;return option; + })); + select.disabled=!MONTAR.sizes.length; + select.value=MONTAR.sizes.some(size=>size.letter===current)?current:(MONTAR.sizes[0]?.letter||''); +} +// A row of the table: the letter and its width in centimetres. +function montarSizeRow(size){ + const row=node('div',undefined,'montar-size-row'); + const letter=node('input',undefined,'montar-letter');letter.value=size?.letter||'';letter.maxLength=2; + letter.autocomplete='off';letter.setAttribute('aria-label','Letra do tamanho'); + letter.oninput=()=>{letter.value=letter.value.toUpperCase().replace(/[^A-Z]/g,'');MONTAR.dirty=true;}; + const width=node('input',undefined,'montar-width');width.type='number';width.min='0.01';width.max='56';width.step='0.01'; + width.value=size?Number(size.width_cm):'';width.setAttribute('aria-label','Largura em centímetros'); + width.oninput=()=>{MONTAR.dirty=true;}; + const remove=iconButton(IC.close,'Remover tamanho',()=>{row.remove();MONTAR.dirty=true;}); + row.append(letter,width,remove); + return row; +} +function montarPaintSizeEditor(){ + const panel=$('montar-sizes-panel'); + if(!may('manage')){panel.hidden=true;return;} + panel.hidden=false; + const head=node('div',undefined,'montar-size-head'); + head.append(node('span','Letra'),node('span','Largura (cm)'),node('span')); + $('montar-sizes').replaceChildren(head,...MONTAR.sizes.map(montarSizeRow)); +} +async function montarSaveSizes(){ + const rows=[...$('montar-sizes').querySelectorAll('.montar-size-row')]; + const sizes=[],seen=new Set(); + for(const row of rows){ + const letter=row.querySelector('.montar-letter').value.trim().toUpperCase(); + const width=Number(row.querySelector('.montar-width').value); + if(!/^[A-Z]{1,2}$/.test(letter))return say('Cada tamanho precisa de uma letra de A a ZZ.',true); + if(seen.has(letter))return say('A letra '+letter+' aparece mais de uma vez.',true); + if(!(width>0&&width<=56))return say('A largura de '+letter+' vai de 0,01 a 56 cm.',true); + seen.add(letter);sizes.push({letter,width_cm:Number(width.toFixed(2))}); + } + if(!sizes.length)return say('A tabela precisa de pelo menos um tamanho.',true); + await api('/stamp-sizes',{sizes}); + MONTAR.dirty=false; + say('Tamanhos salvos.'); + await montarLoadSizes(true); + montarQueuePreview(); +} +async function montarLoadSizes(repaint){ + MONTAR.sizes=(await api('/stamp-sizes')).sizes||[]; + montarPaintSelect(); + if(repaint||!MONTAR.dirty)montarPaintSizeEditor(); +} +async function loadMontador(){ + montarPaintFolder(); + try{await montarLoadSizes(false);} + catch(e){say(e.message,true);return;} + if(montarFolderReady()){ + if($('montar-code').value.trim()){if(!MONTAR.preview)montarQueuePreview();} + else montarPaintHint(); + } + montarPaintLines(); + if(MONTAR.layout)montarDrawPreview(MONTAR.layout); +} + +// 2b splits an order that passes these limits into more than one sheet; from +// now on it only warns, it does not block. +const montarWarning=node('p','O pedido será dividido em mais de uma folha.','montar-warn'); +montarWarning.id='montar-warning';montarWarning.hidden=true; +$('montar-sheet').insertBefore(montarWarning,$('montar-lines')); + +let montarResize=null; +addEventListener('resize',()=>{ + clearTimeout(montarResize); + montarResize=setTimeout(()=>{if(MONTAR.layout)montarDrawPreview(MONTAR.layout);},200); +}); + +$('montar-code').addEventListener('input',montarQueuePreview); +$('montar-size').addEventListener('change',()=>montarPreview().catch(e=>say(e.message,true))); +$('montar-qty').addEventListener('keydown',event=>{ + if(event.key==='Enter'){event.preventDefault();$('montar-add').click();} +}); +$('montar-add').onclick=async()=>{ + $('montar-add').disabled=true; + try{await montarAdd();}catch(e){say(e.message,true);}finally{$('montar-add').disabled=false;} +}; +$('montar-clear').onclick=()=>montarClear(); +$('montar-build').onclick=()=>montarCreate(); +for(const id of MONTAR_CUSTOMER)$(id).addEventListener('input',()=>{MONTAR.requestKey=null;montarPaintActions();}); +$('montar-size-add').onclick=()=>{MONTAR.dirty=true;$('montar-sizes').append(montarSizeRow(null));}; +$('montar-size-save').onclick=async()=>{ + $('montar-size-save').disabled=true; + try{await montarSaveSizes();}catch(e){say(e.message,true);}finally{$('montar-size-save').disabled=false;} +}; diff --git a/web/kanban.css b/web/kanban.css index 9eefde4..468a256 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -1251,3 +1251,60 @@ dialog.viewer::backdrop{background:var(--scrim)} background:var(--sf);border:1px solid var(--ln2);font-size:13px;color:var(--tx2);max-width:min(560px,calc(100% - 32px))} .vnote:empty{display:none} @media(max-width:700px){.vname{max-width:100%;flex-basis:100%}.vwhere{display:none}} + +/* Montador (Fase 2, front 7): the stamp by its code, the sheet's list and the + table of sizes. The lookup reads Estampas/ from the folder of Integrações. */ +#tab-montar .montar-add{display:grid;grid-template-columns:minmax(160px,1fr) minmax(130px,200px) 110px auto;gap:12px;align-items:end;padding:16px 18px 0} +#tab-montar .montar-add>.btn{height:42px} +#tab-montar .montar-preview{padding:16px 18px} +#tab-montar .montar-preview:empty{display:none} +#tab-montar .montar-stamp{display:flex;align-items:center;gap:14px;min-width:0} +#tab-montar .montar-stamp img{width:64px;height:64px;object-fit:contain;padding:4px;border-radius:9px;border:1px solid var(--ln2);background:var(--bg);flex:none} +#tab-montar .montar-stampinfo{display:flex;flex-direction:column;gap:3px;min-width:0} +#tab-montar .montar-stampinfo b{font-size:15px;font-weight:650} +#tab-montar .montar-stampinfo span{font-size:13px;color:var(--tx2)} +#tab-montar .montar-missing{margin:0;font-size:13.5px;color:var(--bad)} +#tab-montar .montar-hint{margin:0;font-size:13.5px;color:var(--tx3)} +#tab-montar .montar-total{margin-left:auto;font-size:13.5px;font-weight:650} +#tab-montar .montar-line{display:grid;grid-template-columns:56px minmax(110px,1fr) 82px auto 70px 36px;gap:12px;align-items:center;padding:10px 18px;border-bottom:1px solid var(--ln)} +#tab-montar .montar-line:last-child{border-bottom:0} +#tab-montar .montar-thumb{width:56px;height:56px;object-fit:contain;padding:4px;border-radius:9px;border:1px solid var(--ln2);background:var(--bg)} +#tab-montar .montar-linemeta{display:flex;flex-direction:column;gap:2px;min-width:0} +#tab-montar .montar-linemeta b{font-size:14px;font-weight:650} +#tab-montar .montar-linemeta span{font-size:12.5px;color:var(--tx3)} +#tab-montar .montar-qty{width:82px;height:36px;padding:0 8px;border-radius:9px;border:1px solid var(--ln2);background:var(--bg);color:var(--tx);text-align:right} +#tab-montar .montar-dpi{display:flex;justify-content:flex-end} +#tab-montar .montar-height{font-size:13px;color:var(--tx2);text-align:right;white-space:nowrap} +#tab-montar #montar-lines .emptystate{padding:28px 18px} +#tab-montar .montar-customer{border-top:1px solid var(--ln);padding:14px 18px} +#tab-montar .montar-customer h3{margin:0 0 10px;font-size:13px;font-weight:650;color:var(--tx2)} +#tab-montar .montar-customer-fields{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px} +@media (max-width:1100px){#tab-montar .montar-customer-fields{grid-template-columns:repeat(2,minmax(0,1fr))}} +#tab-montar .montar-actions{display:flex;justify-content:flex-end;gap:10px;padding:12px 18px;border-top:1px solid var(--ln)} +#tab-montar .montar-warn{margin:0;padding:10px 18px;border-bottom:1px solid var(--ln);font-size:13px;font-weight:600;color:var(--warn)} +#tab-montar .montar-layout{height:340px;overflow:auto;scrollbar-gutter:stable;border-top:1px solid var(--ln);background:var(--sf2);padding:12px} +#tab-montar .montar-layout canvas{display:block;margin:0 auto;background:#fff;box-shadow:0 0 0 1px var(--ln2)} +#tab-montar .montar-sizes{display:flex;flex-direction:column;padding:8px 0} +#tab-montar .montar-size-head,#tab-montar .montar-size-row{display:grid;grid-template-columns:90px 160px 36px;gap:12px;align-items:center;padding:6px 18px} +#tab-montar .montar-size-head{font-size:12.5px;color:var(--tx3)} +#tab-montar .montar-size-row input{height:36px;padding:0 10px;border-radius:9px;border:1px solid var(--ln2);background:var(--bg);color:var(--tx)} +#tab-montar .montar-size-row input:focus{border-color:var(--acc)} +@media (max-width:700px){ + #tab-montar .montar-add{grid-template-columns:minmax(0,1fr) minmax(0,1fr);padding:14px 14px 0} + #tab-montar .montar-add>.btn{grid-column:1/-1} + #tab-montar .montar-preview{padding:14px} + #tab-montar .montar-line{grid-template-columns:48px minmax(0,1fr) auto auto;grid-template-areas:"thumb meta qty remove" "thumb meta dpi height";gap:8px 10px;padding:10px 14px} + #tab-montar .montar-thumb{grid-area:thumb;width:48px;height:48px} + #tab-montar .montar-linemeta{grid-area:meta} + #tab-montar .montar-qty{grid-area:qty} + #tab-montar .montar-dpi{grid-area:dpi} + #tab-montar .montar-height{grid-area:height} + #tab-montar .montar-line>.btn{grid-area:remove} + #tab-montar .montar-actions{flex-wrap:wrap;padding:12px 14px} + #tab-montar .montar-actions .btn{flex:1} + #tab-montar .montar-customer{padding:12px 14px} + #tab-montar .montar-customer-fields{grid-template-columns:minmax(0,1fr)} + #tab-montar .montar-warn{padding:10px 14px} + #tab-montar .montar-layout{height:260px;padding:8px} + #tab-montar .montar-size-head,#tab-montar .montar-size-row{grid-template-columns:70px minmax(0,1fr) 36px;padding:6px 14px} +} diff --git a/web/kanban.html b/web/kanban.html index 1480532..1b523b0 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -38,6 +38,7 @@ + @@ -115,6 +116,45 @@
+ @@ -165,7 +205,7 @@ @@ -201,4 +241,4 @@
- + diff --git a/web/kanban.js b/web/kanban.js index ce9599e..9e509f7 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -44,7 +44,7 @@ let quoteQuery='', quoteProduct='', quoteLayout='', quoteFlag='', quoteTimer=nul // The signed-in operator and what their profile allows (app/core/auth.py). let ME=null; const may=cap=>!!ME?.can?.includes(cap); -const ROLE_NAMES={superadmin:'Superadmin',admin:'Administrador',gestao:'Gestão',designer:'Designer',operador:'Operador',revisor:'Revisor',vendedor:'Vendedor',financeiro:'Financeiro'}; +const ROLE_NAMES={superadmin:'Superadmin',admin:'Administrador',gestao:'Gestão',designer:'Designer',operador:'Operador',revisor:'Revisor',vendedor:'Vendedor',financeiro:'Financeiro',expedicao:'Expedição'}; // Which moves this profile makes, and which columns' order it sets: the // server's own list (app/core/auth.py MOVES), never worked out here. const mayMove=(from,to)=>!!ME?.moves?.some(([a,b])=>a===from&&b===to); @@ -60,7 +60,7 @@ const mayAct=order=>ME?.role!=='operador'||order.state==='tra'||isMine(order); const consults=()=>['vendedor','financeiro'].includes(ME?.role); const TAB_NEEDS={quotes:o=>may('manage')||consults(),payments:()=>may('payments'), stats:()=>may('manage')||consults(),site:()=>may('manage'), - integrations:()=>may('manage')||may('print'),users:()=>may('users')}; + integrations:()=>may('manage')||may('print'),users:()=>may('users'),montar:()=>may('assemble')}; function applyRole(){ for(const b of document.querySelectorAll('[data-tab]')){const need=TAB_NEEDS[b.dataset.tab];b.hidden=!!need&&!need();} if(TAB_NEEDS[tab]&&!TAB_NEEDS[tab]())showTab('board'); @@ -655,14 +655,14 @@ async function load(quiet=false){ } } // The page's name in the top bar; Produção also says what is open. -const PAGE_TITLES={board:'Produção',quotes:'Cotações',payments:'Pagamentos',stats:'Números',site:'Site',integrations:'Integrações',users:'Usuários'}; +const PAGE_TITLES={board:'Produção',quotes:'Cotações',payments:'Pagamentos',stats:'Números',site:'Site',integrations:'Integrações',users:'Usuários',montar:'Montar folha'}; function showTab(name){ tab=name;$('tab-quotes').classList.remove('reviewing'); for(const b of document.querySelectorAll('[data-tab]'))b.setAttribute('aria-selected',String(b.dataset.tab===name)); $('page-title').textContent=PAGE_TITLES[name];$('board-summary').hidden=name!=='board';$('filter-open').hidden=name!=='board'; $('more-nav').classList.toggle('on',['integrations','users'].includes(name)); - for(const id of ['board','quotes','payments','stats','site','integrations','users'])$('tab-'+id).hidden=name!==id; - const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,site:loadSiteAdmin,integrations:eventsIfAllowed,users:loadUsers}; + for(const id of ['board','quotes','payments','stats','site','integrations','users','montar'])$('tab-'+id).hidden=name!==id; + const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,site:loadSiteAdmin,integrations:eventsIfAllowed,users:loadUsers,montar:loadMontador}; if(board&&lists[name])lists[name]().catch(e=>say(e.message,true)); } function render(){ @@ -675,7 +675,7 @@ function render(){ tinyHeader();renderBoard();renderIntegrations(); $('badge-more').textContent=$('badge-integrations').textContent; // Lists live on their own pages of the API; refresh the one being looked at. - const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,site:loadSiteAdmin,integrations:eventsIfAllowed,users:loadUsers}; + const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,site:loadSiteAdmin,integrations:eventsIfAllowed,users:loadUsers,montar:loadMontador}; if(lists[tab])lists[tab]().catch(e=>say(e.message,true)); if(openOrder){const order=board.orders.find(o=>o.id===openOrder);if(order)renderPanel(order);else closePanel();} } @@ -2566,7 +2566,8 @@ const PRODUCT_LABEL={textil:'Têxtil',uv:'UV'}; const ROLE_HINTS={superadmin:'Tudo, e o suporte do sistema.',admin:'Tudo, inclusive usuários e máquinas.', gestao:'Tudo menos usuários; no quadro só puxa para trás, com motivo.',designer:'Aprova e recusa o arquivo final e pede correção.', operador:'Escolhe a máquina ao entrar, puxa da fila, imprime e passa para a Revisão.',revisor:'Confere a folha impressa e libera para Finalizado.', - vendedor:'Só consulta.',financeiro:'Pagamentos, Números e Cotações; cancela pedido com motivo.'}; + vendedor:'Só consulta.',financeiro:'Pagamentos, Números e Cotações; cancela pedido com motivo.', + expedicao:'Monta folhas no Kanban; só consulta o resto.'}; // Who is on the system: used it in the last 15 minutes, signed in before, // never, or switched off. const PRESENCE={on:'Ativo agora: usou o sistema nos últimos 15 minutos',away:'Inativo',never:'Nunca entrou',off:'Desativado: não entra no sistema'}; @@ -2577,11 +2578,11 @@ function avatar(u,className='ava'){ p.title=PRESENCE[presence(u)];a.append(p);return a; } // "O que cada perfil faz": Y does it, V only looks; the server's rules (app/core/auth.py). -const ROLE_COLUMNS=['admin','gestao','designer','operador','revisor','vendedor','financeiro']; -const ROLE_MATRIX=[['Aprovar o arquivo final','YYYNNNN'],['Pedir correção','YYYNNNN'],['Puxar da fila e imprimir','YNNYNNN'], - ['Lançar na ficha da máquina','YYNYNNN'],['Liberar para Finalizado','YNNNYNN'],['Foto da revisão','YYNNYNN'],['Voltar uma etapa, com motivo','YYYYYNN'],['Marcar retirado','YYYYYNN'], - ['Cotações e Números','YYNNNVV'],['Pagamentos','YYNNNNV'],['Pedido pago fora do site','YYNNNNN'],['Prova OK ou reprovada','YYNNNYN'],['Cancelar pedido','YYNNNNY'], - ['Abrir retrabalho','NYNNNNN'],['Autorizar retrabalho','YNNNNNN'],['Usuários e máquinas','YNNNNNN']]; +const ROLE_COLUMNS=['admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao']; +const ROLE_MATRIX=[['Aprovar o arquivo final','YYYNNNNN'],['Pedir correção','YYYNNNNN'],['Puxar da fila e imprimir','YNNYNNNN'], + ['Lançar na ficha da máquina','YYNYNNNN'],['Liberar para Finalizado','YNNNYNNN'],['Foto da revisão','YYNNYNNN'],['Voltar uma etapa, com motivo','YYYYYNNN'],['Marcar retirado','YYYYYNNN'], + ['Cotações e Números','YYNNNVVN'],['Pagamentos','YYNNNNVN'],['Pedido pago fora do site','YYNNNNNN'],['Prova OK ou reprovada','YYNNNYNN'],['Cancelar pedido','YYNNNNYN'], + ['Abrir retrabalho','NYNNNNNN'],['Autorizar retrabalho','YNNNNNNN'],['Usuários e máquinas','YNNNNNNN'],['Montar folha','YYNNNYNY']]; let usersData=null; async function loadUsers(){ usersData=await api('/users'); @@ -2654,7 +2655,7 @@ function userForm(u){ const editing=!!u; const name=node('input');name.required=true;name.maxLength=80;name.value=u?.name||'';name.placeholder='Nome e sobrenome'; const email=node('input');email.type='email';email.required=true;email.value=u?.email||'';email.placeholder='nome@dropstar.com.br'; - const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','designer','operador','revisor','vendedor','financeiro']; + const roles=u?.role==='superadmin'?['superadmin']:['admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao']; const role=choice(roles.map(r=>({value:r,label:ROLE_NAMES[r],hint:ROLE_HINTS[r]})),u?.role||'operador', {label:'Perfil',disabled:u?.role==='superadmin'||u?.email===ME.email}); const roleField=node('div',undefined,'fld');roleField.append(node('span','Perfil'),role,role.hint); @@ -3543,7 +3544,7 @@ function callout(d,title,text,tone=''){ // An order paid outside the site (Dropstar's rule D-35): the team builds the // cart on the Site, as a customer would, and registers it here. Origin and // payment start unchosen: a default would become the answer to everything. -const PAID_OUTSIDE={pix:'Pix',card:'Cartão',cash:'Dinheiro',credit:'Crédito do cliente'}; +const PAID_OUTSIDE={pix:'Pix',card:'Cartão',cash:'Dinheiro',credit:'Crédito do cliente',faturado:'Faturado'}; function registerForm(quote){ const form=node('form',undefined,'register'); const group=(name,label,options)=>{ diff --git a/web/packing.js b/web/packing.js new file mode 100644 index 0000000..e2b7d12 --- /dev/null +++ b/web/packing.js @@ -0,0 +1,213 @@ +/* DTF — o encaixe da folha, compartilhado pelo Site e pelo montador do Kanban: + máscaras, as regras de margem e a montagem em si. Script clássico: as páginas + o carregam antes do próprio código e dividem um só escopo global. */ +const CEL=0.5; // célula da máscara, em cm = a folga de 5 mm · deve ser igual a GAP_CM em web/site-config.js +// Dilata 1 célula para a direita e para baixo. Como toda peça é dilatada igual, +// duas vizinhas ficam separadas por exatamente 1 célula — os 5 mm da regra. +function dilatar(bruto,cw,ch,cheias){ + const cw2=cw+1, ch2=ch+1; + const out=new Uint8Array(cw2*ch2); + for(let y=0;y16 ? 1 : 0; cheias+=bruto[i]; } + return dilatar(bruto,cw,ch,cheias); +} + +// Margens e folgas da folha (regra da Dropstar, 21/10/2026): 5 mm em cima, +// embaixo e entre as linhas. Na largura, 5 mm nas bordas e entre as peças como +// alvo; quando não cabem, a sobra é dividida em partes iguais, e duas peças só +// ficam lado a lado com pelo menos 1,5 mm entre elas e nas bordas. +const MARGEM_CM=0.5, FOLGA_MIN_CM=0.15; +// Pela forma, as peças se aproximam (favo de mel) e as colunas se deslocam. +// Só compensa quando a folha encurta de verdade; senão, colunas alinhadas. +const GANHO_FORMA_CM=1; + +// pecas em centímetros: {w,h,img,a,travado}. W é a largura do filme em cm. +// Devolve {pos, altura, folga}: a altura já com as margens, a folga a menor +// usada na largura. +function encaixar(pecas,W){ + if(pecas.some(p=>!Number.isFinite(p.w) || p.w<=0 || p.w>W)) + throw new RangeError('A largura solicitada não cabe no filme.'); + const linhas=encaixarEmLinhas(pecas,W); + const forma=encaixarComMargens(pecas,W); + if(forma.altura<=linhas.altura-GANHO_FORMA_CM) return forma; + // A máscara de cada peça: a área de arte que a prévia mostra como aproveitada. + const mascaras=new Map(); + linhas.pos.forEach(p=>{ + const k=p.ref.a||p.ref, giro=p.rot+(p.ref.a?.giro||0); + if(!mascaras.has(k)) mascaras.set(k,new Map()); + const daArte=mascaras.get(k); + if(!daArte.has(p.rot)) daArte.set(p.rot,mascara(p.ref.img,p.w,p.h,giro,p.ref.a?.esp)); + p.m=daArte.get(p.rot); + }); + return linhas; +} + +// Em linhas, com as medidas exatas: cada arte (todas as cópias juntas) fica de +// pé ou deitada, a que der a folha mais curta. Em arte retangular, girar 90° é +// o que mais economiza filme. +function encaixarEmLinhas(pecas,W){ + const arteDe=p=>p.a||p; + const artes=[...new Set(pecas.map(arteDe))]; + // Toda peça que não é quadrada é testada nos dois sentidos (Dropstar, + // 23/10/2026): 19,5 x 18,5 cm cabe 2 por linha de pé e 3 deitada. + const giraveis=artes.filter(arte=>{const p=pecas.find(q=>arteDe(q)===arte); + return !p.mPronta && !p.travado && Math.abs(p.w-p.h)>0.01 && p.h<=W;}); + const deitadas=new Set(); + const montar=()=>emLinhas(pecas.map(p=>deitadas.has(arteDe(p)) + ? {ref:p,w:p.h,h:p.w,rot:90} : {ref:p,w:p.w,h:p.h,rot:0}),W); + const virar=arte=>deitadas.has(arte)?deitadas.delete(arte):deitadas.add(arte); + let melhor=montar(); + for(let volta=0;volta<2;volta++){ + let mudou=false; + for(const arte of giraveis){ + virar(arte); + const teste=montar(); + if(teste.alturab.h-a.h||b.w-a.w); + const linhas=[]; + for(const it of ordem){ + const linha=linhas.find(l=>l.soma+it.w+(l.itens.length+2)*FOLGA_MIN_CM<=W+1e-9); + if(linha){ linha.itens.push(it); linha.soma+=it.w; } + else linhas.push({itens:[it],soma:it.w,h:it.h}); // sozinha, cabe sempre + } + const pos=[]; + let y=MARGEM_CM, folgaMin=MARGEM_CM; + linhas.forEach((l,i)=>{ + const folga=Math.min(MARGEM_CM,(W-l.soma)/(l.itens.length+1)); + folgaMin=Math.min(folgaMin,folga); + let x=folga; + for(const it of l.itens){ pos.push({x,y,w:it.w,h:it.h,rot:it.rot,ref:it.ref}); x+=it.w+folga; } + y+=l.h+(ip.w)); + const lado=Math.max(0,Math.min(MARGEM_CM,(W-maior)/2)); + const enc=encaixarPelaForma(pecas,W-2*lado); + return {pos:enc.pos.map(p=>({...p, x:p.x+lado, y:p.y+MARGEM_CM})), + altura:enc.altura+2*MARGEM_CM, folga:lado}; +} + +// Encaixe pela forma: mapa de ocupação real, máscara por arte e candidatos +// numa grade de 5 mm ao longo da largura. +function encaixarPelaForma(pecas,W){ + const cols=Math.ceil(W/CEL)+1; // +1 = a coluna de folga da dilatação + let linhas=0; const mapa=[]; + function garantir(ate){ while(linhascols) return true; + for(let y=0;y=linhas) continue; // vazio abaixo do que já existe + const L=mapa[gy], off=y*m.cw; + for(let x=0;x!Number.isFinite(p.w) || p.w<=0 || p.w>W)) + throw new RangeError('A largura solicitada não cabe no filme.'); + const ordem=[...pecas].sort((a,b)=>(b.w*b.h)-(a.w*a.h)); + + ordem.forEach(p=>{ + const oris=[{w:p.w,h:p.h,rot:0}]; + if(!p.mPronta && !p.travado && Math.abs(p.w-p.h)>0.01 && p.h<=W) oris.push({w:p.h,h:p.w,rot:90}); + + let melhor=null; + oris.forEach(o=>{ + if(o.w>W) return; + // a máscara segue a medida da orientação escolhida · girada, largura e altura trocam + const m = (p.mPronta && o.rot===0) ? p.mPronta : mascara(p.img, o.w, o.h, + o.rot+(p.a?.giro||0), p.a?.esp); + const xs=new Set([0]), ys=new Set([0]); + postas.forEach(q=>{ xs.add(q.cx+q.m.cw); xs.add(q.cx); ys.add(q.cy+q.m.ch); ys.add(q.cy); }); + const passoX=Math.max(1,Math.round(cols/34)); + for(let x=0;x+m.cw<=cols;x+=passoX) xs.add(x); + xs.add(cols-m.cw); + const passoY=Math.max(1,Math.round(Math.max(linhas,1)/50)); + for(let y=0;y<=linhas;y+=passoY) ys.add(y); + const XS=[...xs].filter(x=>x>=0 && x+m.cw<=cols && x*CEL+o.w<=W+0.01).sort((a,b)=>a-b); + const YS=[...ys].filter(y=>y>=0).sort((a,b)=>a-b); + + for(const cy of YS){ + if(melhor && cy*CEL > melhor.y + CEL) break; + for(const cx of XS){ + if(cx*CEL + o.w > W + 0.01) continue; // não deixa a peça sair do filme + if(colide(m,cx,cy)) continue; + const cand={cx,cy,m,x:cx*CEL,y:cy*CEL,w:o.w,h:o.h,rot:o.rot,ref:p}; + // menor y, depois menor x · em empate, mantém a orientação original. + // Desempatar por largura gira tudo, e texto deitado na prévia parece erro. + const ganha = !melhor || cand.yp.y+p.h),1); + return {pos:postas, altura}; +} + +// O que o encaixe entrega a quem salva a montagem: cada peça em centímetros. +function placementsDe(pos){ + return pos.map(p=>({source_index:p.ref.a.sourceIndex, + copy_index:p.ref.copyIndex,x_cm:+p.x.toFixed(4),y_cm:+p.y.toFixed(4), + width_cm:+p.w.toFixed(4),length_cm:+p.h.toFixed(4), + rotation_degrees:(p.rot+(p.ref.a.giro||0))%360, + mirrored:!!p.ref.a.esp})); +} diff --git a/web/site-packing.js b/web/site-packing.js index d0ae639..0a7faad 100644 --- a/web/site-packing.js +++ b/web/site-packing.js @@ -83,208 +83,6 @@ function marcaDagua(ctx,w,h){ } ctx.restore(); } -const CEL=GAP_CM; // célula da máscara, em cm = a folga de 5 mm -// Dilata 1 célula para a direita e para baixo. Como toda peça é dilatada igual, -// duas vizinhas ficam separadas por exatamente 1 célula — os 5 mm da regra. -function dilatar(bruto,cw,ch,cheias){ - const cw2=cw+1, ch2=ch+1; - const out=new Uint8Array(cw2*ch2); - for(let y=0;y16 ? 1 : 0; cheias+=bruto[i]; } - return dilatar(bruto,cw,ch,cheias); -} - -// Margens e folgas da folha (regra da Dropstar, 21/10/2026): 5 mm em cima, -// embaixo e entre as linhas. Na largura, 5 mm nas bordas e entre as peças como -// alvo; quando não cabem, a sobra é dividida em partes iguais, e duas peças só -// ficam lado a lado com pelo menos 1,5 mm entre elas e nas bordas. -const MARGEM_CM=0.5, FOLGA_MIN_CM=0.15; -// Pela forma, as peças se aproximam (favo de mel) e as colunas se deslocam. -// Só compensa quando a folha encurta de verdade; senão, colunas alinhadas. -const GANHO_FORMA_CM=1; - -// pecas em centímetros: {w,h,img,a,travado}. W é a largura do filme em cm. -// Devolve {pos, altura, folga}: a altura já com as margens, a folga a menor -// usada na largura. -function encaixar(pecas,W){ - if(pecas.some(p=>!Number.isFinite(p.w) || p.w<=0 || p.w>W)) - throw new RangeError('A largura solicitada não cabe no filme.'); - const linhas=encaixarEmLinhas(pecas,W); - const forma=encaixarComMargens(pecas,W); - if(forma.altura<=linhas.altura-GANHO_FORMA_CM) return forma; - // A máscara de cada peça: a área de arte que a prévia mostra como aproveitada. - const mascaras=new Map(); - linhas.pos.forEach(p=>{ - const k=p.ref.a||p.ref, giro=p.rot+(p.ref.a?.giro||0); - if(!mascaras.has(k)) mascaras.set(k,new Map()); - const daArte=mascaras.get(k); - if(!daArte.has(p.rot)) daArte.set(p.rot,mascara(p.ref.img,p.w,p.h,giro,p.ref.a?.esp)); - p.m=daArte.get(p.rot); - }); - return linhas; -} - -// Em linhas, com as medidas exatas: cada arte (todas as cópias juntas) fica de -// pé ou deitada, a que der a folha mais curta. Em arte retangular, girar 90° é -// o que mais economiza filme. -function encaixarEmLinhas(pecas,W){ - const arteDe=p=>p.a||p; - const artes=[...new Set(pecas.map(arteDe))]; - // Toda peça que não é quadrada é testada nos dois sentidos (Dropstar, - // 23/10/2026): 19,5 x 18,5 cm cabe 2 por linha de pé e 3 deitada. - const giraveis=artes.filter(arte=>{const p=pecas.find(q=>arteDe(q)===arte); - return !p.mPronta && !p.travado && Math.abs(p.w-p.h)>0.01 && p.h<=W;}); - const deitadas=new Set(); - const montar=()=>emLinhas(pecas.map(p=>deitadas.has(arteDe(p)) - ? {ref:p,w:p.h,h:p.w,rot:90} : {ref:p,w:p.w,h:p.h,rot:0}),W); - const virar=arte=>deitadas.has(arte)?deitadas.delete(arte):deitadas.add(arte); - let melhor=montar(); - for(let volta=0;volta<2;volta++){ - let mudou=false; - for(const arte of giraveis){ - virar(arte); - const teste=montar(); - if(teste.alturab.h-a.h||b.w-a.w); - const linhas=[]; - for(const it of ordem){ - const linha=linhas.find(l=>l.soma+it.w+(l.itens.length+2)*FOLGA_MIN_CM<=W+1e-9); - if(linha){ linha.itens.push(it); linha.soma+=it.w; } - else linhas.push({itens:[it],soma:it.w,h:it.h}); // sozinha, cabe sempre - } - const pos=[]; - let y=MARGEM_CM, folgaMin=MARGEM_CM; - linhas.forEach((l,i)=>{ - const folga=Math.min(MARGEM_CM,(W-l.soma)/(l.itens.length+1)); - folgaMin=Math.min(folgaMin,folga); - let x=folga; - for(const it of l.itens){ pos.push({x,y,w:it.w,h:it.h,rot:it.rot,ref:it.ref}); x+=it.w+folga; } - y+=l.h+(ip.w)); - const lado=Math.max(0,Math.min(MARGEM_CM,(W-maior)/2)); - const enc=encaixarPelaForma(pecas,W-2*lado); - return {pos:enc.pos.map(p=>({...p, x:p.x+lado, y:p.y+MARGEM_CM})), - altura:enc.altura+2*MARGEM_CM, folga:lado}; -} - -// Encaixe pela forma: mapa de ocupação real, máscara por arte e candidatos -// numa grade de 5 mm ao longo da largura. -function encaixarPelaForma(pecas,W){ - const cols=Math.ceil(W/CEL)+1; // +1 = a coluna de folga da dilatação - let linhas=0; const mapa=[]; - function garantir(ate){ while(linhascols) return true; - for(let y=0;y=linhas) continue; // vazio abaixo do que já existe - const L=mapa[gy], off=y*m.cw; - for(let x=0;x!Number.isFinite(p.w) || p.w<=0 || p.w>W)) - throw new RangeError('A largura solicitada não cabe no filme.'); - const ordem=[...pecas].sort((a,b)=>(b.w*b.h)-(a.w*a.h)); - - ordem.forEach(p=>{ - const oris=[{w:p.w,h:p.h,rot:0}]; - if(!p.mPronta && !p.travado && Math.abs(p.w-p.h)>0.01 && p.h<=W) oris.push({w:p.h,h:p.w,rot:90}); - - let melhor=null; - oris.forEach(o=>{ - if(o.w>W) return; - // a máscara segue a medida da orientação escolhida · girada, largura e altura trocam - const m = (p.mPronta && o.rot===0) ? p.mPronta : mascara(p.img, o.w, o.h, - o.rot+(p.a?.giro||0), p.a?.esp); - const xs=new Set([0]), ys=new Set([0]); - postas.forEach(q=>{ xs.add(q.cx+q.m.cw); xs.add(q.cx); ys.add(q.cy+q.m.ch); ys.add(q.cy); }); - const passoX=Math.max(1,Math.round(cols/34)); - for(let x=0;x+m.cw<=cols;x+=passoX) xs.add(x); - xs.add(cols-m.cw); - const passoY=Math.max(1,Math.round(Math.max(linhas,1)/50)); - for(let y=0;y<=linhas;y+=passoY) ys.add(y); - const XS=[...xs].filter(x=>x>=0 && x+m.cw<=cols && x*CEL+o.w<=W+0.01).sort((a,b)=>a-b); - const YS=[...ys].filter(y=>y>=0).sort((a,b)=>a-b); - - for(const cy of YS){ - if(melhor && cy*CEL > melhor.y + CEL) break; - for(const cx of XS){ - if(cx*CEL + o.w > W + 0.01) continue; // não deixa a peça sair do filme - if(colide(m,cx,cy)) continue; - const cand={cx,cy,m,x:cx*CEL,y:cy*CEL,w:o.w,h:o.h,rot:o.rot,ref:p}; - // menor y, depois menor x · em empate, mantém a orientação original. - // Desempatar por largura gira tudo, e texto deitado na prévia parece erro. - const ganha = !melhor || cand.yp.y+p.h),1); - return {pos:postas, altura}; -} - function desenhaMontagem(area,lista,mts,W,fora,aoTerminar){ const versao=area.montagemVersao=(area.montagemVersao||0)+1; const filme=larguraFilme(), PX_CM=W/filme; @@ -356,11 +154,7 @@ function desenhaMontagem(area,lista,mts,W,fora,aoTerminar){ (girou>1?' artes giradas':' arte girada')+' 90° para caber melhor':''); (fora||area).appendChild(el); if(aoTerminar) aoTerminar({alturaCm, uso, girou, folgaCm:enc.folga, - placements:enc.pos.map(p=>({source_index:p.ref.a.sourceIndex, - copy_index:p.ref.copyIndex,x_cm:+p.x.toFixed(4),y_cm:+p.y.toFixed(4), - width_cm:+p.w.toFixed(4),length_cm:+p.h.toFixed(4), - rotation_degrees:(p.rot+(p.ref.a.giro||0))%360, - mirrored:!!p.ref.a.esp}))}); + placements:placementsDe(enc.pos)}); }); }