From a9a4b61d994fb68c32a520b57fc0c82977bbae76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Wed, 11 Nov 2026 10:52:08 -0300 Subject: [PATCH 01/10] feat: Premium built and switched off; default machine minimums (front 3, Marcus 10/11) Premium (8 passadas, R$ 39,90/m, SKU DTFP.TX.100CM) is a fifth textile ready-sheet product: priced on the server and the Site, a hidden fifth card, a PREMIUM hot-folder class, its Tiny SKU, and a products row created disabled by a migration until Dropstar says 'testado'. A machine with no typed minimum now alerts at Dropstar's fixed minimums: 1 roll of film, 1 L of each ink, 5 kg of powder. Co-Authored-By: Claude Opus 5.5 (1M context) --- .gitea/workflows/deploy.yml | 1 + app/api/machine_log.py | 2 + app/api/operator/common.py | 4 +- app/catalog.py | 9 ++-- app/core/models.py | 8 ++-- app/core/pricing.py | 2 +- app/hotfolder.py | 18 ++++++-- app/machine_log.py | 20 ++++++-- app/mail.py | 3 +- .../202611111200_premium-product.sql | 17 +++++++ app/receipt.py | 3 +- app/tiny.py | 17 ++++--- deploy/nginx.conf.template | 2 +- tests/site_admin_test.py | 46 +++++++++++++++++-- tests/smoke_test.py | 2 +- tests/test_hotfolder.py | 26 +++++++++++ tests/test_machine_log.py | 20 +++++++- tests/test_pricing.py | 5 +- tests/test_tiny.py | 3 ++ web/checkout.js | 3 +- web/index.html | 10 ++++ web/kanban.js | 16 +++++-- web/site-config.js | 6 ++- web/site-modes.js | 5 +- web/site-pages.js | 3 +- 25 files changed, 202 insertions(+), 49 deletions(-) create mode 100644 app/migrations/202611111200_premium-product.sql create mode 100644 tests/test_hotfolder.py diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 4991f95..f120671 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -26,6 +26,7 @@ jobs: tests.test_db_pool \ tests.test_coupons \ tests.test_grade_rules \ + tests.test_hotfolder \ tests.test_migrate \ tests.test_secrets -v sh -n infra/lock_dependencies.sh diff --git a/app/api/machine_log.py b/app/api/machine_log.py index 7f18399..3bad147 100644 --- a/app/api/machine_log.py +++ b/app/api/machine_log.py @@ -53,6 +53,8 @@ def sheet(mid: UUID, user=Depends(can('view'))): 'counters': machine_log.counters(c, mid), 'supplies': machine_log.supply_estimates(c, mid), 'minimums': minimums, + # The values the sheet shows when Gestão has not typed one. + 'default_minimums': machine_log.DEFAULT_MINIMUMS, 'alerts': machine_log.alerts(c, mid), 'entries': [{**row, 'label': entry_label(row)} for row in entries], 'catalog': {'supplies': machine_log.SUPPLIES, 'parts': machine_log.PARTS, diff --git a/app/api/operator/common.py b/app/api/operator/common.py index 3ff55e0..4fa00f5 100644 --- a/app/api/operator/common.py +++ b/app/api/operator/common.py @@ -65,8 +65,8 @@ def cursor_pair(first, second): return first is not None -MODES = {'textil': {'file', 'avulsa'}, 'uv': {'uvfile', 'uv'}, - 'folha': {'file', 'uvfile'}, 'avulsa': {'avulsa', 'uv'}} +MODES = {'textil': {'file', 'avulsa', 'premium'}, 'uv': {'uvfile', 'uv'}, + 'folha': {'file', 'uvfile', 'premium'}, 'avulsa': {'avulsa', 'uv'}} def like(text): diff --git a/app/catalog.py b/app/catalog.py index a4b43cc..867c515 100644 --- a/app/catalog.py +++ b/app/catalog.py @@ -2,7 +2,7 @@ Dropstar, 2026-11-05 (Fase 2, front 8): the products and their prices leave the code and live in the database, with a start date and a history. `PRICES` in -app/core/pricing.py stays as the seed and the fallback for the four modes; +app/core/pricing.py stays as the seed and the fallback for the five modes; `treatment_cents()` stays as the fallback for `tratamento`. A price row is never changed or deleted once its start date has passed (the table is the history), and an approved quote keeps the price it was approved with. @@ -19,8 +19,8 @@ from decimal import Decimal from .core import pricing -# The four modes sold by the metre, and the treatment sold per order. -MODES = ('file', 'avulsa', 'uvfile', 'uv') +# The modes sold by the metre, and the treatment sold per order. +MODES = ('file', 'avulsa', 'uvfile', 'uv', 'premium') PRODUCTS = (*MODES, 'tratamento') TITLES = { @@ -28,10 +28,11 @@ TITLES = { 'avulsa': 'Têxtil artes avulsas', 'uvfile': 'UV folha pronta', 'uv': 'UV artes avulsas', + 'premium': 'Têxtil Premium · 8 passadas', 'tratamento': 'Tratamento pelo designer', } UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro', - 'tratamento': 'pedido'} + 'premium': 'metro', 'tratamento': 'pedido'} def fallback_cents(product: str) -> int: diff --git a/app/core/models.py b/app/core/models.py index e534eb0..6ec18b8 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -174,7 +174,7 @@ def check_splits(items): class Item(StrictModel): - mode: Literal['file','avulsa','uvfile','uv'] + mode: Literal['file','avulsa','uvfile','uv','premium'] metres: Decimal = Field(gt=0, le=12000) grade: int = Field(ge=0, le=100, strict=True) uploads: list[UUID] = Field(min_length=1, max_length=20) @@ -205,7 +205,7 @@ class Item(StrictModel): raise ValueError('Only loose artwork is split into sheets') if [source.upload_id for source in self.production.sources] != self.uploads: raise ValueError('Production sources must match uploaded files in order') - is_sheet = self.mode in ('file', 'uvfile') + is_sheet = self.mode in ('file', 'uvfile', 'premium') # UV is 27 cm wide (Dropstar, 2026-10-28; it was 28,5). film_width = Decimal('27') if self.mode in ('uvfile', 'uv') else Decimal('57') if self.production.film_width_cm != film_width: @@ -396,7 +396,7 @@ class CouponNew(StrictModel): min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1) max_uses: int | None = Field(default=None, gt=0, strict=True) max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True) - product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None + product: Literal['file', 'avulsa', 'uvfile', 'uv', 'premium'] | None = None note: str = Field(default='', max_length=1000) @@ -409,7 +409,7 @@ class CouponUpdate(StrictModel): min_metres: Decimal | None = Field(default=None, gt=0, decimal_places=1) max_uses: int | None = Field(default=None, gt=0, strict=True) max_uses_per_customer: int | None = Field(default=None, gt=0, strict=True) - product: Literal['file', 'avulsa', 'uvfile', 'uv'] | None = None + product: Literal['file', 'avulsa', 'uvfile', 'uv', 'premium'] | None = None note: str | None = Field(default=None, max_length=1000) paused: bool | None = None diff --git a/app/core/pricing.py b/app/core/pricing.py index b2c631b..e190df2 100644 --- a/app/core/pricing.py +++ b/app/core/pricing.py @@ -8,7 +8,7 @@ import os import re from decimal import Decimal, ROUND_CEILING -PRICES = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990} +PRICES = {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990, 'premium': 3990} # A finished sheet the Site cannot open (CDR, AI, PSD, TIFF) is opened by a # person before printing. It pays this per metre on top of the product's price diff --git a/app/hotfolder.py b/app/hotfolder.py index 70f399e..bed73c3 100644 --- a/app/hotfolder.py +++ b/app/hotfolder.py @@ -1,8 +1,9 @@ """Each machine's hot folders (Dropstar's third round, item 10, 2026-10-29/30). -FlexiPRINT watches 3. Imprimindo/// and takes a file out -of it when it rips. When the operator pulls a card to Imprimindo, its files -go, as a copy, into its machine's folder for the item's contraction class; +FlexiPRINT watches 3. Imprimindo/// and takes a +file out of it when it rips. When the operator pulls a card to Imprimindo, its +files go, as a copy, into its machine's folder for the item's contraction +class; a premium item always goes to PREMIUM, whichever class it carries; the order's own file stays in its stage folder. A film over 15 m is several parts (item 13): all on the same machine, in order, never more than two in the folder at once. The third is written when Flexi takes the first. @@ -27,6 +28,8 @@ IN_FOLDER = 2 # A computer that claimed a part and never said it was written. CLAIM_TIMEOUT = timedelta(minutes=10) CLASSES = ('C1', 'C2', 'C3') +# The premium product's own folder (Dropstar, 2026-11-10, front 3). +PREMIUM = 'PREMIUM' def contraction(order, index): @@ -41,6 +44,13 @@ def contraction(order, index): return item.get('stroke_class') if item.get('stroke_class') in CLASSES else None +def folder_class(order, index): + """The folder an item's parts go to: PREMIUM for the premium product, + whatever contraction class is recorded, else C1/C2/C3.""" + item = order['snapshot']['items'][index] + return PREMIUM if item.get('mode') == 'premium' else contraction(order, index) + + def start(c, order_id): """The order entered Imprimindo: its approved finals queue for its machine's folder, item by item, part by part.""" @@ -83,7 +93,7 @@ def claim(c, user): machine, order = row['machine_id'], row['order_id'] if row['state'] != 'queued' or order in blocked: continue - cls = contraction(row, row['item_index']) + cls = folder_class(row, row['item_index']) # A part without its class waits, and the parts after it with it. if busy.get(machine, 0) >= IN_FOLDER or not cls: blocked.add(order) diff --git a/app/machine_log.py b/app/machine_log.py index 8d8634d..0606ab4 100644 --- a/app/machine_log.py +++ b/app/machine_log.py @@ -16,8 +16,9 @@ once, which lets exactly one more card through. clean CLEAN_EVERY_METRES printed since the last "clean" event. align ALIGN_AFTER_FILM_METRES printed since the last film change (a supply entry of "film") with no "align" event after it. - supply a supply whose estimated stock is at or below the minimum Gestão set - for that machine (no minimum, no alert). + supply a supply whose estimated stock is at or below the machine's minimum: + the one Gestão typed, or Dropstar's default for that supply (1 roll + of film, 1 L of each ink, 5 kg of powder). The supply estimate assumes each entry refills what was used since the one before: the use per metre is the quantity entered over the metres printed in @@ -40,6 +41,11 @@ SUPPLY_INTERVALS = 3 SUPPLIES = {'film': ('Filme', 'rolo'), 'ink_c': ('Tinta ciano', 'L'), 'ink_m': ('Tinta magenta', 'L'), 'ink_y': ('Tinta amarela', 'L'), 'ink_k': ('Tinta preta', 'L'), 'ink_w': ('Tinta branca', 'L'), 'powder': ('Poliamida', 'kg')} +# Dropstar's fixed minimums (2026-11-10): a machine with no minimum typed uses +# these. Units match the supplies: rolls, litres and kilograms. +DEFAULT_MINIMUMS = {'film': Decimal('1'), 'ink_c': Decimal('1'), 'ink_m': Decimal('1'), + 'ink_y': Decimal('1'), 'ink_k': Decimal('1'), 'ink_w': Decimal('1'), + 'powder': Decimal('5')} PARTS = {'cap': 'Cap', 'damper': 'Damper', 'head': 'Cabeça de impressão', 'wiper': 'Wiper', 'other': 'Outra peça'} EVENTS = {'clean': 'Limpeza', 'align': 'Alinhamento da cabeça', 'stop': 'Parada'} @@ -130,8 +136,13 @@ def estimate(entries, metres_between, metres_since_last, minimum=None): 'minimum': minimum} +def minimum_for(minimums, item): + """The minimum typed for the machine, or Dropstar's default for that supply.""" + return minimums.get(item, DEFAULT_MINIMUMS.get(item)) + + def supply_low(value): - """Whether an estimate is at or below the machine's minimum (no minimum, no alert).""" + """Whether an estimate is at or below the machine's minimum (typed or default).""" return bool(value) and value['minimum'] is not None and value['stock'] <= value['minimum'] @@ -151,7 +162,8 @@ def supply_estimates(c, machine_id): continue printed = [printed_since(c, machine_id, row['created_at']) for row in rows] between = [printed[index - 1] - printed[index] for index in range(1, len(printed))] - value = estimate([row['quantity'] for row in rows], between, printed[-1], minimums.get(item)) + value = estimate([row['quantity'] for row in rows], between, printed[-1], + minimum_for(minimums, item)) if value is not None: result[item] = value return result diff --git a/app/mail.py b/app/mail.py index 99b192f..2fdd26e 100644 --- a/app/mail.py +++ b/app/mail.py @@ -93,7 +93,8 @@ def order_paid(c, order, origin): PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas', - 'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'} + 'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas', + 'premium': 'DTF Têxtil Premium · folha montada'} def quote_expired(c, quote, origin): diff --git a/app/migrations/202611111200_premium-product.sql b/app/migrations/202611111200_premium-product.sql new file mode 100644 index 0000000..2836fb0 --- /dev/null +++ b/app/migrations/202611111200_premium-product.sql @@ -0,0 +1,17 @@ +-- Front 3: the Premium product (Marcus, 2026-11-10), built and switched OFF +-- until Dropstar prints the three test sheets and says "testado". The products +-- CHECK is the inline constraint of dtf_local.products.id, which Postgres +-- named products_id_check; widening a list is a new migration that drops and +-- adds that one constraint (never schema.sql). +ALTER TABLE dtf_local.products DROP CONSTRAINT IF EXISTS products_id_check; +ALTER TABLE dtf_local.products ADD CONSTRAINT products_id_check + CHECK (id IN ('file','avulsa','uvfile','uv','premium','tratamento')); + +INSERT INTO dtf_local.products(id, enabled) VALUES ('premium', false) +ON CONFLICT (id) DO NOTHING; + +-- A coupon may also target the new product (the Site tab lists every mode). +ALTER TABLE dtf_local.coupons DROP CONSTRAINT IF EXISTS coupons_product_check; +ALTER TABLE dtf_local.coupons ADD CONSTRAINT coupons_product_check + CHECK (product IN ('file','avulsa','uvfile','uv','premium')); + diff --git a/app/receipt.py b/app/receipt.py index f146d3c..5b2f966 100644 --- a/app/receipt.py +++ b/app/receipt.py @@ -21,7 +21,8 @@ MARGIN = 4 * MM ROOM = WIDTH - 2 * MARGIN FONTS = {'F1': 'Helvetica-Bold', 'F2': 'Helvetica'} PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas', - 'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'} + 'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas', + 'premium': 'DTF Têxtil Premium · folha montada'} METHODS = {'pix': 'Pix', 'card': 'Cartão', 'cash': 'Dinheiro', 'credit': 'Crédito do cliente'} # Helvetica's widths for what the tables in printfile.py leave out. EXTRA = {'$': 556, '(': 333, ')': 333, '_': 556, '#': 556, '—': 1000, '@': 1015, '&': 667, '+': 584, "'": 191} diff --git a/app/tiny.py b/app/tiny.py index 2ecb8b1..ac569b8 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -59,29 +59,34 @@ AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect' # Not TINY_PRODUCT_: app/core/secrets.py reads any variable ending in # _FILE as a path to a secret file, and one product mode is called "file". PRODUCT_SETTINGS = {'file': 'TINY_PRODUCT_TEXTIL_FOLHA', 'avulsa': 'TINY_PRODUCT_TEXTIL_AVULSA', - 'uvfile': 'TINY_PRODUCT_UV_FOLHA', 'uv': 'TINY_PRODUCT_UV_AVULSA'} + 'uvfile': 'TINY_PRODUCT_UV_FOLHA', 'uv': 'TINY_PRODUCT_UV_AVULSA', + 'premium': 'TINY_PRODUCT_TEXTIL_PREMIUM'} # The common code prefix of a mode's SKUs ("DTFIMP.TX" for DTFIMP.TX.100CM, # the metre, and DTFIMP.TX.0010CM to DTFIMP.TX.0090CM). When set, it replaces # the mode's product id. SKU_SETTINGS = {'file': 'TINY_SKU_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_TEXTIL_AVULSA', - 'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA'} + 'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA', + 'premium': 'TINY_SKU_TEXTIL_PREMIUM'} # Or a SKU per 10 cm ("DTFIMP.UV.010CM"), alone (2,30 m is 23 of it) or after # a metre SKU ("DTFIMP.UV.1MT"): 2,30 m is 2 metres and 3 of the 10 cm. STEP_SETTINGS = {'file': 'TINY_SKU10_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU10_TEXTIL_AVULSA', - 'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA'} + 'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA', + 'premium': 'TINY_SKU10_TEXTIL_PREMIUM'} METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_METRO_TEXTIL_AVULSA', - 'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA'} + 'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA', + 'premium': 'TINY_SKU_METRO_TEXTIL_PREMIUM'} # Dropstar's own catalogue (checked against its Tiny export, 2026-10-14): Têxtil # as DTFIMP.TX.100CM per metre and DTFIMP.TX.0010CM to 0090CM for the rest, UV # as DTFIMP.UV.1MT per metre and DTFIMP.UV.010CM per 10 cm, the ready sheet and # loose artwork alike. The settings above only override these. -SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX'} +SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX', 'premium': 'DTFP.TX'} STEP_DEFAULTS = {'uvfile': 'DTFIMP.UV.010CM', 'uv': 'DTFIMP.UV.010CM'} METRE_DEFAULTS = {'uvfile': 'DTFIMP.UV.1MT', 'uv': 'DTFIMP.UV.1MT'} PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada', 'avulsa': 'DTF Têxtil 57 cm · artes avulsas', 'uvfile': 'DTF UV 27 cm · folha montada', - 'uv': 'DTF UV 27 cm · artes avulsas'} + 'uv': 'DTF UV 27 cm · artes avulsas', + 'premium': 'DTF Têxtil Premium 57 cm · folha montada'} # How far back to look for an order a previous delivery may already have made. SEARCH_DAYS = 7 # A "ready" event can come after corrections; it normally knows the Tiny id. diff --git a/deploy/nginx.conf.template b/deploy/nginx.conf.template index a1dbc11..4150efe 100644 --- a/deploy/nginx.conf.template +++ b/deploy/nginx.conf.template @@ -49,7 +49,7 @@ server { # Always revalidate HTML/JS/CSS after a deployment. Without this, a browser # can pair a new Kanban page with a cached older script after a rollout. # The Site's product pages and cart are addresses of the same page (web/site-pages.js). - location ~ ^/(arquivo-por-metro|artes-avulsas|uv-arquivo-por-metro|uv-artes-avulsas|carrinho|pagamento|pagamento/pix)/?$ { + location ~ ^/(arquivo-por-metro|artes-avulsas|uv-arquivo-por-metro|uv-artes-avulsas|premium|carrinho|pagamento|pagamento/pix)/?$ { expires -1; try_files /index.html =404; } diff --git a/tests/site_admin_test.py b/tests/site_admin_test.py index 9dfa6fe..f8d75bf 100644 --- a/tests/site_admin_test.py +++ b/tests/site_admin_test.py @@ -3,22 +3,35 @@ Run against the local stack: SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost python -m tests.site_admin_test """ +import io import secrets from datetime import datetime, timedelta, timezone from uuid import uuid4 +from PIL import Image, ImageDraw + from app.core import db from tests.print_file_test import artwork from tests.smoke_test import Client, item_spec, upload_bytes PASSWORD = 'senha-de-teste-123' UV = 'uv' +PREMIUM = 'premium' -def quote(client, item, mail): +def premium_sheet(): + """A 57 cm wide sheet above 96 DPI at that width, so the server accepts it.""" + image = Image.new('RGBA', (2400, 800), (0, 0, 0, 0)) + ImageDraw.Draw(image).rectangle([40, 40, 2360, 760], fill=(220, 30, 60, 255)) + out = io.BytesIO() + image.save(out, 'PNG', dpi=(300, 300)) + return out.getvalue() + + +def quote(client, item, mail, expected=200): return client.call('/quotes', {'request_key': str(uuid4()), 'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail}, - 'items': [item], 'freight': {'service': 'pickup'}}) + 'items': [item], 'freight': {'service': 'pickup'}}, expected=expected) def run(): @@ -34,9 +47,30 @@ def run(): prices, user = [], None try: products = manager.call('/operator/site/products')['products'] - assert {product['id'] for product in products} == {'file', 'avulsa', 'uvfile', 'uv', 'tratamento'} + assert {product['id'] for product in products} == \ + {'file', 'avulsa', 'uvfile', 'uv', 'premium', 'tratamento'} assert all(product['unit'] in ('metro', 'pedido') and product['title'] for product in products) + # Front 3: Premium is listed and starts switched off (Marcus, 2026-11-10). + premium_entry = next(product for product in products if product['id'] == PREMIUM) + assert premium_entry['enabled'] is False, premium_entry + assert premium_entry['title'] == 'Têxtil Premium · 8 passadas', premium_entry + assert client.call('/session')['products'][PREMIUM]['enabled'] is False + premium_item = {**item_spec(PREMIUM, '1', 0, upload_bytes( + client, premium_sheet(), name='LOCAL-SITE-PREMIUM.png')), + 'quality_status': 'warning', 'quality_acknowledged': True} + refused = quote(client, premium_item, mail, expected=422) + assert refused['detail'] == 'Este produto não está à venda agora.', refused + manager.call(f'/operator/site/products/{PREMIUM}', {'enabled': True}) + assert client.call('/session')['products'][PREMIUM]['enabled'] is True + created = quote(client, premium_item, mail) + assert created['status'] == 'approved', created + approved = client.call('/quotes/' + created['id'])['approved'] + assert approved['items'][0]['mode'] == PREMIUM, approved + assert approved['items'][0]['unit_cents'] == 3990, approved + assert approved['total_cents'] == 3990, approved + manager.call(f'/operator/site/products/{PREMIUM}', {'enabled': False}) + manager.call(f'/operator/site/products/{UV}', {'enabled': True}) uid = upload_bytes(client, artwork(), name='LOCAL-SITE-ADMIN.png') item = {**item_spec('uv', '1', 0, uid), 'quality_status': 'warning', 'quality_acknowledged': True} @@ -123,13 +157,15 @@ def run(): staff.call(f'/operator/site/products/{UV}', {'enabled': True}, expected=403) staff.call(f'/operator/site/products/{UV}/prices', {'unit_cents': 1000}, expected=403) staff.call(f'/operator/site/prices/{made["id"]}/cancel', {}, expected=403) - print('PASS: the Site tab switches a product off and refuses quotes, schedules and cancels prices,' - ' charges the new price, and refuses a non-manage profile') + print('PASS: the Site tab switches a product off and refuses quotes, lists Premium switched off' + ' and accepts it once enabled, schedules and cancels prices, charges the new price,' + ' and refuses a non-manage profile') finally: with db.connect() as c: if prices: c.execute('DELETE FROM dtf_local.product_prices WHERE id=ANY(%s::bigint[])', (prices,)) c.execute("UPDATE dtf_local.products SET enabled=true WHERE id=%s", (UV,)) + c.execute("UPDATE dtf_local.products SET enabled=false WHERE id=%s", (PREMIUM,)) if user: try: manager.call('/operator/users/' + str(user['id']) + '/delete', {}, expected=200) diff --git a/tests/smoke_test.py b/tests/smoke_test.py index 19b6994..d91e1b0 100644 --- a/tests/smoke_test.py +++ b/tests/smoke_test.py @@ -131,7 +131,7 @@ def item_spec(mode, metres, grade, uid): return {'mode':mode,'metres':str(metres),'grade':grade,'uploads':[uid], 'production':{'version':2,'film_width_cm':film_width,'height_cm':length_cm, 'sources':[{'upload_id':uid, - 'kind':'sheet' if mode in ('file','uvfile') else 'artwork', + 'kind':'sheet' if mode in ('file','uvfile','premium') else 'artwork', 'width_cm':film_width,'length_cm':length_cm,'copies':1, 'rotation_degrees':0,'mirrored':False,'measurement':'customer'}], 'placements':[{'source_index':0,'copy_index':0,'x_cm':0,'y_cm':0, diff --git a/tests/test_hotfolder.py b/tests/test_hotfolder.py new file mode 100644 index 0000000..85cbba7 --- /dev/null +++ b/tests/test_hotfolder.py @@ -0,0 +1,26 @@ +"""The machine hot folder class (Fase 2, front 3), without a database.""" +import unittest + +from app.hotfolder import PREMIUM, contraction, folder_class + + +def order(mode, stroke_class='C2', chosen=None): + return {'snapshot': {'items': [{'mode': mode, 'stroke_class': stroke_class}]}, + 'contraction': {'0': {'class': chosen}} if chosen else {}} + + +class FolderClassTest(unittest.TestCase): + def test_premium_always_goes_to_its_own_folder(self): + # Marcus, 2026-11-10: every premium item, whatever its contraction class. + self.assertEqual(folder_class(order('premium', 'C3'), 0), PREMIUM) + self.assertEqual(folder_class(order('premium', 'C1', chosen='C2'), 0), PREMIUM) + + def test_a_recorded_contraction_class_still_wins_for_other_products(self): + self.assertEqual(folder_class(order('file', 'C1', chosen='C2'), 0), 'C2') + self.assertEqual(folder_class(order('file'), 0), 'C2') + self.assertIsNone(contraction(order('file', None), 0)) + self.assertIsNone(folder_class(order('file', None), 0)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_machine_log.py b/tests/test_machine_log.py index 73ce778..1e43587 100644 --- a/tests/test_machine_log.py +++ b/tests/test_machine_log.py @@ -2,8 +2,8 @@ import unittest from decimal import Decimal -from app.machine_log import (ALIGN_AFTER_FILM_METRES, CLEAN_EVERY_METRES, estimate, - one_decimal, supply_low) +from app.machine_log import (ALIGN_AFTER_FILM_METRES, CLEAN_EVERY_METRES, DEFAULT_MINIMUMS, + estimate, minimum_for, one_decimal, supply_low) class EstimateTest(unittest.TestCase): @@ -38,6 +38,22 @@ class EstimateTest(unittest.TestCase): self.assertEqual(CLEAN_EVERY_METRES, Decimal('10')) self.assertEqual(ALIGN_AFTER_FILM_METRES, Decimal('20')) + def test_a_machine_without_typed_minimums_alerts_at_dropstars_defaults(self): + # Marcus, 2026-11-10: 1 roll of film, 1 L of each ink, 5 kg of powder. + self.assertEqual(DEFAULT_MINIMUMS, {'film': Decimal('1'), 'ink_c': Decimal('1'), + 'ink_m': Decimal('1'), 'ink_y': Decimal('1'), + 'ink_k': Decimal('1'), 'ink_w': Decimal('1'), + 'powder': Decimal('5')}) + for item, default in DEFAULT_MINIMUMS.items(): + with self.subTest(item=item): + minimum = minimum_for({}, item) + self.assertEqual(minimum, default) + value = estimate([Decimal('1'), Decimal('1')], [Decimal('10')], + Decimal('9'), minimum) + self.assertTrue(supply_low(value)) + # A minimum Gestão typed still wins over the default. + self.assertEqual(minimum_for({'film': Decimal('0')}, 'film'), Decimal('0')) + class AlertTextTest(unittest.TestCase): def test_one_decimal_uses_a_comma(self): diff --git a/tests/test_pricing.py b/tests/test_pricing.py index 0cc5e8e..784bd3c 100644 --- a/tests/test_pricing.py +++ b/tests/test_pricing.py @@ -34,8 +34,9 @@ class PricingTests(unittest.TestCase): def test_one_price_per_product(self): # Dropstar, 2026-10-23: textile R$ 19,90 ready sheet and R$ 21,90 loose - # art; UV R$ 79,90 and R$ 89,90. - self.assertEqual(PRICES, {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990}) + # art; UV R$ 79,90 and R$ 89,90. Premium R$ 39,90 (2026-11-10). + self.assertEqual(PRICES, {'file': 1990, 'avulsa': 2190, 'uvfile': 7990, 'uv': 8990, + 'premium': 3990}) self.assertEqual(price('avulsa', '2.75', 90)['total_cents'], 6132) def test_the_grade_never_changes_the_price(self): diff --git a/tests/test_tiny.py b/tests/test_tiny.py index 962e43f..979eef4 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -794,6 +794,9 @@ class DefaultSkuTests(unittest.TestCase): self.assertEqual(tiny.mode_codes('file'), tiny.sku_codes('DTFIMP.TX')) self.assertEqual(tiny.mode_codes('avulsa'), tiny.sku_codes('DTFIMP.TX')) self.assertEqual(tiny.mode_codes('uv'), ['DTFIMP.UV.1MT', 'DTFIMP.UV.010CM']) + # Premium's own catalogue: DTFP.TX.100CM per metre (front 3). + self.assertEqual(tiny.mode_codes('premium'), tiny.sku_codes('DTFP.TX')) + self.assertIn('DTFP.TX.100CM', tiny.mode_codes('premium')) self.assertEqual(tiny.required_settings(), ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI']) with mock.patch.dict(os.environ, {'TINY_SKU10_UV_FOLHA': 'UV.X'}): self.assertEqual(tiny.mode_codes('uvfile'), ['UV.X']) diff --git a/web/checkout.js b/web/checkout.js index 19e271a..982634b 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -97,7 +97,8 @@ PRECO[mode]=product.unit_cents/100; FAIXAS[mode]=product.bands||[]; const card=document.querySelector('button.ec[data-modo="'+mode+'"]'); - if(card&&!product.enabled)card.hidden=true; + // Premium starts hidden in the HTML and only appears once enabled. + if(card)card.hidden=!product.enabled; } document.querySelectorAll('[data-preco]').forEach(el=>{ const product=session.products[el.dataset.preco]; diff --git a/web/index.html b/web/index.html index 71a0f50..ad2c9ff 100644 --- a/web/index.html +++ b/web/index.html @@ -75,6 +75,7 @@ h1 em{font-style:normal;color:var(--laranja)} .escolha{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-top:24px; align-items:stretch} .escolha .ec{display:flex;flex-direction:column} +.escolha .ec[hidden]{display:none} .escolha .ec .in{flex:1} @media(max-width:1000px){.escolha{grid-template-columns:repeat(2,1fr)}} @media(max-width:600px){.escolha{grid-template-columns:1fr}} @@ -815,6 +816,15 @@ h2 em{font-style:normal;color:var(--laranja)} Enviar artes de UV + diff --git a/web/kanban.js b/web/kanban.js index 92e51ba..7783095 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -10,11 +10,11 @@ sessionStorage.removeItem('dtf-operator'); const FLOW=['rec','tra','imp','rev','fin']; const FORMER_STATES={fil:'Fila de impressão'}; const stateName=s=>board.states[s]||FORMER_STATES[s]||s; -const PRODUCT={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas'}; +const PRODUCT={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes avulsas',uvfile:'DTF UV · folha montada',uv:'DTF UV · artes avulsas',premium:'DTF Têxtil Premium · folha montada'}; // Loose art the Site split by stroke (item 17): each sheet is an item of its own. const productName=item=>PRODUCT[item.mode]+(item.split?' · folha '+item.split.part+' de '+item.split.of+ ', '+(item.stroke_class==='C3'?'chapado':'traço fino'):''); -const SHORT={file:'Têxtil folha',avulsa:'Têxtil avulsa',uvfile:'UV folha',uv:'UV avulsa'}; +const SHORT={file:'Têxtil folha',avulsa:'Têxtil avulsa',uvfile:'UV folha',uv:'UV avulsa',premium:'Premium'}; const EVENTS={payment_approved:'Pagamento aprovado',production_started:'Produção iniciada',correction_needed:'Correção necessária',ready:'Pedido pronto',cancelled:'Pedido cancelado'}; // Payment outcomes are recorded by the API in English; operators read Portuguese. function outcomeText(outcome){ @@ -427,7 +427,7 @@ async function fetchInto(dir,file){ await writeWhole(dir,file.name,r.body); } -// The machines' hot folders (item 10): 3. Imprimindo///. +// The machines' hot folders (item 10): 3. Imprimindo///. // The server says what this computer writes now (claimed for it alone, two // parts at most per machine); a written part gone from its folder was taken // by FlexiPRINT, and is never written again; a withdrawn one, from a card that @@ -757,7 +757,7 @@ const FILTER_TESTS={ site:o=>o.origin==='site', dropflow:o=>o.origin==='dropflow', atendimento:o=>o.origin==='atendimento', - textil:o=>o.snapshot.items.some(i=>i.mode==='file'||i.mode==='avulsa'), + textil:o=>o.snapshot.items.some(i=>i.mode==='file'||i.mode==='avulsa'||i.mode==='premium'), uv:o=>o.snapshot.items.some(i=>i.mode==='uvfile'||i.mode==='uv'), entrega:o=>!!o.snapshot.destination, retirada:o=>!o.snapshot.destination, @@ -1114,6 +1114,7 @@ function card(order,place){ row.append(node('span','#'+order.number,'num'),originTag(order),age); const name=node('span',who.title,'cname');name.title=[who.legal,who.mail].filter(Boolean).join(' · ')||who.title; const meta=node('span',undefined,'cmeta');meta.append(node('span',productLine(s.items))); + if(s.items.some(i=>i.mode==='premium'))meta.append(badge('Premium','','DTF Têxtil Premium: 8 passadas, branco no máximo')); if(order.machine){const m=node('span',order.machine.name,'mach'+(mine?' mine':''));m.title=mine?'Sua máquina':'Máquina';meta.append(m);} meta.append(node('b',metres(orderMetres(order)),'mtr')); info.append(row,name,meta); @@ -1436,6 +1437,7 @@ function renderPanel(order){ sub.append(badge('Nota '+s.grade_flags.aviso+': conferir a arte','warn', 'A nota da arte ficou abaixo do limite configurado: confira antes de imprimir')); if(isTest(order))sub.append(badge('Teste','','Pedido de teste: sem pagamento, não vai ao Tiny')); + if(s.items.some(i=>i.mode==='premium'))sub.append(badge('Premium','','DTF Têxtil Premium: 8 passadas, branco no máximo')); if(stalled(order)&&!order.cancelled_at)sub.append(badge('Parado há '+hoursSince(order.updated_at)+' h','bad','Sem mudar de etapa desde '+when(order.updated_at))); const steps=node('ol',undefined,'stepper');steps.setAttribute('aria-label','Etapas'); const at=FLOW.indexOf(order.state); @@ -2815,7 +2817,11 @@ async function openMachineSheet(machineId){ box.append(field('Preço de compra (R$)',price),field('Data de instalação',installed)); for(const [item,[label,unit]] of Object.entries(data.catalog.supplies)){ const input=node('input');input.type='number';input.min='0';input.step='0.001';input.inputMode='decimal'; - input.value=data.minimums[item]!==null&&data.minimums[item]!==undefined?Number(data.minimums[item]).toString():''; + // Dropstar's fixed minimums are the defaults: a machine with none typed + // shows and uses them until Gestão changes them. + const typed=data.minimums[item], fallback=data.default_minimums?.[item]; + input.value=typed!==null&&typed!==undefined?Number(typed).toString() + :fallback!==null&&fallback!==undefined?Number(fallback).toString():''; minimums[item]=input; box.append(field('Mínimo de '+label.toLowerCase()+' ('+unit+')',input)); } diff --git a/web/site-config.js b/web/site-config.js index 8c1e495..094f1ac 100644 --- a/web/site-config.js +++ b/web/site-config.js @@ -51,12 +51,14 @@ const MODOS={ zt:'Arraste sua folha de UV aqui', zs:'PNG ou PDF com fundo transparente · 27 cm de largura'}, uv: {tit:'Artes avulsas · UV', lg:'Adesivo UV · 27 cm', larg:27, multi:true, zt:'Arraste suas artes de UV', - zs:'PNG com fundo transparente · informe a largura de cada arte'} + zs:'PNG com fundo transparente · informe a largura de cada arte'}, + premium:{tit:'DTF Premium', lg:'DTF têxtil premium · 57 cm', larg:57, multi:true, folha:true, + zt:'Arraste sua folha montada aqui', zs:'PNG ou PDF com fundo transparente · 57 cm de largura'} }; // Preço único por produto (Dropstar, 23/10/2026). A nota da arte continua na // tela, para o cliente entender o arquivo dele, mas não mexe no preço. // O servidor cobra o mesmo (app/core/pricing.py, conferido em tests/test_pricing.py). -const PRECO={file:19.90, avulsa:21.90, uvfile:79.90, uv:89.90}; +const PRECO={file:19.90, avulsa:21.90, uvfile:79.90, uv:89.90, premium:39.90}; // Faixas por metragem (front 8.2): o preço do metro depende do total do // produto no pedido, não de cada item. Vem do servidor (/api/session), que // cobra o mesmo (app/catalog.py band_price). diff --git a/web/site-modes.js b/web/site-modes.js index d2d88a8..562fccf 100644 --- a/web/site-modes.js +++ b/web/site-modes.js @@ -46,7 +46,8 @@ function pintaModo(){ // dá para voltar atrás sem recomeçar o pedido. function pintaTipoEnvio(){ const el=$('tipoEnvio'); if(!el) return; - el.hidden=!modo; + // A product without its loose-art counterpart (Premium) has nothing to choose. + el.hidden=!modo || (ehFolha() && !PAR[modo]); if(el.hidden) return; const folha = ehFolha() ? modo : PAR[modo]; const avulsa = ehFolha() ? PAR[modo] : modo; @@ -80,7 +81,7 @@ function recusaFolha(x, md){ ''); const botao=$('usarAvulsa'); if(botao) botao.addEventListener('click',()=>{ - avisoTipo(''); trocaTipo(PAR[modo]); sel([arquivo]); + avisoTipo(''); trocaTipo(destino); sel([arquivo]); }); } document.querySelectorAll('#tipoEnvio .cam').forEach(b=>b.addEventListener('click',()=>{ diff --git a/web/site-pages.js b/web/site-pages.js index 09f0925..6a52629 100644 --- a/web/site-pages.js +++ b/web/site-pages.js @@ -6,7 +6,8 @@ addresses. Loaded in so the right page is the first one painted; site-steps.js does the navigation. */ const PAGINAS={file:'/arquivo-por-metro', avulsa:'/artes-avulsas', - uvfile:'/uv-arquivo-por-metro', uv:'/uv-artes-avulsas'}; + uvfile:'/uv-arquivo-por-metro', uv:'/uv-artes-avulsas', + premium:'/premium'}; const CARRINHO='/carrinho', PAGAMENTO='/pagamento', PAGAMENTO_PIX='/pagamento/pix'; function paginaDe(caminho){ caminho=caminho.replace(/\/+$/,'')||'/'; From b5a51137fbe4edffaa670bcc2fdf5a9aa6b5de42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Wed, 11 Nov 2026 11:01:44 -0300 Subject: [PATCH 02/10] feat: montador Interno and Venda, Tiny customers, brand per stamp (front 7a.3, Marcus 10/11) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Interno: the Expedição assembles the marketplace's own sales on the fixed internal customer Gestão fills in once; no Tiny order, no paid e-mail, marked interno, it stays in house. Venda: a Vendedor or Gestão picks the customer from the Tiny base and the order goes to Tiny like an approved quote, faturado (Boleto from TINY_RECEIPT_BOLETO when set), pickup or 'junto com o pedido de roupa nº X'. Números counts both at table price, apart from cash (and the average ticket over cash orders only). Each stamp can carry a brand and a public flag for the future catalogue. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/adapters.py | 12 + app/api/operator/integrations.py | 16 ++ app/api/operator/stats.py | 28 +- app/api/stamps.py | 116 +++++++- app/core/models.py | 24 +- .../202611111200_montador-interno-stamps.sql | 24 ++ app/payments.py | 23 +- app/tiny.py | 47 +++- tests/stamps_test.py | 139 ++++++++-- tests/test_moves.py | 28 +- web/kanban-montador.js | 247 ++++++++++++++++-- web/kanban-numbers.js | 13 +- web/kanban.css | 30 +++ web/kanban.html | 37 ++- web/kanban.js | 23 +- 15 files changed, 710 insertions(+), 97 deletions(-) create mode 100644 app/migrations/202611111200_montador-interno-stamps.sql diff --git a/app/adapters.py b/app/adapters.py index 3b5dbcd..f8ea3e7 100644 --- a/app/adapters.py +++ b/app/adapters.py @@ -190,10 +190,22 @@ class EventAdapter(Protocol): def deliver(self, event_key: str, payload: dict) -> dict: ... class FakeTiny: + # The montador's Venda customer search (front 7a.3) has somewhere to look + # on the local stack and in CI. Two fixed contacts, always. + CONTACTS = [ + {'id': 1001, 'name': 'Nexstar Marketplace Ltda', 'document': '11.222.333/0001-81', + 'email': 'financeiro@nexstar.example', 'phone': '1633334444'}, + {'id': 1002, 'name': 'Maria Souza', 'document': '123.456.789-09', + 'email': 'maria.souza@example.test', 'phone': '16988887777'}, + ] + def deliver(self, event_key: str, payload: dict) -> dict: return {'provider': 'fake-tiny', 'reference': f"LOCAL-{payload['number']}", 'event_key': event_key, 'status': 'recorded-locally'} + def search_contacts(self, query: str) -> list: + return [dict(contact) for contact in self.CONTACTS] + class ObjectStorage(Protocol): def begin(self, key: str) -> str: ... def parts(self, key: str, upload_id: str) -> list: ... diff --git a/app/api/operator/integrations.py b/app/api/operator/integrations.py index 36a0e36..0b3d217 100644 --- a/app/api/operator/integrations.py +++ b/app/api/operator/integrations.py @@ -133,6 +133,22 @@ def tiny_status(c=None): return {'configured': True, 'orders_enabled': os.environ.get('TINY_ADAPTER') == 'tiny', **tiny.TinyAuth().status(c)} +@router.get('/api/operator/tiny/contacts') +def tiny_contacts(q: str = Query(min_length=1, max_length=120), user=Depends(can('assemble'))): + """The Tiny contacts a Venda customer is picked from (Fase 2, front + 7a.3): by name, or by CPF/CNPJ when only digits were typed. The fake + adapter answers with two fixed contacts on the local stack and in CI.""" + if os.environ.get('TINY_ADAPTER') != 'tiny': + from ...adapters import FakeTiny + return FakeTiny().search_contacts(q) + if not tiny.configured(): + raise HTTPException(409, 'O Tiny não está conectado.') + try: + return tiny.search_contacts(tiny.TinyOrders(), q) + except tiny.TinyNotConnected: + raise HTTPException(409, 'O Tiny não está conectado.') + + @router.post('/api/operator/tiny/connect') def tiny_connect(user=Depends(can('integrations'))): """Start the one-time authorisation of this system in the client's Tiny.""" diff --git a/app/api/operator/stats.py b/app/api/operator/stats.py index 01ed0fd..95eae47 100644 --- a/app/api/operator/stats.py +++ b/app/api/operator/stats.py @@ -4,7 +4,7 @@ from decimal import Decimal from fastapi import APIRouter, Depends, HTTPException, Query -from ... import machines, unpaid +from ... import machines, payments, unpaid from ...core import db from ...core.auth import operator from .common import ORIGINS, REAL_ORDER, TREATED, person @@ -13,6 +13,11 @@ from .rework import CUSTOMER_CAUSE, HOUSE_CAUSES, REWORK_GOAL_PERCENT router = APIRouter() LOCAL_DAY = "(o.created_at AT TIME ZONE 'America/Sao_Paulo')::date" +# A montador "Interno" or "faturado" order records the table price, not money +# received (Marcus, 2026-11-10): the cash figures leave it out and Números +# shows it in its own block. +NOT_CASH = ('COALESCE(o.payment->>\'method\',\'\') NOT IN ' + f"('{payments.INTERNAL_METHOD}','{payments.INVOICED_METHOD}')") def waited(order, start, end): @@ -57,7 +62,8 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start limit_rows = c.execute('SELECT state,hours,responsible FROM dtf_local.stage_limits').fetchall() limits = {row['state']: {'hours': float(row['hours']), 'responsible': row['responsible']} for row in limit_rows} - total = c.execute(f'''SELECT count(*) AS orders, COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents, + total = c.execute(f'''SELECT count(*) AS orders, + COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents, COALESCE(sum({metres}),0) AS metres, count(*) FILTER (WHERE EXISTS (SELECT 1 FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state='cor' AND NOT m.back)) AS corrected @@ -131,20 +137,29 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start # Each way in apart (D-21): what came from where, and how long it took # from payment to Finalizado, Aguardando contato left out as above. origins = {row['origin']: row for row in c.execute(f'''SELECT o.origin, count(*) AS orders, - COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents, COALESCE(sum({metres}),0) AS metres, + COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents, + COALESCE(sum({metres}),0) AS metres, count(f.at) AS finished, percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM f.at - o.created_at) - {waited('o.id', 'o.created_at', 'f.at')}) / 3600 AS median_hours FROM dtf_local.orders o LEFT JOIN LATERAL (SELECT min(created_at) AS at FROM dtf_local.movements m WHERE m.order_id=o.id AND m.to_state='fin') f ON true WHERE {REAL_ORDER} AND {within} GROUP BY o.origin''', period).fetchall()} + # The table price of the montador's Interno and Venda orders, counted + # apart from the money received above (front 7a.3). + price_table = {row['method']: row for row in c.execute(f'''SELECT o.payment->>'method' AS method, + count(*) AS orders, COALESCE(sum({metres}),0) AS metres, + COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents + FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within} + AND o.payment->>'method' IN (%s,%s) GROUP BY 1''', + period + (payments.INTERNAL_METHOD, payments.INVOICED_METHOD)).fetchall()} # Coupons used by the period's paid orders (front 8.3): what each code # brought in orders, billed metres, discount and money received. coupons_used = c.execute(f'''SELECT o.snapshot->'coupon'->>'id' AS id, o.snapshot->'coupon'->>'code' AS code, count(*) AS orders, COALESCE(sum({metres}),0) AS metres, COALESCE(sum((o.snapshot->'coupon'->>'discount_cents')::bigint),0) AS discount_cents, - COALESCE(sum((o.snapshot->>'total_cents')::bigint),0) AS cents + COALESCE(sum((o.snapshot->>'total_cents')::bigint) FILTER (WHERE {NOT_CASH}),0) AS cents FROM dtf_local.orders o WHERE {REAL_ORDER} AND {within} AND o.snapshot->'coupon'->>'id' IS NOT NULL GROUP BY 1,2 ORDER BY orders DESC, code''', period).fetchall() @@ -224,6 +239,11 @@ def production_stats(days: int | None = Query(default=None, ge=7, le=365), start 'median_hours': hours(origins[name]['median_hours']) if name in origins else None} for name in ORIGINS], 'unpaid': unpaid_figures, + 'price_table': [{'method': method, + 'orders': price_table[method]['orders'] if method in price_table else 0, + 'metres': float(price_table[method]['metres']) if method in price_table else 0.0, + 'cents': int(price_table[method]['cents']) if method in price_table else 0} + for method in (payments.INVOICED_METHOD, payments.INTERNAL_METHOD)], 'lead': {'orders': lead['orders'], 'median_hours': hours(lead['median_hours'])}, 'stage_limits': limits, 'late': late, 'stages': {row['state']: {'orders': row['orders'], 'passages': row['passages'], diff --git a/app/api/stamps.py b/app/api/stamps.py index 712ea9c..b683f95 100644 --- a/app/api/stamps.py +++ b/app/api/stamps.py @@ -1,6 +1,8 @@ -"""The montador's stamp sizes and its invoiced orders (Fase 2, front 7).""" +"""The montador's stamp sizes, its brand per stamp, the internal customer and +the Interno and Venda orders a sheet becomes (Fase 2, fronts 7a to 7a.3).""" import hashlib import json +import re from uuid import uuid4 from fastapi import APIRouter, Depends, HTTPException, Request @@ -9,12 +11,22 @@ 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 ..core.models import (Customer, Freight, MontadorOrder, QuoteRequest, StampBrand, + StampSizeTable, UploadStart) from ..runtime import operator_identity from .uploads import begin_upload router = APIRouter() +CODE = re.compile(r'^[A-Za-z0-9_-]{1,40}$') +INTERNAL_MISSING = 'Peça à Gestão para completar o cliente interno.' +# Who chooses which kind of order in the montador (Marcus, 2026-11-10): the +# Expedição only Interno, the Vendedor only Venda; Gestão and the +# administrators both. +MONTADOR_KINDS = {'expedicao': {'interno'}, 'vendedor': {'venda'}, + 'superadmin': {'interno', 'venda'}, 'admin': {'interno', 'venda'}, + 'gestao': {'interno', 'venda'}} + @router.get('/api/operator/stamp-sizes') def stamp_sizes(user=Depends(can('assemble'))): @@ -33,6 +45,63 @@ def save_stamp_sizes(body: StampSizeTable, user=Depends(can('manage'))): return {'ok': True} +@router.get('/api/operator/internal-customer') +def read_internal_customer(user=Depends(can('assemble'))): + """The customer every Interno order belongs to; empty fields mean Gestão + still has to complete it.""" + with db.connect() as c: + row = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone() + return row or {'name': '', 'cnpj': '', 'zap': '', 'mail': ''} + + +@router.post('/api/operator/internal-customer') +def save_internal_customer(body: Customer, user=Depends(can('manage'))): + with db.connect() as c: + c.execute('''INSERT INTO dtf_local.internal_customer(id,name,cnpj,zap,mail,updated_by,updated_at) + VALUES(1,%s,%s,%s,%s,%s,now()) ON CONFLICT(id) DO UPDATE SET name=EXCLUDED.name, + cnpj=EXCLUDED.cnpj, zap=EXCLUDED.zap, mail=EXCLUDED.mail, + updated_by=EXCLUDED.updated_by, updated_at=now()''', + (body.name, body.cnpj, body.zap, body.mail, user)) + audit('internal_customer_changed', operator=user) + return {'ok': True} + + +def internal_customer(c): + """The fixed Interno customer, ready to use, or the reason Gestão must + complete it first.""" + row = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone() + if not row or not all(str(row[key] or '').strip() for key in ('name', 'cnpj', 'zap', 'mail')): + raise HTTPException(409, INTERNAL_MISSING) + try: + return Customer(**row) + except ValueError: + raise HTTPException(409, INTERNAL_MISSING) from None + + +@router.get('/api/operator/stamps/{code}') +def read_stamp(code: str, user=Depends(can('assemble'))): + """The brand recorded for a stamp code; nothing else uses it yet.""" + if not CODE.fullmatch(code): + raise HTTPException(422, 'Código inválido.') + with db.connect() as c: + row = c.execute('SELECT code,brand,public FROM dtf_local.stamps WHERE code=%s', (code,)).fetchone() + return row or {'code': code, 'brand': '', 'public': False} + + +@router.post('/api/operator/stamps/{code}') +def save_stamp(code: str, body: StampBrand, user=Depends(can('manage'))): + if not CODE.fullmatch(code): + raise HTTPException(422, 'Código inválido.') + brand = body.brand.strip() + with db.connect() as c: + c.execute('''INSERT INTO dtf_local.stamps(code,brand,public,updated_by,updated_at) + VALUES(%s,%s,%s,%s,now()) ON CONFLICT(code) DO UPDATE SET brand=EXCLUDED.brand, + public=EXCLUDED.public, updated_by=EXCLUDED.updated_by, updated_at=now()''', + (code, brand, body.public, user)) + audit('stamp_brand_saved', code=code, operator=user, public=body.public) + 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'): @@ -42,16 +111,29 @@ def montador_upload(body: UploadStart, user=Depends(can('assemble'))): @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) + """The card a montador sheet becomes (front 7a.3): Interno (the fixed + internal customer, origin dropflow, never Tiny) or Venda (a Tiny customer, + origin atendimento, invoiced and sent to Tiny). Pickup in both, at the + Site's table price; the order records whether it travels with a clothing + order.""" + role = request.state.operator['role'] + if body.kind not in MONTADOR_KINDS.get(role, set()): + raise HTTPException(403, 'Seu perfil não permite este tipo de pedido.') with db.connect() as c: + if body.kind == 'interno': + customer = internal_customer(c) + origin, method = 'dropflow', payments.INTERNAL_METHOD + else: + customer = body.customer + origin, method = 'atendimento', payments.INVOICED_METHOD + draft = QuoteRequest(request_key=body.request_key, customer=customer, items=body.items, + freight=Freight(service='pickup')).model_dump(mode='json', exclude={'request_key'}) + draft['montador'] = True + draft['kind'] = body.kind + if body.with_order: + draft['with_order'] = body.with_order + digest = hashlib.sha256(json.dumps(draft, sort_keys=True).encode()).hexdigest() + owner = operator_identity(user) 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))) @@ -60,12 +142,18 @@ def montador_order(body: MontadorOrder, request: Request, user=Depends(can('asse 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) + approved = quote_review.approve(c, quote, body.items, user) + # The order's kind and the clothing order it travels with, on the + # card and in Tiny's internal note. + approved = {**approved, 'kind': body.kind, + **({'with_order': body.with_order} if body.with_order else {})} + c.execute('UPDATE dtf_local.quotes SET approved=%s WHERE id=%s', + (Jsonb(approved), quote['id'])) quote = c.execute('SELECT * FROM dtf_local.quotes WHERE id=%s', (quote['id'],)).fetchone() - receipt = {'provider': payments.MANUAL_PROVIDER, 'method': payments.INVOICED_METHOD, 'note': '', + receipt = {'provider': payments.MANUAL_PROVIDER, 'method': 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) + audit('montador_order_created', order=str(order['id']), origin=origin, kind=body.kind, operator=user) return order diff --git a/app/core/models.py b/app/core/models.py index e534eb0..c2eee20 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -289,16 +289,26 @@ class QuoteRequest(StrictModel): 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.""" + """What the montador sends (front 7a.3): Interno or Venda, loose artwork + only and pickup; the server prices and approves it as a quote. An Interno + order takes the fixed customer from the database, a Venda one the customer + picked from Tiny.""" request_key: UUID - customer: Customer + kind: Literal['interno', 'venda'] + # Empty for an Interno order: the server reads the internal customer. + customer: Customer | None = None items: list[Item] = Field(min_length=1, max_length=30) + # A Venda that travels with the customer's clothing order; pickup freight. + with_order: int | None = Field(default=None, ge=1, le=999999, strict=True) @model_validator(mode='after') - def loose_art_only(self): + def order_kind(self): if any(item.mode != 'avulsa' for item in self.items): raise ValueError('O montador só monta artes avulsas.') + if self.kind == 'venda' and self.customer is None: + raise ValueError('O pedido de venda precisa do cliente.') + if self.kind == 'interno' and self.with_order is not None: + raise ValueError('O pedido interno não tem envio.') return self class Review(StrictModel): @@ -528,3 +538,9 @@ class StampSizeTable(StrictModel): if len(letters) != len(set(letters)): raise ValueError('Cada tamanho tem uma letra própria.') return self + + +class StampBrand(StrictModel): + """The brand recorded per stamp code, for the future catalogue (front 7a.3).""" + brand: str = Field(default='', max_length=120) + public: bool = False diff --git a/app/migrations/202611111200_montador-interno-stamps.sql b/app/migrations/202611111200_montador-interno-stamps.sql new file mode 100644 index 0000000..f164de0 --- /dev/null +++ b/app/migrations/202611111200_montador-interno-stamps.sql @@ -0,0 +1,24 @@ +-- Front 7a.3: a brand per stamp, for the future catalogue, and the montador's +-- fixed internal customer. The brand is only recorded here for now; nothing +-- else reads it yet (Marcus, 2026-11-10). +CREATE TABLE IF NOT EXISTS dtf_local.stamps ( + code text PRIMARY KEY CHECK (code ~ '^[A-Za-z0-9_-]{1,40}$'), + brand text NOT NULL DEFAULT '', + public boolean NOT NULL DEFAULT false, + updated_by text NOT NULL, + updated_at timestamptz NOT NULL DEFAULT now() +); + +-- The one customer every Interno order belongs to (the marketplace's own +-- sales). Gestão completes it; until then an Interno order is refused. +CREATE TABLE IF NOT EXISTS dtf_local.internal_customer ( + id integer PRIMARY KEY DEFAULT 1 CHECK (id=1), + name text NOT NULL DEFAULT '', + cnpj text NOT NULL DEFAULT '', + zap text NOT NULL DEFAULT '', + mail text NOT NULL DEFAULT '', + updated_by text NOT NULL DEFAULT 'sistema', + updated_at timestamptz NOT NULL DEFAULT now() +); +INSERT INTO dtf_local.internal_customer(id,name) VALUES(1,'Nexstar · Marketplace') +ON CONFLICT (id) DO NOTHING; diff --git a/app/payments.py b/app/payments.py index 345e599..05cb5ff 100644 --- a/app/payments.py +++ b/app/payments.py @@ -60,18 +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. +# A montador Venda order is invoiced, not paid at the counter: it is not one of +# the Cotações "registrar" methods. It goes to Tiny as an approved quote does. INVOICED_METHOD = 'faturado' +# A montador Interno order: the marketplace's own sale, already invoiced there. +# It stays in house and never reaches Tiny (Marcus, 2026-11-10). +INTERNAL_METHOD = 'interno' 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). + """Whether the order goes to Tiny: every order but an internal one, 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') == INTERNAL_METHOD: return False return not is_test(order) and not order.get('parent_id') @@ -153,9 +154,9 @@ def create_order(c, quote, payment, origin): proof.create_child(c, order) if is_test(order): return order, True - # 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: + # An invoiced or internal montador order was not paid here: no "pedido + # pago" e-mail for either (front 7a.3). + if payment.get('method') not in (INVOICED_METHOD, INTERNAL_METHOD): mail.order_paid(c, order, PUBLIC_ORIGIN) if not in_tiny(order): return order, True diff --git a/app/tiny.py b/app/tiny.py index 2ecb8b1..39ddf3f 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -103,8 +103,19 @@ OUTSIDE_NOTES = {'pix': 'Pix', 'card': 'cartão', 'cash': 'dinheiro', 'credit': def internal_note(payload): paid = payload.get('payment') or {} - how = f"pago fora do site ({OUTSIDE_NOTES.get(paid.get('method'), paid.get('method'))})" if paid.get('outside') else 'pago' - return f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}" + method = paid.get('method') + if method == 'faturado': + # A montador Venda order is invoiced (front 7a.3): its forma de + # recebimento is "Boleto" when the client's id is configured. + boleto = os.environ.get('TINY_RECEIPT_BOLETO', '').strip() + how = 'faturado (Boleto)' if boleto.isdigit() else 'faturado: forma de recebimento a definir' + else: + how = f"pago fora do site ({OUTSIDE_NOTES.get(method, method)})" if paid.get('outside') else 'pago' + note = f"{ORIGIN_NOTES.get(payload.get('origin') or 'site')} · {how} · {payload['order_id']}" + with_order = (payload.get('order') or {}).get('with_order') + if with_order: + note += f' · junto com o pedido de roupa nº {with_order}' + return note STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES' @@ -119,8 +130,12 @@ PICKUP_EXACT = 'retirar pessoalmente' # looked up: Pix and credit card, as the store's orders are paid, and the # DropStar carrier its pickup orders name. Dinheiro and, for the customer's # credit, Dropstar's own "CORREÇÃO DTF" were sent by Marcus on 2026-10-27, for -# the orders the team registers as paid outside the site (D-35). -RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 977493654} +# the orders the team registers as paid outside the site (D-35). "Boleto" is +# for a montador Venda order (front 7a.3); no id is known yet, and while +# TINY_RECEIPT_BOLETO is empty the order goes without a forma de recebimento. +_BOLETO = os.environ.get('TINY_RECEIPT_BOLETO', '').strip() +RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722, 'cash': 919478944, 'credit': 977493654, + **({'faturado': int(_BOLETO)} if _BOLETO.isdigit() else {})} PICKUP_CARRIER = 761565838 # Dropstar's answers: the financial category "DTF SITE" (RECEITAS, id sent on # 2026-10-26; it goes in pagamento.categoria, and replaced the store's @@ -438,6 +453,30 @@ def search_forms(document): return list(dict.fromkeys((punctuated(d), d))) +def search_contacts(orders, query, limit=10): + """Up to `limit` contacts matching what was typed (the montador's typeahead, + front 7a.3): by CPF/CNPJ when it is only digits and punctuation, else by + name. Tiny's own search does the matching.""" + text = str(query or '').strip() + digits = ''.join(ch for ch in text if ch.isdigit()) + found = [] + if digits and not any(ch.isalpha() for ch in text): + for form in search_forms(digits): + found += orders.request('GET', '/contatos', params={'cpfCnpj': form, 'limit': limit}).get('itens') or [] + else: + found = orders.request('GET', '/contatos', params={'nome': text, 'limit': limit}).get('itens') or [] + contacts, seen = [], set() + for entry in found: + if entry.get('id') in seen: + continue + seen.add(entry.get('id')) + contacts.append({'id': entry.get('id'), 'name': entry.get('nome') or '', + 'document': entry.get('cpfCnpj') or '', + 'email': entry.get('email') or '', + 'phone': entry.get('telefone') or entry.get('celular') or ''}) + return contacts[:limit] + + def contact_payload(order, company=None): """A new contact, named after the company's razão social when the registry gave it (app/cnpj.py), else the customer's name, else the diff --git a/tests/stamps_test.py b/tests/stamps_test.py index 0eb41f3..476c1b0 100644 --- a/tests/stamps_test.py +++ b/tests/stamps_test.py @@ -1,4 +1,5 @@ -"""The montador: stamp sizes, and the invoiced order a sheet becomes. +"""The montador: stamp sizes, brand per stamp, and the Interno and Venda +orders a sheet becomes (fronts 7a to 7a.3). Run against the local stack: python -m tests.stamps_test """ @@ -14,6 +15,7 @@ from tests.smoke_test import Client PASSWORD = 'senha-de-teste-123' PNG = (Path(__file__).resolve().parent / 'fixtures' / 'final-300.png').read_bytes() +INTERNAL_MISSING = 'Peça à Gestão para completar o cliente interno.' def signed_in(email, password=PASSWORD): @@ -55,6 +57,10 @@ def montador_item(uid, mode='avulsa'): 'quality_status': 'ok', 'quality_acknowledged': False, 'residue_accepted': 0} +def price_table(stats): + return {row['method']: row for row in stats['price_table']} + + def run(): tag = secrets.token_hex(3) su = Client() @@ -62,27 +68,37 @@ def run(): assert su.call('/operator/me', operator=True)['role'] == 'superadmin' with db.connect() as c: original = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall() - emails = {role: f'{role}-{tag}@example.test' for role in ('expedicao', 'designer', 'gestao')} + internal = c.execute('SELECT name,cnpj,zap,mail FROM dtf_local.internal_customer').fetchone() + # The seed state: only the name, so Interno must be refused until + # Gestão completes the other fields. + c.execute("UPDATE dtf_local.internal_customer SET name='Nexstar · Marketplace'," + "cnpj='',zap='',mail=''") + emails = {role: f'{role}-{tag}@example.test' for role in ('expedicao', 'vendedor', 'designer', 'gestao')} table = [(row['letter'], float(row['width_cm'])) for row in original] - customer = {'name': 'Cliente Montador', 'cnpj': '11222333000181', 'zap': '16999999999', - 'mail': f'montador-{tag}@example.test'} - identity = operator_identity(emails['expedicao']) + internal_customer = {'name': 'Nexstar · Marketplace', 'cnpj': '11222333000181', + 'zap': '1633334444', 'mail': f'interno-{tag}@example.test'} + venda_customer = {'name': 'Maria Souza', 'cnpj': '12345678909', + 'zap': '16988887777', 'mail': f'venda-{tag}@example.test'} + identities = [operator_identity(emails['expedicao']), operator_identity(emails['vendedor'])] made_orders, made_quotes = [], [] + # A code of its own, so a brand someone saved in Estampas/ is never touched. + stamp_code = 'T' + tag try: for role, email in emails.items(): su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role, 'password': PASSWORD}, operator=True) # The new profile creates through the users API and reads the table. shipping = signed_in(emails['expedicao']) + seller = signed_in(emails['vendedor']) + manager = signed_in(emails['gestao']) + designer = signed_in(emails['designer']) me = shipping.call('/operator/me') assert me['role'] == 'expedicao' and me['can'] == ['assemble', 'view'], me read = shipping.call('/operator/stamp-sizes')['sizes'] assert [(row['letter'], float(row['width_cm'])) for row in read] == table, read # The designer does not assemble: no reading the table. - designer = signed_in(emails['designer']) designer.call('/operator/stamp-sizes', expected=403) # Gestão replaces the whole table in one go and reads it back, by width. - manager = signed_in(emails['gestao']) manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'D', 'width_cm': 30}, {'letter': 'A', 'width_cm': 20}, {'letter': 'B', 'width_cm': 24.5}]}) @@ -102,35 +118,95 @@ def run(): read = manager.call('/operator/stamp-sizes')['sizes'] assert [(row['letter'], float(row['width_cm'])) for row in read] == [('A', 20), ('B', 24.5), ('D', 30)], read - # The montador's order: the stamp upload, then the invoiced card in rec. + # The brand per stamp: read by whoever assembles, saved by Gestão. + default = shipping.call('/operator/stamps/' + stamp_code) + assert default == {'code': stamp_code, 'brand': '', 'public': False}, default + manager.call('/operator/stamps/' + stamp_code, {'brand': 'Dropstar', 'public': True}) + saved = shipping.call('/operator/stamps/' + stamp_code) + assert saved == {'code': stamp_code, 'brand': 'Dropstar', 'public': True}, saved + designer.call('/operator/stamps/' + stamp_code, {'brand': 'X', 'public': False}, expected=403) + shipping.call('/operator/stamps/' + stamp_code, {'brand': 'X', 'public': False}, expected=403) + + # The fake Tiny answers the Venda customer search with two contacts. + contacts = shipping.call('/operator/tiny/contacts?q=Nexstar') + assert len(contacts) == 2, contacts + assert set(contacts[0]) == {'id', 'name', 'document', 'email', 'phone'}, contacts[0] + assert contacts[0]['document'] == '11.222.333/0001-81', contacts[0] + + # Interno is refused while Gestão has not completed the customer. stamp = upload_stamp(shipping) - request_key = uuid4() - body = {'request_key': str(request_key), 'customer': customer, - 'items': [montador_item(stamp)]} - order = shipping.call('/operator/montador/orders', body) - made_orders.append(UUID(order['id'])) - made_quotes.append(UUID(order['quote_id'])) - assert order['state'] == 'rec' and order['origin'] == 'dropflow', order - payment = order['payment'] - assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'faturado', 'paid'), payment - assert payment['total_cents'] == order['snapshot']['total_cents'], payment + interno = {'kind': 'interno', 'items': [montador_item(stamp)]} + refused = shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno}, + expected=409) + assert refused['detail'] == INTERNAL_MISSING, refused + manager.call('/operator/internal-customer', internal_customer) + completed = shipping.call('/operator/internal-customer') + assert (completed['name'], completed['cnpj'], completed['zap'], completed['mail']) == ( + 'Nexstar · Marketplace', '11222333000181', '1633334444', internal_customer['mail']), completed + + before_stats = manager.call('/operator/stats?days=30') + before = price_table(before_stats) + # Interno: the fixed customer, origin dropflow, no Tiny, no paid e-mail. + order_interno = shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno}) + made_orders.append(UUID(order_interno['id'])) + made_quotes.append(UUID(order_interno['quote_id'])) + assert order_interno['state'] == 'rec' and order_interno['origin'] == 'dropflow', order_interno + assert order_interno['snapshot']['kind'] == 'interno', order_interno['snapshot'].get('kind') + assert order_interno['snapshot']['customer']['cnpj'] == '11222333000181', order_interno['snapshot'] + payment = order_interno['payment'] + assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'interno', 'paid'), payment with db.connect() as c: assert c.execute('SELECT 1 FROM dtf_local.print_files WHERE order_id=%s', - (UUID(order['id']),)).fetchone() + (UUID(order_interno['id']),)).fetchone() assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s', - (f"{order['id']}:paid:tiny",)).fetchone() + (f"{order_interno['id']}:paid:tiny",)).fetchone() + assert not c.execute('SELECT 1 FROM dtf_local.mail_queue WHERE to_addr=%s', + (internal_customer['mail'],)).fetchone() + + # Venda: a Tiny customer, origin atendimento, invoiced and sent to Tiny. + venda_stamp = upload_stamp(seller) + venda = {'kind': 'venda', 'customer': venda_customer, 'with_order': 4321, + 'items': [montador_item(venda_stamp)]} + venda_body = {'request_key': str(uuid4()), **venda} + order_venda = seller.call('/operator/montador/orders', venda_body) + made_orders.append(UUID(order_venda['id'])) + made_quotes.append(UUID(order_venda['quote_id'])) + assert order_venda['state'] == 'rec' and order_venda['origin'] == 'atendimento', order_venda + assert order_venda['snapshot']['with_order'] == 4321, order_venda['snapshot'].get('with_order') + payment = order_venda['payment'] + assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'faturado', 'paid'), payment + with db.connect() as c: + assert c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s AND provider=%s', + (f"{order_venda['id']}:paid:tiny", 'tiny')).fetchone() + assert not c.execute('SELECT 1 FROM dtf_local.mail_queue WHERE to_addr=%s', + (venda_customer['mail'],)).fetchone() + + # Números: both are counted apart from the money received. + after_stats = manager.call('/operator/stats?days=30') + after = price_table(after_stats) + for method, order in (('interno', order_interno), ('faturado', order_venda)): + assert after[method]['orders'] == before[method]['orders'] + 1, (method, before[method], after[method]) + assert after[method]['cents'] == before[method]['cents'] + order['snapshot']['total_cents'], (method, before[method], after[method]) + assert after[method]['metres'] > before[method]['metres'], (method, before[method], after[method]) + assert after_stats['cents'] == before_stats['cents'], (before_stats['cents'], after_stats['cents']) + # The same montagem cannot become a second order. - refused = shipping.call('/operator/montador/orders', body, expected=409) - assert refused['detail'] == f"Esta montagem já virou o pedido #{order['number']}.", refused - # A designer does not use the montador, and only loose art becomes one. + refused = seller.call('/operator/montador/orders', venda_body, expected=409) + assert refused['detail'] == f"Esta montagem já virou o pedido #{order_venda['number']}.", refused + # Each profile makes only its own kind, and only loose art becomes one. + seller.call('/operator/montador/orders', {'request_key': str(uuid4()), **interno}, expected=403) + shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), **venda}, expected=403) designer.call('/operator/montador/uploads', {'name': 'ESTAMPA.png', 'size': 1}, expected=403) - designer.call('/operator/montador/orders', body, expected=403) - shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'customer': customer, + designer.call('/operator/montador/orders', {'request_key': str(uuid4()), **venda}, expected=403) + shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'kind': 'interno', 'items': [montador_item(stamp, 'file')]}, expected=422) - print('PASS: Expedição reads the sizes, uploads a stamp and gets the invoiced montador card; ' - 'Gestão edits the table; invalid rows, profiles and modes are refused') + print('PASS: Expedição makes Interno and Vendedor makes Venda; the internal customer, the Tiny ' + 'contacts, the stamp brand and the table price in Números work; invalid profiles and modes are refused') finally: with db.connect() as c: + if made_orders: + c.execute("DELETE FROM dtf_local.outbox WHERE payload->>'order_id' = ANY(%s::text[])", + ([str(oid) for oid in made_orders],)) for oid in made_orders: c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (oid,)) c.execute('DELETE FROM dtf_local.order_files WHERE order_id=%s', (oid,)) @@ -139,8 +215,13 @@ def run(): c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,)) if made_quotes: c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', (made_quotes,)) - c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr=%s', (customer['mail'],)) - c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (identity,)) + c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr IN (%s,%s)', + (internal_customer['mail'], venda_customer['mail'])) + for identity in identities: + c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (identity,)) + c.execute('DELETE FROM dtf_local.stamps WHERE code=%s', (stamp_code,)) + c.execute('UPDATE dtf_local.internal_customer SET name=%s,cnpj=%s,zap=%s,mail=%s', + (internal['name'], internal['cnpj'], internal['zap'], internal['mail'])) c.execute('DELETE FROM dtf_local.stamp_sizes') c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES(%s,%s)', table) c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',)) diff --git a/tests/test_moves.py b/tests/test_moves.py index f2cc637..5743262 100644 --- a/tests/test_moves.py +++ b/tests/test_moves.py @@ -1,8 +1,9 @@ """Who moves which card on the Kanban: Dropstar's flow of 2026-10-23.""" +import os import unittest from unittest import mock -from app import payments +from app import payments, tiny from app.core import auth from app.core.auth import CAPABILITIES, ROLES, may_move, may_reorder from app.runtime import BACK, STATES, TRANSITIONS @@ -78,14 +79,31 @@ class CanAnyTest(unittest.TestCase): route(None) -class InvoicedOrderTest(unittest.TestCase): - def test_an_invoiced_montador_order_is_held_out_of_tiny(self): +class MontadorPaymentTest(unittest.TestCase): + def test_a_faturado_order_goes_to_tiny_and_an_internal_one_does_not(self): self.assertEqual(payments.INVOICED_METHOD, 'faturado') - # It is not one of the Cotações "registrar" methods. + self.assertEqual(payments.INTERNAL_METHOD, 'interno') + # Neither is one of the Cotações "registrar" methods. self.assertNotIn(payments.INVOICED_METHOD, payments.OUTSIDE_METHODS) - self.assertFalse(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'faturado'}})) + self.assertNotIn(payments.INTERNAL_METHOD, payments.OUTSIDE_METHODS) + self.assertTrue(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'faturado'}})) + self.assertFalse(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'interno'}})) self.assertTrue(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'pix'}})) +class InternalNoteTest(unittest.TestCase): + payload = {'order_id': 'b6f1c0de-0000-4000-8000-000000000001', 'number': 42, + 'origin': 'atendimento', 'payment': {'method': 'faturado', 'outside': True}, + 'order': {'with_order': 4321}} + + def test_an_invoiced_order_says_how_it_is_received(self): + with mock.patch.dict(os.environ, {'TINY_RECEIPT_BOLETO': ''}): + note = tiny.internal_note(self.payload) + self.assertIn('faturado: forma de recebimento a definir', note) + self.assertIn('junto com o pedido de roupa nº 4321', note) + with mock.patch.dict(os.environ, {'TINY_RECEIPT_BOLETO': '123456'}): + self.assertIn('faturado (Boleto)', tiny.internal_note(self.payload)) + + if __name__ == '__main__': unittest.main() diff --git a/web/kanban-montador.js b/web/kanban-montador.js index 9ab4e73..f8990f7 100644 --- a/web/kanban-montador.js +++ b/web/kanban-montador.js @@ -1,20 +1,115 @@ /* 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. */ + Montar creates the card: Interno for the Expedição, Venda for a customer + picked from Tiny (front 7a.3). 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}; + layout:null,layoutTimer:null,layoutToken:0,layoutPending:false,creating:false,requestKey:null, + kind:null,internal:null,internalDirty:false,brands:new Map(),contactToken:0,contactTimer: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; +// ---- Interno or Venda ------------------------------------------------------ +// Marcus's answers of 2026-11-10 (front 7a.3): the Expedição only makes +// Interno orders, the Vendedor only Venda, and Gestão and the administrators +// both. An Interno order uses the fixed internal customer; a Venda one is +// picked from Tiny. +const montarKindNames=()=>ME?.role==='expedicao'?['interno']:ME?.role==='vendedor'?['venda']:['interno','venda']; +const montarInternalField=key=>String(MONTAR.internal?.[key]||''); +const montarInternalReady=()=>!!MONTAR.internal&&['name','cnpj','zap','mail'].every(key=>montarInternalField(key).trim()); +function montarPaintKind(){ + const kinds=montarKindNames(); + if(!MONTAR.kind||!kinds.includes(MONTAR.kind))MONTAR.kind=kinds.length===1?kinds[0]:'venda'; + if(MONTAR.kind==='interno'&&!montarInternalReady()&&kinds.length>1){ + MONTAR.kind='venda'; + for(const id of ['montar-name','montar-doc','montar-zap','montar-mail'])$(id).value=''; + } + const box=$('montar-kind'); + $('montar-kind-hint').textContent=kinds.length===1 + ?(MONTAR.kind==='interno'?'Interno, para a Expedição.':'Venda, para o Vendedor.') + :'Interno para a Expedição; Venda para um cliente do Tiny.'; + box.hidden=kinds.length<2; + box.replaceChildren(...kinds.map(kind=>{ + const b=node('button',kind==='interno'?'Interno':'Venda',kind===MONTAR.kind?'on':'');b.type='button'; + b.setAttribute('aria-pressed',String(kind===MONTAR.kind)); + b.disabled=kind==='interno'&&!montarInternalReady(); + b.title=b.disabled?'Peça à Gestão para completar o cliente interno.':''; + b.onclick=()=>montarSetKind(kind); + return b; + })); + $('montar-interno-missing').hidden=montarInternalReady(); +} +function montarSetKind(kind){ + if(MONTAR.kind===kind)return; + MONTAR.kind=kind; + montarClearCustomer(); + montarPaintKind();montarPaintCustomer();montarPaintActions(); +} +function montarPaintCustomer(){ + const interno=MONTAR.kind==='interno'; + $('montar-customer-title').textContent=interno?'Cliente interno':'Cliente'; + $('montar-customer-search').hidden=interno; + $('montar-interno-note').hidden=!interno; + $('montar-delivery').hidden=interno; + for(const [id,key] of [['montar-name','name'],['montar-doc','cnpj'],['montar-zap','zap'],['montar-mail','mail']]){ + $(id).disabled=interno; + if(interno)$(id).value=montarInternalField(key); + } +} +const montarDelivery=()=>document.querySelector('input[name="montar-delivery"]:checked')?.value||'pickup'; +function montarPaintDelivery(){ + const withOrder=montarDelivery()==='with_order'; + $('montar-with-order').disabled=!withOrder; + if(!withOrder)$('montar-with-order').value=''; +} +function montarWithOrder(){ + if(MONTAR.kind!=='venda'||montarDelivery()!=='with_order')return null; + const value=Math.round(Number($('montar-with-order').value)); + return Number.isInteger(value)&&value>=1&&value<=999999?value:null; +} +// The brand of a stamp, recorded for the future catalogue (Marcus, 10/11): +// only Gestão edits it; everyone who assembles reads it. +async function montarStampBrand(code){ + if(MONTAR.brands.has(code))return MONTAR.brands.get(code); + const stamp=await api('/stamps/'+encodeURIComponent(code)); + MONTAR.brands.set(code,stamp); + return stamp; +} +function montarBrandRow(code,stamp){ + const current=stamp||{brand:'',public:false}; + const row=node('div',undefined,'montar-brand'); + row.append(node('span','Marca','lbl')); + if(!may('manage')){ + row.append(node('b',current.brand||'—'),node('span',current.public?'Pública':'Não pública','lbl')); + return row; + } + const brand=node('input',undefined,'montar-brandinput'); + brand.value=current.brand||'';brand.maxLength=120;brand.autocomplete='off';brand.spellcheck=false; + brand.setAttribute('aria-label','Marca da estampa '+code); + const pub=node('label',undefined,'montar-public'); + const check=node('input');check.type='checkbox';check.checked=!!current.public; + pub.append(check,'Pública'); + const save=node('button','Salvar marca','btn');save.type='button'; + save.onclick=async()=>{ + save.disabled=true; + try{ + await api('/stamps/'+encodeURIComponent(code),{brand:brand.value.trim(),public:check.checked}); + MONTAR.brands.set(code,{code,brand:brand.value.trim(),public:check.checked}); + say('Marca salva.'); + }catch(e){say(e.message,true);}finally{save.disabled=false;} + }; + row.append(brand,pub,save); + return row; +} + // Without the folder there is no Estampas/ to read: only the size table works. function montarPaintFolder(){ const ok=montarFolderReady(); @@ -59,14 +154,16 @@ function montarDropPreview(){ if(MONTAR.preview)URL.revokeObjectURL(MONTAR.preview.url); MONTAR.preview=null; } -function montarPaintPreview(found){ +function montarPaintPreview(found,stamp){ 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); + const body=node('div',undefined,'montar-stampbody'); + body.append(words,montarBrandRow(found.code,stamp)); + const wrap=node('div',undefined,'montar-stamp');wrap.append(img,body); $('montar-preview').replaceChildren(wrap); } function montarPaintNotFound(){ @@ -88,7 +185,12 @@ async function montarPreview(){ 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(); + if(found){ + let stamp=null; + try{stamp=await montarStampBrand(code);}catch(e){stamp={code,brand:'',public:false};} + if(token!==MONTAR.token){URL.revokeObjectURL(found.url);return;} + montarPaintPreview(found,stamp); + }else montarPaintNotFound(); } function montarQueuePreview(){ clearTimeout(MONTAR.timer); @@ -198,15 +300,24 @@ function montarCustomer(){ const montarCustomerFilled=()=>MONTAR_CUSTOMER.every(id=>$(id).value.trim()); function montarClearCustomer(){ for(const id of MONTAR_CUSTOMER)$(id).value=''; + $('montar-customer-q').value=''; + $('montar-customer-hits').hidden=true; + document.querySelector('input[name="montar-delivery"][value="pickup"]').checked=true; + montarPaintDelivery(); MONTAR.requestKey=null; } -// Montar is the real thing now: a sheet, its layout and the customer. +// Montar is the real thing now: a sheet, its layout and the customer, which +// Interno reads from the database and Venda from Tiny. function montarPaintActions(){ const build=$('montar-build'); + const customerReady=MONTAR.kind==='interno'?montarInternalReady():montarCustomerFilled(); const ready=!!(MONTAR.lines.length&&MONTAR.layout&&!MONTAR.layoutPending&& - montarCustomerFilled()&&!MONTAR.creating); + customerReady&&!MONTAR.creating); build.disabled=!ready; - build.title=ready?'':(MONTAR.lines.length?'Aguarde a montagem e preencha o cliente.':'Monte a folha primeiro.'); + build.title=ready?'':(!MONTAR.lines.length?'Monte a folha primeiro.' + :(MONTAR.layoutPending||!MONTAR.layout)?'Aguarde a montagem da folha.' + :MONTAR.kind==='interno'?'Peça à Gestão para completar o cliente interno.' + :'Preencha os dados do cliente.'); } // 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'. @@ -252,13 +363,23 @@ function montarItems(lines,uploads){ } async function montarCreate(){ if(MONTAR.creating)return; - const customer=montarCustomer(); - if(!montarCustomerFilled())return say('Preencha os dados do cliente.',true); + const kind=MONTAR.kind||'venda'; + let customer=null,name=''; + if(kind==='interno'){ + if(!montarInternalReady())return say('Peça à Gestão para completar o cliente interno.',true); + name=montarInternalField('name'); + }else{ + customer=montarCustomer(); + if(!montarCustomerFilled())return say('Preencha os dados do cliente.',true); + name=customer.name; + } + if(kind==='venda'&&montarDelivery()==='with_order'&&!montarWithOrder()) + return say('Informe o número do pedido de roupa.',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; + ', '+metres(MONTAR.layout.altura/100)+', para '+name+'?','Criar pedido'))return; MONTAR.creating=true;montarPaintActions(); try{ const uploads=new Map(); @@ -271,11 +392,17 @@ async function montarCreate(){ } say('Criando o pedido…'); if(!MONTAR.requestKey)MONTAR.requestKey=crypto.randomUUID(); - const order=await api('/montador/orders',{request_key:MONTAR.requestKey, - customer,items:montarItems(lines,uploads)}); + const body={request_key:MONTAR.requestKey,kind,items:montarItems(lines,uploads)}; + if(kind==='venda'){ + body.customer=customer; + const withOrder=montarWithOrder(); + if(withOrder)body.with_order=withOrder; + } + const order=await api('/montador/orders',body); MONTAR.requestKey=null; montarClear(); montarClearCustomer(); + montarPaintCustomer(); say('Pedido #'+order.number+' criado em Arte recebida.',false,10000); load(true).catch(()=>{}); }catch(e){say(e.message,true);} @@ -328,7 +455,9 @@ async function montarAdd(){ 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); + let stamp=null; + try{stamp=await montarStampBrand(code);}catch(e){stamp={code,brand:'',public:false};} + montarPaintPreview(found,stamp); 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(dpicustomer[key]))return say('Preencha todos os campos do cliente interno.',true); + await api('/internal-customer',customer); + MONTAR.internalDirty=false; + say('Cliente interno salvo.'); + await montarLoadInternal(true); +} +// The Venda customer comes from Tiny's contacts, by name or CPF/CNPJ. +async function montarSearchContacts(){ + const token=++MONTAR.contactToken,q=$('montar-customer-q').value.trim(),hits=$('montar-customer-hits'); + if(q.length<2){hits.hidden=true;hits.replaceChildren();return;} + let contacts; + try{contacts=await api('/tiny/contacts?q='+encodeURIComponent(q));} + catch(e){ + if(token!==MONTAR.contactToken)return; + hits.replaceChildren(node('p',e.message,'montar-hint'));hits.hidden=false;return; + } + if(token!==MONTAR.contactToken)return; + if(!contacts.length){hits.replaceChildren(node('p','Nenhum contato no Tiny.','montar-hint'));hits.hidden=false;return;} + hits.replaceChildren(...contacts.map(contact=>{ + const hit=node('button',undefined,'montar-hit');hit.type='button';hit.setAttribute('role','option'); + hit.append(node('b',contact.name||contact.document||'Contato'), + node('span',[contact.document,contact.email,contact.phone].filter(Boolean).join(' · '),'sub')); + hit.onclick=()=>montarPickContact(contact); + return hit; + })); + hits.hidden=false; +} +function montarQueueContacts(){ + clearTimeout(MONTAR.contactTimer); + MONTAR.contactTimer=setTimeout(()=>montarSearchContacts().catch(e=>say(e.message,true)),300); +} +function montarPickContact(contact){ + $('montar-name').value=contact.name||''; + $('montar-doc').value=contact.document||''; + $('montar-zap').value=contact.phone||''; + $('montar-mail').value=contact.email||''; + $('montar-customer-q').value=contact.name||contact.document||''; + $('montar-customer-hits').hidden=true; + MONTAR.requestKey=null; + montarPaintActions(); + const missing=MONTAR_CUSTOMER.find(id=>!$(id).value.trim()); + if(missing)$(missing).focus(); +} async function loadMontador(){ montarPaintFolder(); - try{await montarLoadSizes(false);} + // Paint the chosen kind and customer before the fetch answers: an Expedição + // never sees an editable customer field, not even for a moment. + montarPaintKind();montarPaintCustomer(); + try{await Promise.all([montarLoadSizes(false),montarLoadInternal(false)]);} catch(e){say(e.message,true);return;} if(montarFolderReady()){ if($('montar-code').value.trim()){if(!MONTAR.preview)montarQueuePreview();} @@ -433,3 +629,22 @@ $('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;} }; +for(const id of ['montar-interno-name','montar-interno-doc','montar-interno-zap','montar-interno-mail']) + $(id).addEventListener('input',()=>{MONTAR.internalDirty=true;}); +$('montar-interno-save').onclick=async()=>{ + $('montar-interno-save').disabled=true; + try{await montarSaveInternal();}catch(e){say(e.message,true);}finally{$('montar-interno-save').disabled=false;} +}; +$('montar-customer-q').addEventListener('input',montarQueueContacts); +$('montar-customer-q').addEventListener('focus',()=>{if($('montar-customer-hits').children.length)$('montar-customer-hits').hidden=false;}); +$('montar-with-order').addEventListener('focus',()=>{ + document.querySelector('input[name="montar-delivery"][value="with_order"]').checked=true; + montarPaintDelivery(); +}); +$('montar-with-order').addEventListener('input',()=>{MONTAR.requestKey=null;}); +for(const radio of document.querySelectorAll('input[name="montar-delivery"]')) + radio.addEventListener('change',()=>{MONTAR.requestKey=null;montarPaintDelivery();}); +document.addEventListener('click',event=>{ + if(!event.target.closest('.montar-customer-search'))$('montar-customer-hits').hidden=true; +}); +montarPaintDelivery(); diff --git a/web/kanban-numbers.js b/web/kanban-numbers.js index 6964d11..994919c 100644 --- a/web/kanban-numbers.js +++ b/web/kanban-numbers.js @@ -181,14 +181,17 @@ async function loadStats(){ const mk=(label,value,unit)=>{const k=node('div',undefined,'mk');const b=node('b',value);if(unit)b.append(node('small',unit));k.append(node('span',label),b);return k;}; const pct=n=>data.orders?Math.round(100*n/data.orders)+'%':''; const [reais,centavos]=money(data.cents).split(','); + // The ticket is the cash received over the cash orders only: an Interno or + // faturado order records the table price, not money received (front 7a.3). + const cashOrders=Math.max(0,Number(data.orders)-(data.price_table||[]).reduce((sum,row)=>sum+(row.orders||0),0)); const hero=node('div',undefined,'hero'); hero.append(hk('Metros vendidos',metres(data.metres).replace(' m',''),'m',plural(data.orders,'pedido pago','pedidos pagos')), - hk('Recebido, com frete',reais,','+centavos,data.orders?'ticket médio de '+money(Math.round(data.cents/data.orders)):''), + hk('Recebido, com frete',reais,','+centavos,cashOrders?'ticket médio de '+money(Math.round(data.cents/cashOrders)):''), hk('Do pagamento ao Finalizado',duration(data.lead.median_hours),'',data.lead.orders?'mediana de '+plural(data.lead.orders,'pedido','pedidos')+', sem o tempo em Aguardando contato':'nenhum finalizado no período')); const rw=data.rework, share=v=>v==null?'—':String(v).replace('.',',')+'%'; const minis=node('div',undefined,'minis'); minis.append(mk('Pedidos pagos',String(data.orders)), - mk('Ticket médio',data.orders?money(Math.round(data.cents/data.orders)):'—'), + mk('Ticket médio',cashOrders?money(Math.round(data.cents/cashOrders)):'—'), mk('Com correção',String(data.corrected),pct(data.corrected)), mk('Artes tratadas',String(data.treated.orders),pct(data.treated.orders)), mk('Retrabalho da casa',share(rw.house.percent),'meta '+share(rw.house.goal_percent)), @@ -211,6 +214,12 @@ async function loadStats(){ tr.append(node('td',ORIGINS[o.origin]),node('td',String(o.orders),'r'),node('td',metres(o.metres).replace(' m',''),'r'),node('td',money(o.cents),'r'), node('td',o.finished?duration(o.median_hours):'—','r')); if(!o.orders)tr.classList.add('off');return tr;})); + // The montador's table price, apart from the money received (front 7a.3). + const priceNames={faturado:'Faturado',interno:'Interno'}; + $('stats-price-table').replaceChildren(...(data.price_table||[]).map(p=>{const tr=node('tr'); + tr.append(node('td',priceNames[p.method]||p.method),node('td',String(p.orders),'r'), + node('td',metres(p.metres).replace(' m',''),'r'),node('td',money(p.cents),'r')); + if(!p.orders)tr.classList.add('off');return tr;})); // Approved orders never paid: made, paid, expired and the abandonment rate. const unpaid=data.unpaid; const unpaidRows=[['Pedidos feitos',String(unpaid.made)],['Pagos',String(unpaid.paid)], diff --git a/web/kanban.css b/web/kanban.css index 468a256..a98548b 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -1289,6 +1289,32 @@ dialog.viewer::backdrop{background:var(--scrim)} #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)} +/* The Tiny typeahead opens over the sheet: the panel must not clip it. */ +#tab-montar #montar-sheet{overflow:visible} +#tab-montar .montar-kindbar{display:flex;align-items:center;gap:14px;flex-wrap:wrap;padding:12px 18px} +#tab-montar .montar-kindbar .phint{margin:0} +#tab-montar .montar-customer-search{position:relative;margin-bottom:12px} +#tab-montar .montar-hits{position:absolute;z-index:30;left:0;right:0;top:calc(100% + 4px);max-height:260px;overflow:auto;border:1px solid var(--ln2);border-radius:10px;background:var(--sf);box-shadow:0 12px 32px rgba(0,0,0,.25);padding:4px} +#tab-montar .montar-hit{display:flex;flex-direction:column;gap:2px;width:100%;padding:8px 10px;border:0;border-radius:7px;background:transparent;color:var(--tx);text-align:left;cursor:pointer} +#tab-montar .montar-hit:hover{background:var(--sf3)} +#tab-montar .montar-hit b{font-size:13.5px;font-weight:650} +#tab-montar .montar-hit .sub{font-size:12.5px;color:var(--tx3)} +#tab-montar .montar-delivery{border-top:1px solid var(--ln);padding:14px 18px} +#tab-montar .montar-delivery h3{margin:0 0 10px;font-size:13px;font-weight:650;color:var(--tx2)} +#tab-montar .montar-delivery-options{display:flex;flex-wrap:wrap;gap:8px} +#tab-montar .montar-radio{display:inline-flex;align-items:center;gap:8px;height:36px;padding:0 12px;border-radius:9px;border:1px solid var(--ln2);font-size:13px;font-weight:550;color:var(--tx2);cursor:pointer} +#tab-montar .montar-radio:has(input[type="radio"]:checked){border-color:var(--acc);color:var(--tx)} +#tab-montar .montar-radio input[type="number"]{width:110px;height:28px;padding:0 8px;border-radius:7px;border:1px solid var(--ln2);background:var(--bg);color:var(--tx);font-family:inherit;font-size:13px} +#tab-montar .montar-radio input[type="number"]:disabled{opacity:.5} +#tab-montar .montar-brand{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:8px} +#tab-montar .montar-brand .lbl{font-size:12px;color:var(--tx3)} +#tab-montar .montar-brand b{font-size:13.5px;font-weight:650} +#tab-montar .montar-brandinput{width:190px;height:34px;padding:0 10px;border-radius:8px;border:1px solid var(--ln2);background:var(--bg);color:var(--tx);font-family:inherit;font-size:13px} +#tab-montar .montar-brandinput:focus{border-color:var(--acc)} +#tab-montar .montar-public{display:inline-flex;align-items:center;gap:6px;font-size:12.5px;color:var(--tx2);cursor:pointer} +#tab-montar .montar-public input{accent-color:var(--acc)} +#tab-montar .montar-stampbody{display:flex;flex-direction:column;gap:4px;min-width:0} +#tab-montar .montar-interno-fields{padding:0 18px} @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} @@ -1307,4 +1333,8 @@ dialog.viewer::backdrop{background:var(--scrim)} #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} + #tab-montar .montar-kindbar{padding:12px 14px} + #tab-montar .montar-delivery{padding:12px 14px} + #tab-montar .montar-interno-fields{padding:0 14px} + #tab-montar .montar-brandinput{width:100%} } diff --git a/web/kanban.html b/web/kanban.html index e0897f1..76dc5d1 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -117,6 +117,13 @@