From e81b2b1681b8ef7fa7a527f55a282ff724fde2da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Mon, 5 Oct 2026 10:46:07 -0300 Subject: [PATCH] feat: a Tiny order can be the client's own SKUs per length, 1 metro plus the rest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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_ 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 --- app/tiny.py | 88 +++++++++++++++++++++++++++++++++++++++++---- app/tiny_probe.py | 33 +++++++++++++---- compose.local.yaml | 4 +++ docker-compose.yml | 4 +++ docs/LOCAL_SETUP.md | 5 +++ docs/ROADMAP.md | 13 +++++++ tests/test_tiny.py | 64 +++++++++++++++++++++++++++++++++ 7 files changed, 197 insertions(+), 14 deletions(-) diff --git a/app/tiny.py b/app/tiny.py index 042c9f9..f62e2bc 100644 --- a/app/tiny.py +++ b/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-", 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 diff --git a/app/tiny_probe.py b/app/tiny_probe.py index 90f806e..4463ea1 100644 --- a/app/tiny_probe.py +++ b/app/tiny_probe.py @@ -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}') diff --git a/compose.local.yaml b/compose.local.yaml index 4d25d3f..eaab0d5 100644 --- a/compose.local.yaml +++ b/compose.local.yaml @@ -58,6 +58,10 @@ x-app: &app TINY_PRODUCT_TEXTIL_AVULSA: ${TINY_PRODUCT_TEXTIL_AVULSA:-} TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-} TINY_PRODUCT_UV_AVULSA: ${TINY_PRODUCT_UV_AVULSA:-} + TINY_SKU_TEXTIL_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-} + TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-} + TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-} + TINY_SKU_UV_AVULSA: ${TINY_SKU_UV_AVULSA:-} TINY_ECOMMERCE_ID: ${TINY_ECOMMERCE_ID:-} WHATSAPP_ADAPTER: fake STORAGE_ADAPTER: s3-local diff --git a/docker-compose.yml b/docker-compose.yml index 53ce1e0..86b5241 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -72,6 +72,10 @@ x-app-environment: &app-environment TINY_PRODUCT_TEXTIL_AVULSA: ${TINY_PRODUCT_TEXTIL_AVULSA:-} TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-} TINY_PRODUCT_UV_AVULSA: ${TINY_PRODUCT_UV_AVULSA:-} + TINY_SKU_TEXTIL_FOLHA: ${TINY_SKU_TEXTIL_FOLHA:-} + TINY_SKU_TEXTIL_AVULSA: ${TINY_SKU_TEXTIL_AVULSA:-} + TINY_SKU_UV_FOLHA: ${TINY_SKU_UV_FOLHA:-} + TINY_SKU_UV_AVULSA: ${TINY_SKU_UV_AVULSA:-} # The client's "retirar pessoalmente" forma de envio id, on pickup orders. TINY_FORMA_ENVIO_RETIRADA: ${TINY_FORMA_ENVIO_RETIRADA:-} # Sets "Aprovada" on paid orders and "Pronto para envio" on finished pickup diff --git a/docs/LOCAL_SETUP.md b/docs/LOCAL_SETUP.md index ac67949..a132e2d 100644 --- a/docs/LOCAL_SETUP.md +++ b/docs/LOCAL_SETUP.md @@ -309,6 +309,11 @@ TINY_PRODUCT_TEXTIL_FOLHA=... # Tiny product id for each Site product TINY_PRODUCT_TEXTIL_AVULSA=... TINY_PRODUCT_UV_FOLHA=... TINY_PRODUCT_UV_AVULSA=... +TINY_SKU_TEXTIL_FOLHA=DTFIMP.TX # optional, instead of the product id: sell by the client's + # SKUs (.100CM per metre + .0010CM … .0090CM) +TINY_SKU_TEXTIL_AVULSA= # same, for the other modes, once their SKUs are confirmed +TINY_SKU_UV_FOLHA= +TINY_SKU_UV_AVULSA= ``` With the client ID and secret set, the Kanban header shows **Conectar Tiny**. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 7b90b28..bff0888 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -352,6 +352,19 @@ From the report already sent. These are dated promises, not backlog. the two Têxtil modes; UV needs a product either way. The item note already carries the Site mode and grade. No product ids are set in production yet; both questions go to the client with the Mercado Pago credentials request. + **SKUs (2026-10-05):** the client answered that the products already exist + and an order is a sum of SKUs (1,30 m = `DTFIMP.TX.100CM` + `DTFIMP.TX.0030CM`); + the contact permission is no longer an issue (the user, 2026-09-28). + `TINY_SKU_` (e.g. `TINY_SKU_TEXTIL_FOLHA=DTFIMP.TX`) sells a mode as + N × `.100CM` plus one `.00X0CM`, at the price the customer + paid (the client agreed), the last line taking what is left of the item's + total so the order adds up to the cent. Codes are looked up by `codigo` + (exact match on `sku`, active only) and remembered; "Testar conexão" and + `tiny_probe conferir` check all ten. Assumed, to confirm with the client: + above 1 m it is always N × "1 metro", not the 2–10 m SKUs. UV (only + `DTFIMP.UV.010CM` seen) and artes avulsas stay on a product id per metre + until their SKUs are confirmed. Fake transport only; whether v3's `/produtos` + filters by `codigo` is checked by `conferir` on the account. **Customer notices through Tiny (2026-09-25, Week 3 head start):** the client already sends WhatsApp notices from Tiny's order situação (Tiny webhook -> the `api-tiny-n8n` middleware, which reads the order through API v2 -> n8n diff --git a/tests/test_tiny.py b/tests/test_tiny.py index 67ff19f..2751c81 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -240,6 +240,70 @@ class TinyStatusTests(FakeTinyCase): self.assertNotIn('transportador', order_payload(PICKUP, 1)) +TEXTIL = {**PAID, 'order': {**PAID['order'], 'items': [ + {'mode': 'file', 'grade': 100, 'billed_metres': '2.8', 'unit_cents': 1490, 'total_cents': 4172}]}} + + +@mock.patch.dict(os.environ, {**PRODUCTS, 'TINY_SKU_TEXTIL_FOLHA': 'DTFIMP.TX'}) +class TinySkuTests(FakeTinyCase): + """Têxtil folha sold as the client's SKUs: 1 metro plus 10 to 90 cm.""" + + def setUp(self): + super().setUp() + skus = {'DTFIMP.TX.100CM': 200, **{f'DTFIMP.TX.{cm:04d}CM': 200 + cm // 10 for cm in range(10, 100, 10)}, + # Same family, different product: must never be taken for 10 cm. + 'DTFIMP.TX.010CM': 299} + for code, pid in skus.items(): + self.products[str(pid)] = {'id': pid, 'sku': code, 'descricao': code, 'situacao': 'A'} + + def test_metres_become_metre_skus_plus_one_centimetre_sku_at_the_price_paid(self): + self.tiny.deliver('k1', TEXTIL) + lines = [(i['produto']['id'], i['quantidade'], i['valorUnitario']) for i in self.orders[0]['itens']] + # 2,80 m at R$ 14,90: 2 × "1 metro" + 1 × "80 cm", adding up to R$ 41,72. + self.assertEqual(lines, [(200, 2, 14.9), (208, 1, 11.92)]) + self.assertAlmostEqual(sum(q * v for _, q, v in lines), 41.72) + self.assertIn('2.8 m', self.orders[0]['itens'][0]['infoAdicional']) + # Each code is looked up once, then remembered. + self.tiny.deliver('k2', {**TEXTIL, 'number': 43}) + self.assertEqual(self.calls.count(('GET', '/produtos')), 2) + + def test_whole_metres_and_small_rests(self): + from app.tiny import sku_lines + item = lambda metres: {'billed_metres': metres, 'unit_cents': 1990} + self.assertEqual(sku_lines(item('1'), 'P'), [('P.100CM', 1, 1990)]) + self.assertEqual(sku_lines(item('1.3'), 'P'), [('P.100CM', 1, 1990), ('P.0030CM', 1, 597)]) + self.assertEqual(sku_lines(item('12.4'), 'P'), [('P.100CM', 12, 1990), ('P.0040CM', 1, 796)]) + with self.assertRaises(TinyError): + sku_lines(item('1.25'), 'P') + + def test_a_missing_sku_fails_before_the_order_is_created(self): + del self.products['208'] + with self.assertRaisesRegex(TinyError, 'DTFIMP.TX.0080CM'): + self.tiny.deliver('k3', TEXTIL) + self.assertNotIn(('POST', '/pedidos'), self.calls) + + def test_other_modes_keep_their_product_id(self): + self.tiny.deliver('k4', PAID) + self.assertEqual(self.orders[0]['itens'][0]['produto'], {'id': 102}) + + def test_settings_check_and_probe_report_the_skus(self): + from app.tiny import check, required_settings + self.assertNotIn('TINY_PRODUCT_TEXTIL_FOLHA', required_settings()) + self.assertIn('TINY_PRODUCT_TEXTIL_AVULSA', required_settings()) + self.assertEqual(check(orders=self.tiny)['DTF Têxtil 57 cm · folha montada'], 'ok') + self.products['205']['situacao'] = 'I' + self.tiny.skus.clear() + self.assertIn('DTFIMP.TX.0050CM', check(orders=self.tiny)['DTF Têxtil 57 cm · folha montada']) + from app import tiny_probe + lines = [] + tiny_probe.main(['pedido', '--cnpj', '11222333000181', '--email', 'a@example.test', + '--celular', '16999999999', '--metros', '1,3'], orders=self.tiny, out=lines.append) + text = '\n'.join(lines) + self.assertIn('"quantidade": 1', text) + self.assertIn('"valorUnitario": 4.47', text) + self.assertEqual(self.orders, []) + + @mock.patch.dict(os.environ, PRODUCTS) class TinyProbeTests(FakeTinyCase): """The supervised console tool run against the fake Tiny."""