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 6ec18b8..38b0fd5 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 c2a4534..f7cc62c 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -108,8 +108,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' @@ -124,8 +135,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 @@ -443,6 +458,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 @@