From ffc7d3153a1b51c71593c0b3fead982facce1047 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Fri, 27 Nov 2026 09:16:53 -0300 Subject: [PATCH] feat: a Tiny order goes with the seller in the customer's registration (Marcus, 2026-11-26) Tiny does not fill the seller on an order created through its API, and it cannot be set afterwards (order 151250). The existing contact's seller, from its dados complementares, now goes in the order; it wins over who assembled a montador Venda. No seller in the registration: the assembler's, or none for a Site order. A failed reading never holds the order. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/tiny.py | 31 +++++++++++++++++++++++-------- tests/test_tiny.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 8 deletions(-) diff --git a/app/tiny.py b/app/tiny.py index c5ce929..5467691 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -42,6 +42,7 @@ An order someone already moved further in Tiny is never moved back, and an invoiced one is not cancelled here (its nota fiscal is cancelled in Tiny). Pickup orders carry the client's "retirar pessoalmente" forma de envio. """ +import logging import os import secrets import time @@ -553,7 +554,7 @@ def business_days_after(day, days): return day -def order_payload(payload, contact_id, today=None, product_id=None, shipping=None): +def order_payload(payload, contact_id, today=None, product_id=None, shipping=None, contact_seller=None): """The v3 'pedido' for a paid order's approved snapshot, filled in as the store's own orders are: payment, carrier and expected date. product_id finds a SKU's product id by its code; shipping(service) the forma de envio and de @@ -625,9 +626,11 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non 'valorFrete': money(freight['total_cents']), 'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''), 'observacoesInternas': internal_note(payload)} - # No seller, so Tiny's channel sets it (Dropstar, 2026-10-23), except a - # montador Venda, whose seller is who assembled it (Marcus, 2026-11-17). - seller = (order.get('seller') or {}).get('id') + # The seller in the customer's Tiny registration (dados complementares): + # Tiny does not fill it on an order made this way, and it cannot be set + # after (Marcus, 2026-11-26). Without one, a montador Venda goes with who + # assembled it (Marcus, 2026-11-17), a Site order without. + seller = contact_seller or (order.get('seller') or {}).get('id') if seller: pedido['vendedor'] = {'id': int(seller)} coupon = order.get('coupon') or {} @@ -852,17 +855,28 @@ class TinyOrders: return None def contact(self, order): + """The customer's contact id, and the seller of an existing one.""" cnpj = order['customer']['cnpj'] known = self.find_contact(cnpj) if known: - return known + return known, self.contact_seller(known) company = None if self.names and len(cnpj) == 14: try: company = self.names(cnpj) except Exception: # a name is a nicety; the order must still go company = None - return self.request('POST', '/contatos', json=contact_payload(order, company))['id'] + return self.request('POST', '/contatos', json=contact_payload(order, company))['id'], None + + def contact_seller(self, contact_id): + """The seller (vendedor) in a contact's registration, or None. A + failed reading leaves the order without one: it must still go.""" + try: + seller = (self.request('GET', f'/contatos/{contact_id}').get('vendedor') or {}).get('id') + except TinyError as exc: + logging.warning('Tiny: could not read the seller of contact %s: %s', contact_id, exc) + return None + return int(seller) if str(seller or '').isdigit() and int(seller) > 0 else None def find(self, payload, days=SEARCH_DAYS): """An order a previous delivery already created, or None.""" @@ -921,9 +935,10 @@ class TinyOrders: 'tiny_id': str(existing.get('id')), 'tiny_number': str(existing.get('numeroPedido'))} tiny_id, situacao = existing.get('id'), existing.get('situacao') else: - contact_id = self.contact(payload['order']) + contact_id, seller = self.contact(payload['order']) created = self.request('POST', '/pedidos', json=order_payload( - payload, contact_id, self.today, product_id=self.product_id, shipping=self.shipping)) + payload, contact_id, self.today, product_id=self.product_id, shipping=self.shipping, + contact_seller=seller)) 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/tests/test_tiny.py b/tests/test_tiny.py index 5c0e7d7..cb420bf 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -51,6 +51,7 @@ class FakeTinyCase(unittest.TestCase): self.calls = [] self.refuse_status = 0 self.refuse_tag = 0 + self.refuse_contact = False self.tags = {} self.methods = {'77': {'id': 77, 'nome': 'Retirar pessoalmente', 'tipo': '6', 'formasFrete': [{'id': 771, 'nome': 'Retirar em loja'}]}, @@ -73,6 +74,11 @@ class FakeTinyCase(unittest.TestCase): if request.method == 'GET' and path == '/contatos': cnpj = request.url.params.get('cpfCnpj') return httpx.Response(200, json={'itens': [c for c in self.contacts if cnpj in (None, c['cpfCnpj'])]}) + if request.method == 'GET' and path.startswith('/contatos/'): + wanted = int(path.rsplit('/', 1)[-1]) + if self.refuse_contact: + return httpx.Response(503, text='indisponível') + return httpx.Response(200, json=next(c for c in self.contacts if c['id'] == wanted)) if request.method == 'POST' and path == '/contatos': contact = {**json.loads(request.content), 'id': 500 + len(self.contacts)} self.contacts.append(contact) @@ -240,6 +246,33 @@ class TinyTests(FakeTinyCase): self.assertEqual(self.tiny.deliver('k1', PAID)['status'], 'already-created') self.assertEqual(len(self.orders), 1) + def test_the_seller_of_an_existing_contact_goes_with_the_order(self): + # Marcus, 2026-11-26: the seller in the customer's registration + # (dados complementares); Tiny does not fill it on an API order. + self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477, 'nome': 'Lais'}}) + self.tiny.deliver('k1', PAID) + self.assertEqual(self.orders[0]['vendedor'], {'id': 977231477}) + + def test_the_registration_seller_wins_over_who_assembled_a_venda(self): + self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477}}) + venda = {**PAID, 'order': {**PAID['order'], 'seller': {'id': 2001, 'name': 'Kedma'}}} + self.tiny.deliver('k1', venda) + self.assertEqual(self.orders[0]['vendedor'], {'id': 977231477}) + + def test_without_a_registration_seller_the_assembler_or_none(self): + self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 0, 'nome': ''}}) + venda = {**PAID, 'order': {**PAID['order'], 'seller': {'id': 2001, 'name': 'Kedma'}}} + self.tiny.deliver('k1', venda) + self.assertEqual(self.orders[0]['vendedor'], {'id': 2001}) + self.tiny.deliver('k2', {**PAID, 'number': 43}) + self.assertNotIn('vendedor', self.orders[1]) + + def test_a_failed_seller_reading_does_not_hold_the_order(self): + self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477}}) + self.refuse_contact = True + self.assertEqual(self.tiny.deliver('k1', PAID)['status'], 'created') + self.assertNotIn('vendedor', self.orders[0]) + def test_a_contact_typed_without_punctuation_is_found_too(self): self.contacts.append({'id': 322, 'cpfCnpj': '11222333000181'}) self.tiny.deliver('k1', PAID)