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:
@@ -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."""
|
||||
|
||||
@@ -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'],
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user