feat: a Tiny order can be the client's own SKUs per length, 1 metro plus the rest
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 2m31s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 59s
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 2m31s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 59s
Dropstar's catalogue sells film as SKUs per length, and an order is a sum of them: 1,30 m is one "1 metro" (DTFIMP.TX.100CM) and one "30 cm" (DTFIMP.TX.0030CM). The adapter sent one product with the metres as the quantity. TINY_SKU_<MODE> names a mode's SKU prefix; the order then carries N times the metre SKU and one 10 cm SKU for the rest, at the price the customer paid, the last line taking what is left of the item so the order adds up to the cent. Each code is looked up once by its exact SKU among the active products. "Testar conexão" and tiny_probe conferir check all ten, and tiny_probe pedido takes --metros to show a split test order. Modes without the setting keep their product id: UV and artes avulsas stay that way until their SKUs are confirmed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
88
app/tiny.py
88
app/tiny.py
@@ -13,7 +13,9 @@ workers never spend the same one.
|
||||
|
||||
Orders are created by contact and product id: the customer's contact is found
|
||||
by CNPJ or created, and each product mode maps to a product that must already
|
||||
exist in Tiny (PRODUCT_SETTINGS).
|
||||
exist in Tiny (PRODUCT_SETTINGS), sold by the metre. A mode can instead be
|
||||
sold as the client's own SKUs per length (SKU_SETTINGS): the order is then a
|
||||
sum, 1,30 m = 1 × "1 metro" + 1 × "30 cm", at the price the customer paid.
|
||||
|
||||
Idempotency: the outbox may deliver the same event more than once. Every order
|
||||
carries numeroOrdemCompra = "DTF-<order number>", and before creating one the
|
||||
@@ -42,6 +44,11 @@ AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect'
|
||||
# _FILE as a path to a secret file, and one product mode is called "file".
|
||||
PRODUCT_SETTINGS = {'file': 'TINY_PRODUCT_TEXTIL_FOLHA', 'avulsa': 'TINY_PRODUCT_TEXTIL_AVULSA',
|
||||
'uvfile': 'TINY_PRODUCT_UV_FOLHA', 'uv': 'TINY_PRODUCT_UV_AVULSA'}
|
||||
# The common code prefix of a mode's SKUs ("DTFIMP.TX" for DTFIMP.TX.100CM,
|
||||
# the metre, and DTFIMP.TX.0010CM to DTFIMP.TX.0090CM). When set, it replaces
|
||||
# the mode's product id.
|
||||
SKU_SETTINGS = {'file': 'TINY_SKU_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_TEXTIL_AVULSA',
|
||||
'uvfile': 'TINY_SKU_UV_FOLHA', 'uv': 'TINY_SKU_UV_AVULSA'}
|
||||
PRODUCTS = {'file': 'DTF Têxtil 57 cm · folha montada',
|
||||
'avulsa': 'DTF Têxtil 57 cm · artes avulsas',
|
||||
'uvfile': 'DTF UV 28,5 cm · folha montada',
|
||||
@@ -92,7 +99,35 @@ def configured():
|
||||
|
||||
|
||||
def required_settings():
|
||||
return ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'] + list(PRODUCT_SETTINGS.values())
|
||||
"""The OAuth application, and a product id for each mode not sold by SKU."""
|
||||
return ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'] + [
|
||||
setting for mode, setting in PRODUCT_SETTINGS.items() if not sku_prefix(mode)]
|
||||
|
||||
|
||||
def sku_prefix(mode):
|
||||
return os.environ.get(SKU_SETTINGS[mode], '').strip()
|
||||
|
||||
|
||||
def sku_codes(prefix):
|
||||
"""The metre SKU and the nine of 10 to 90 cm, as the client's catalogue names them."""
|
||||
return [f'{prefix}.100CM'] + [f'{prefix}.{cm:04d}CM' for cm in range(10, 100, 10)]
|
||||
|
||||
|
||||
def sku_lines(item, prefix):
|
||||
"""(code, quantity, cents each) adding up to the item: whole metres as the
|
||||
metre SKU, the rest as one 10 cm SKU. The Site bills in 10 cm steps, so
|
||||
the rest always has a SKU; the lines carry the price the customer paid."""
|
||||
billed = Decimal(item['billed_metres'])
|
||||
centimetres = billed * 100
|
||||
if centimetres != centimetres.to_integral_value() or int(centimetres) % 10:
|
||||
raise TinyError(f'{billed} m is not a whole number of 10 cm steps')
|
||||
metres, rest = divmod(int(centimetres), 100)
|
||||
unit = int(item['unit_cents'])
|
||||
lines = [(f'{prefix}.100CM', metres, unit)] if metres else []
|
||||
if rest:
|
||||
# What is left of the item's total, so the order adds up to the cent.
|
||||
lines.append((f'{prefix}.{rest:04d}CM', 1, int(billed * unit) - metres * unit))
|
||||
return lines
|
||||
|
||||
|
||||
def status_updates():
|
||||
@@ -269,11 +304,23 @@ def address(destination):
|
||||
'uf': destination['state'], 'pais': 'Brasil'}
|
||||
|
||||
|
||||
def order_payload(payload, contact_id, today=None):
|
||||
"""The v3 'pedido' for a paid order's approved snapshot."""
|
||||
def order_payload(payload, contact_id, today=None, product_id=None):
|
||||
"""The v3 'pedido' for a paid order's approved snapshot. product_id finds a
|
||||
SKU's product id by its code, for the modes sold by SKU."""
|
||||
order = payload['order']
|
||||
items = []
|
||||
for item in order['items']:
|
||||
note = PRODUCTS[item['mode']] + f" · nota {item['grade']}"
|
||||
prefix = sku_prefix(item['mode'])
|
||||
if prefix:
|
||||
if product_id is None:
|
||||
raise TinyError(f"{SKU_SETTINGS[item['mode']]} needs the SKUs looked up in Tiny")
|
||||
for index, (code, quantity, cents) in enumerate(sku_lines(item, prefix)):
|
||||
line = {'produto': {'id': product_id(code)}, 'quantidade': quantity, 'valorUnitario': money(cents)}
|
||||
if index == 0:
|
||||
line['infoAdicional'] = note + f" · {item['billed_metres']} m"
|
||||
items.append(line)
|
||||
continue
|
||||
setting = PRODUCT_SETTINGS[item['mode']]
|
||||
product = os.environ.get(setting, '')
|
||||
if not product.isdigit():
|
||||
@@ -281,7 +328,7 @@ def order_payload(payload, contact_id, today=None):
|
||||
items.append({'produto': {'id': int(product)},
|
||||
'quantidade': float(Decimal(item['billed_metres'])),
|
||||
'valorUnitario': money(item['unit_cents']),
|
||||
'infoAdicional': PRODUCTS[item['mode']] + f" · nota {item['grade']}"})
|
||||
'infoAdicional': note})
|
||||
freight = order['freight']
|
||||
pickup = freight.get('service') == 'pickup'
|
||||
pedido = {'data': (today or local_today()).isoformat(),
|
||||
@@ -317,6 +364,17 @@ def configured_product(orders, mode):
|
||||
return found, 'ok'
|
||||
|
||||
|
||||
def configured_skus(orders, mode):
|
||||
"""Whether every SKU of a mode sold by SKU is an active product in Tiny."""
|
||||
missing = []
|
||||
for code in sku_codes(sku_prefix(mode)):
|
||||
try:
|
||||
orders.product_id(code)
|
||||
except TinyError:
|
||||
missing.append(code)
|
||||
return 'ok' if not missing else 'SKU não encontrado entre os produtos ativos: ' + ', '.join(missing)
|
||||
|
||||
|
||||
def configured_pickup(orders):
|
||||
"""The forma de envio the pickup setting points at, or why it cannot be used."""
|
||||
value = os.environ.get(PICKUP_SETTING, '')
|
||||
@@ -337,7 +395,8 @@ def check(auth=None, transport=None, orders=None):
|
||||
return 'ok'
|
||||
|
||||
reads = [('pedidos', lambda: listed('/pedidos')), ('contatos', lambda: listed('/contatos'))]
|
||||
reads += [(PRODUCTS[mode], lambda mode=mode: configured_product(orders, mode)[1]) for mode in PRODUCT_SETTINGS]
|
||||
reads += [(PRODUCTS[mode], lambda mode=mode: configured_skus(orders, mode) if sku_prefix(mode)
|
||||
else configured_product(orders, mode)[1]) for mode in PRODUCT_SETTINGS]
|
||||
reads.append(('forma de envio de retirada', lambda: configured_pickup(orders)[1]))
|
||||
results = {}
|
||||
for name, read in reads:
|
||||
@@ -360,6 +419,7 @@ class TinyOrders:
|
||||
self.auth = auth or TinyAuth()
|
||||
self.http = httpx.Client(base_url=API, transport=transport, timeout=30)
|
||||
self.today = today
|
||||
self.skus = {}
|
||||
|
||||
def request(self, method, path, **kwargs):
|
||||
headers = {'Authorization': f'Bearer {self.auth.access_token()}'}
|
||||
@@ -370,6 +430,19 @@ class TinyOrders:
|
||||
raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}')
|
||||
return response.json() if response.content else {}
|
||||
|
||||
def product_id(self, code):
|
||||
"""The id of the active product with this SKU code, remembered once found."""
|
||||
if code not in self.skus:
|
||||
found = self.request('GET', '/produtos', params={'codigo': code, 'situacao': 'A', 'limit': 10})
|
||||
# The filter may match more than the exact code: DTFIMP.TX.010CM is
|
||||
# a different product from DTFIMP.TX.0010CM.
|
||||
match = [p for p in found.get('itens') or []
|
||||
if str(p.get('sku') or p.get('codigo') or '') == code and p.get('situacao', 'A') == 'A']
|
||||
if not match:
|
||||
raise TinyError(f'SKU {code} não encontrado entre os produtos ativos do Tiny')
|
||||
self.skus[code] = int(match[0]['id'])
|
||||
return self.skus[code]
|
||||
|
||||
def contact(self, order):
|
||||
cnpj = order['customer']['cnpj']
|
||||
found = self.request('GET', '/contatos', params={'cpfCnpj': cnpj, 'limit': 5})
|
||||
@@ -415,7 +488,8 @@ class TinyOrders:
|
||||
tiny_id, situacao = existing.get('id'), existing.get('situacao')
|
||||
else:
|
||||
contact_id = self.contact(payload['order'])
|
||||
created = self.request('POST', '/pedidos', json=order_payload(payload, contact_id, self.today))
|
||||
created = self.request('POST', '/pedidos', json=order_payload(payload, contact_id, self.today,
|
||||
product_id=self.product_id))
|
||||
receipt = {'provider': 'tiny', 'event_key': event_key, 'status': 'created',
|
||||
'tiny_id': str(created.get('id')), 'tiny_number': str(created.get('numeroPedido'))}
|
||||
tiny_id, situacao = created.get('id'), ABERTA
|
||||
|
||||
@@ -4,8 +4,8 @@ Tiny has no sandbox, so this is how the adapter is proven on the real account.
|
||||
|
||||
python -m app.tiny_probe produtos [termo] list active products (read-only)
|
||||
python -m app.tiny_probe formas-envio [termo] list formas de envio, to find pickup (read-only)
|
||||
python -m app.tiny_probe conferir connection, the four product ids and pickup (read-only)
|
||||
python -m app.tiny_probe pedido --cnpj ... --email ... --celular ... [--modo file]
|
||||
python -m app.tiny_probe conferir connection, the products or SKUs and pickup (read-only)
|
||||
python -m app.tiny_probe pedido --cnpj ... --email ... --celular ... [--modo file] [--metros 1.3]
|
||||
show the test order; --confirmar creates it
|
||||
|
||||
The test order goes through TinyOrders.deliver, exactly as the worker sends a
|
||||
@@ -20,6 +20,7 @@ import json
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from .core.pricing import TIERS
|
||||
from .core.secrets import load as load_secret_files
|
||||
@@ -29,14 +30,16 @@ FIND_ATTEMPTS = 4
|
||||
FIND_WAIT_SECONDS = 5
|
||||
|
||||
|
||||
def test_order(cnpj, email, celular, mode, now=None):
|
||||
def test_order(cnpj, email, celular, mode, now=None, metres='1'):
|
||||
number = 'TESTE-' + (now or datetime.now(tiny.BRASILIA)).strftime('%Y%m%d%H%M')
|
||||
unit = TIERS[mode][0][1]
|
||||
total = int(Decimal(metres) * unit)
|
||||
return {'order_id': 'teste-integracao', 'number': number, 'event': 'payment_approved',
|
||||
'order': {'customer': {'cnpj': cnpj, 'mail': email, 'zap': celular},
|
||||
'items': [{'mode': mode, 'grade': 100, 'billed_metres': '1', 'unit_cents': unit}],
|
||||
'items': [{'mode': mode, 'grade': 100, 'billed_metres': metres, 'unit_cents': unit,
|
||||
'total_cents': total}],
|
||||
'freight': {'service': 'pickup', 'total_cents': 0},
|
||||
'destination': None, 'total_cents': unit}}
|
||||
'destination': None, 'total_cents': total}}
|
||||
|
||||
|
||||
def produtos(orders, termo, out):
|
||||
@@ -64,6 +67,13 @@ def formas_envio(orders, termo, out):
|
||||
def conferir(orders, out):
|
||||
ok = True
|
||||
for mode, setting in tiny.PRODUCT_SETTINGS.items():
|
||||
prefix = tiny.sku_prefix(mode)
|
||||
if prefix:
|
||||
result = tiny.configured_skus(orders, mode)
|
||||
ok &= result == 'ok'
|
||||
out(f'{tiny.SKU_SETTINGS[mode]} ({tiny.PRODUCTS[mode]}): {result} '
|
||||
f'({prefix}.100CM e {prefix}.0010CM a {prefix}.0090CM)')
|
||||
continue
|
||||
product, result = tiny.configured_product(orders, mode)
|
||||
ok &= result == 'ok'
|
||||
described = f"{product.get('sku') or '-'} · {product.get('descricao')}" if product else ''
|
||||
@@ -87,7 +97,8 @@ def pedido(orders, payload, confirm, out, wait=time.sleep):
|
||||
out(f"Contato {cnpj}: " + (f"já existe no Tiny (id {known[0]['id']})" if known
|
||||
else 'não existe; será criado com o e-mail como nome'))
|
||||
out('Pedido que será enviado:')
|
||||
out(json.dumps(tiny.order_payload(payload, known[0]['id'] if known else 0), ensure_ascii=False, indent=2))
|
||||
out(json.dumps(tiny.order_payload(payload, known[0]['id'] if known else 0, product_id=orders.product_id),
|
||||
ensure_ascii=False, indent=2))
|
||||
if not confirm:
|
||||
out('Nada foi criado. Repita com --confirmar para criar este pedido no Tiny.')
|
||||
return None
|
||||
@@ -124,6 +135,7 @@ def main(argv=None, orders=None, out=print):
|
||||
order.add_argument('--email', required=True)
|
||||
order.add_argument('--celular', required=True)
|
||||
order.add_argument('--modo', choices=sorted(tiny.PRODUCT_SETTINGS), default='file')
|
||||
order.add_argument('--metros', default='1', help='metragem cobrada, em passos de 10 cm (ex.: 1.3)')
|
||||
order.add_argument('--confirmar', action='store_true')
|
||||
args = parser.parse_args(argv)
|
||||
if orders is None:
|
||||
@@ -142,7 +154,14 @@ def main(argv=None, orders=None, out=print):
|
||||
if len(cnpj) != 14:
|
||||
out('Informe um CNPJ com 14 dígitos.')
|
||||
return 2
|
||||
payload = test_order(cnpj, args.email, args.celular, args.modo)
|
||||
try:
|
||||
metres = Decimal(args.metros.replace(',', '.'))
|
||||
except InvalidOperation:
|
||||
metres = Decimal(0)
|
||||
if metres < 1 or (metres * 10) % 1:
|
||||
out('Informe a metragem a partir de 1 m, em passos de 10 cm (ex.: 1.3).')
|
||||
return 2
|
||||
payload = test_order(cnpj, args.email, args.celular, args.modo, metres=str(metres))
|
||||
return 0 if pedido(orders, payload, args.confirmar, out) is not False else 1
|
||||
except tiny.TinyError as exc:
|
||||
out(f'Tiny: {exc}')
|
||||
|
||||
Reference in New Issue
Block a user