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
|
||||
|
||||
Reference in New Issue
Block a user