diff --git a/app/tiny.py b/app/tiny.py index b6b0751..3700084 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -100,6 +100,12 @@ PICKUP_EXACT = 'retirar pessoalmente' # DropStar carrier its pickup orders name. RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722} PICKUP_CARRIER = 761565838 +# Dropstar's answers (2026-10-21): the store's financial category "DUPLICADO +# DROP" (it goes in pagamento.categoria), no seller (the team links one in +# Tiny), and the marcador KANBANDTF, added after the order is created: POST +# /pedidos does not take marcadores. +CATEGORY = 965775137 +TAG = 'KANBANDTF' # Freight is the sender's (CIF), as on the store's orders. FREIGHT_PAID_BY = 'R' # The forma de envio each delivery service uses, by name; a Correios service @@ -460,12 +466,13 @@ def order_payload(payload, contact_id, today=None, product_id=None, shipping=Non if days is not None: pedido['dataPrevista'] = business_days_after(day, int(days)).isoformat() # Paid at once, in full, as the store's orders: one parcel on the day. + pedido['pagamento'] = {'categoria': {'id': CATEGORY}} received = RECEIPT_METHODS.get((payload.get('payment') or {}).get('method')) if received: total = money(order['total_cents']) - pedido['pagamento'] = {'formaRecebimento': {'id': received}, - 'parcelas': [{'dias': 0, 'data': day.isoformat(), 'valor': total, - 'formaRecebimento': {'id': received}}]} + pedido['pagamento'].update({'formaRecebimento': {'id': received}, + 'parcelas': [{'dias': 0, 'data': day.isoformat(), 'valor': total, + 'formaRecebimento': {'id': received}}]}) destination = order.get('destination') if destination: pedido['enderecoEntrega'] = {**address(destination), 'enderecoNro': destination['number'], @@ -660,6 +667,16 @@ class TinyOrders: return detail return None + def tag(self, tiny_id, known=False): + """The KANBANDTF marcador on the order, once. A retry that finds the + order already created checks first, since POST adds another.""" + if known: + have = self.request('GET', f'/pedidos/{tiny_id}/marcadores') + have = have if isinstance(have, list) else have.get('itens') or [] + if any(str(m.get('descricao', '')).strip().upper() == TAG for m in have): + return + self.request('POST', f'/pedidos/{tiny_id}/marcadores', json=[{'descricao': TAG}]) + def set_situacao(self, tiny_id, situacao): self.request('PUT', f'/pedidos/{tiny_id}/situacao', json={'situacao': situacao}) @@ -695,6 +712,10 @@ class TinyOrders: 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 + # Tagged before it is approved, so a failure here is retried while the order is still open. + if situacao == ABERTA: + self.tag(tiny_id, known=bool(existing)) + receipt['marcador'] = TAG if status_updates() and situacao == ABERTA: self.set_situacao(tiny_id, APROVADA) receipt['situacao'] = SITUACOES[APROVADA] diff --git a/app/tiny_probe.py b/app/tiny_probe.py index b866cc7..10ef09f 100644 --- a/app/tiny_probe.py +++ b/app/tiny_probe.py @@ -180,6 +180,7 @@ def pedido(orders, payload, confirm, out, wait=time.sleep): out(json.dumps(tiny.order_payload(payload, known[0]['id'] if known else 0, product_id=orders.product_id, shipping=orders.shipping), ensure_ascii=False, indent=2)) + out(f'Marcador: {tiny.TAG} (incluĂ­do logo depois de criar o pedido)') if not confirm: out('Nada foi criado. Repita com --confirmar para criar este pedido no Tiny.') return None diff --git a/tests/test_tiny.py b/tests/test_tiny.py index f0d1957..f4c6bde 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -49,6 +49,8 @@ class FakeTinyCase(unittest.TestCase): self.orders = [] self.calls = [] self.refuse_status = 0 + self.refuse_tag = 0 + self.tags = {} self.methods = {'77': {'id': 77, 'nome': 'Retirar pessoalmente', 'tipo': '6', 'formasFrete': [{'id': 771, 'nome': 'Retirar em loja'}]}, '78': {'id': 78, 'nome': 'Correios', 'tipo': '1', @@ -94,8 +96,15 @@ class FakeTinyCase(unittest.TestCase): if request.method == 'GET' and path == '/pedidos': return httpx.Response(200, json={'itens': [{'id': o['id'], 'numeroPedido': o['numeroPedido']} for o in self.orders]}) - if request.method == 'GET' and path.endswith('/marcadores'): - return httpx.Response(200, json=[{'descricao': 'SITE DTF'}]) + if path.startswith('/pedidos/') and path.endswith('/marcadores'): + wanted = int(path.split('/')[2]) + if request.method == 'GET': + return httpx.Response(200, json=self.tags.get(wanted, [])) + if self.refuse_tag: + self.refuse_tag -= 1 + return httpx.Response(503, text='indisponĂ­vel') + self.tags.setdefault(wanted, []).extend(json.loads(request.content)) + return httpx.Response(204) if request.method == 'GET' and path.startswith('/pedidos/'): wanted = int(path.rsplit('/', 1)[-1]) return httpx.Response(200, json=next(o for o in self.orders if o['id'] == wanted)) @@ -306,7 +315,7 @@ class TinyStatusTests(FakeTinyCase): def test_orders_are_filled_in_as_the_store_s_own(self): from datetime import date - from app.tiny import PICKUP_CARRIER, RECEIPT_METHODS + from app.tiny import CATEGORY, PICKUP_CARRIER, RECEIPT_METHODS thursday = date(2026, 9, 24) with mock.patch.dict(os.environ, {'FREIGHT_PRODUCTION_DAYS': '1'}): pickup = order_payload({**PICKUP, 'payment': {'method': 'pix'}}, 1, thursday, shipping=self.tiny.shipping) @@ -314,7 +323,7 @@ class TinyStatusTests(FakeTinyCase): self.assertEqual(pickup['transportador'], {'fretePorConta': 'R', 'id': PICKUP_CARRIER, 'formaEnvio': {'id': 77}, 'formaFrete': {'id': 771}}) self.assertEqual(pickup['dataPrevista'], '2026-09-25') - self.assertEqual(pickup['pagamento'], {'formaRecebimento': {'id': RECEIPT_METHODS['pix']}, + self.assertEqual(pickup['pagamento'], {'categoria': {'id': CATEGORY}, 'formaRecebimento': {'id': RECEIPT_METHODS['pix']}, 'parcelas': [{'dias': 0, 'data': '2026-09-24', 'valor': 84.72, 'formaRecebimento': {'id': RECEIPT_METHODS['pix']}}]}) # Delivery: the Correios contract's PAC or SEDEX, or Jadlog; the date in working days. for service, method, frete in (('pac', 78, 781), ('sedex', 78, 782), ('jadlog', 80, 801)): @@ -327,10 +336,32 @@ class TinyStatusTests(FakeTinyCase): self.assertEqual(sent['pagamento']['formaRecebimento'], {'id': RECEIPT_METHODS['card']}) # Looked up once per service. self.assertEqual(self.calls.count(('GET', '/formas-envio/78')), 2) - # A test order, or a carrier Tiny does not have: the order still goes, without them. + # A test order, or a carrier Tiny does not have: the order still goes, without them, + # in the store's category all the same, and with no seller: the team links one in Tiny. plain = order_payload(PAID, 1, thursday, shipping=self.tiny.shipping) self.assertNotIn('transportador', plain) - self.assertNotIn('pagamento', plain) + self.assertEqual(plain['pagamento'], {'categoria': {'id': CATEGORY}}) + self.assertNotIn('vendedor', plain) + + def test_the_order_is_tagged_kanbandtf_once(self): + first = self.tiny.deliver('k1', PAID) + self.assertEqual(first['marcador'], 'KANBANDTF') + tiny_id = self.orders[0]['id'] + self.assertEqual(self.tags[tiny_id], [{'descricao': 'KANBANDTF'}]) + # A second delivery finds the order and its tag, and adds nothing. + self.tiny.deliver('k1', PAID) + self.assertEqual(len(self.orders), 1) + self.assertEqual(self.tags[tiny_id], [{'descricao': 'KANBANDTF'}]) + + def test_a_failed_tag_is_retried_without_a_second_order(self): + self.refuse_tag = 1 + with self.assertRaises(TinyError): + self.tiny.deliver('k1', PAID) + self.assertEqual(len(self.orders), 1) + retry = self.tiny.deliver('k1', PAID) + self.assertEqual((retry['status'], retry['marcador']), ('already-created', 'KANBANDTF')) + self.assertEqual(len(self.orders), 1) + self.assertEqual(self.tags[self.orders[0]['id']], [{'descricao': 'KANBANDTF'}]) def test_pickup_forma_de_envio_is_found_by_name(self): from app.tiny import check, find_pickup @@ -539,6 +570,8 @@ class TinyProbeTests(FakeTinyCase): self.assertEqual(code, 0) self.assertIn('"numeroOrdemCompra": "DTF-TESTE-', text) self.assertIn('Nada foi criado', text) + self.assertIn('"categoria": {', text) + self.assertIn('Marcador: KANBANDTF', text) self.assertEqual(self.orders, []) self.assertTrue(all(method == 'GET' for method, _ in self.calls))