feat: montador Interno and Venda, Tiny customers, brand per stamp (front 7a.3, Marcus 10/11)

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) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-11 11:01:44 -03:00
parent e6197d6e40
commit b5a51137fb
15 changed files with 710 additions and 97 deletions

View File

@@ -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: ...

View File

@@ -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."""

View File

@@ -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'],

View File

@@ -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

View File

@@ -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

View File

@@ -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;

View File

@@ -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

View File

@@ -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