diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index c758d56..f45d15e 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -74,7 +74,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; 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; do echo "--- $suite" $COMPOSE exec -T \ -e SITE_BASE_URL=http://site \ 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/stamps.py b/app/api/stamps.py new file mode 100644 index 0000000..ec07236 --- /dev/null +++ b/app/api/stamps.py @@ -0,0 +1,70 @@ +"""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'}) + 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/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/models.py b/app/core/models.py index 420d0d7..6d8ae6e 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) @@ -493,3 +506,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/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/schema.sql b/app/schema.sql index b61378a..faa663a 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -284,11 +284,11 @@ 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')); + CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao')); -- 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. @@ -618,6 +618,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). 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_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/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 4d4f18b..0f09485 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -1245,3 +1245,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 c08d32a..1b523b0 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -38,6 +38,7 @@ + @@ -115,6 +116,45 @@
+ @@ -201,4 +241,4 @@
- + diff --git a/web/kanban.js b/web/kanban.js index f1c251d..10065ea 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();} } @@ -2559,7 +2559,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'}; @@ -2570,11 +2571,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'); @@ -2647,7 +2648,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); @@ -3536,7 +3537,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)}); }); }