diff --git a/app/payments.py b/app/payments.py index 586fcce..aec8040 100644 --- a/app/payments.py +++ b/app/payments.py @@ -100,9 +100,13 @@ def create_order(c, quote, payment): if is_test(order): return order, True mail.order_paid(c, order, PUBLIC_ORIGIN) + # How it was paid, for the order's payment in Tiny. + paid = c.execute('''SELECT method FROM dtf_local.payment_intents WHERE quote_id=%s AND status='approved' + ORDER BY created_at DESC LIMIT 1''', (quote['id'],)).fetchone() enqueue(c, f"{order['id']}:paid:tiny", 'tiny', {'order_id': str(order['id']), 'number': order['number'], - 'event': 'payment_approved', 'order': approved}) + 'event': 'payment_approved', 'order': approved, + 'payment': {'method': paid['method']} if paid else {}}) mail.alert(c, f"Pedido #{order['number']} pago · {mail.money(approved['total_cents'])}", ['Um pedido novo foi pago e está em Arte recebida.', '', *mail.summary(approved)], '/') return order, True diff --git a/app/tiny.py b/app/tiny.py index 8d21620..b6b0751 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -94,6 +94,17 @@ STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES' PICKUP_SETTING = 'TINY_FORMA_ENVIO_RETIRADA' PICKUP_NAME = 'retir' PICKUP_EXACT = 'retirar pessoalmente' +# Dropstar's own ids, read from its store orders with app.tiny_probe exemplo +# (2026-10-19). The app may not list formas de recebimento, so these are not +# looked up: Pix and credit card, as the store's orders are paid, and the +# DropStar carrier its pickup orders name. +RECEIPT_METHODS = {'pix': 919478952, 'card': 977460722} +PICKUP_CARRIER = 761565838 +# 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 +# is the forma de frete with its contract code (app/correios.py). +CARRIERS = {'pac': 'correios', 'sedex': 'correios', 'jadlog': 'jadlog'} STATE_MINUTES = 10 # Renewal runs about every four hours against a one-day refresh token, so # less than this left means renewals have been failing for hours. @@ -393,9 +404,20 @@ def address(destination): 'uf': destination['state'], 'pais': 'Brasil'} -def order_payload(payload, contact_id, today=None, product_id=None, pickup_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.""" +def business_days_after(day, days): + """The day `days` working days (Monday to Friday) after `day`.""" + while days > 0: + day += timedelta(days=1) + if day.weekday() < 5: + days -= 1 + return day + + +def order_payload(payload, contact_id, today=None, product_id=None, shipping=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 + frete of a delivery service or pickup.""" order = payload['order'] items = [] for item in order['items']: @@ -420,18 +442,30 @@ def order_payload(payload, contact_id, today=None, product_id=None, pickup_id=No 'valorUnitario': money(item['unit_cents']), 'infoAdicional': note}) freight = order['freight'] - pickup = freight.get('service') == 'pickup' - pedido = {'data': (today or local_today()).isoformat(), + service = freight.get('service') + pickup = service == 'pickup' + day = today or local_today() + pedido = {'data': day.isoformat(), 'idContato': contact_id, 'numeroOrdemCompra': purchase_order(payload['number']), 'itens': items, 'valorFrete': money(freight['total_cents']), 'observacoes': f"Pedido DTF #{payload['number']}" + (' · retirada em Franca' if pickup else ''), 'observacoesInternas': f"Site DTF · pago · {payload['order_id']}"} - pickup_method = os.environ.get(PICKUP_SETTING, '') - pickup_method = int(pickup_method) if pickup_method.isdigit() else pickup_id - if pickup and pickup_method: - pedido['transportador'] = {'formaEnvio': {'id': int(pickup_method)}} + carrier = shipping(service) if shipping else None + if carrier: + pedido['transportador'] = {'fretePorConta': FREIGHT_PAID_BY, **carrier} + # The carrier's time already counts production; a pickup is ready after it. + days = freight.get('days') if not pickup else int(os.environ.get('FREIGHT_PRODUCTION_DAYS') or 0) + 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. + 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}}]} destination = order.get('destination') if destination: pedido['enderecoEntrega'] = {**address(destination), 'enderecoNro': destination['number'], @@ -483,6 +517,43 @@ def find_pickup(orders): f"{f.get('nome')} ({f.get('id')})" for f in named) + f'; escolha uma em {PICKUP_SETTING}' +def find_shipping(orders, service): + """The forma de envio and de frete for a service, as {'formaEnvio': ..., + 'formaFrete': ...} (and the DropStar carrier for pickup), or None when Tiny + has no such forma de envio: the order then goes without it.""" + if service == 'pickup': + method, _ = configured_pickup(orders) + if not method: + return None + detail = orders.request('GET', f"/formas-envio/{method['id']}") + options = detail.get('formasFrete') or [] + # "Retirar em loja", as the store's pickup orders. + frete = next((f for f in options if PICKUP_NAME in str(f.get('nome', '')).lower()), options[0] if options else None) + found = {'id': PICKUP_CARRIER, 'formaEnvio': {'id': int(method['id'])}} + if frete: + found['formaFrete'] = {'id': int(frete['id'])} + return found + name = CARRIERS.get(service) + if not name: + return None + listed = orders.request('GET', '/formas-envio', params={'nome': name, 'limit': 100}).get('itens') or [] + method = next((f for f in listed if str(f.get('nome', '')).strip().lower() == name), None) + if not method: + return None + options = orders.request('GET', f"/formas-envio/{method['id']}").get('formasFrete') or [] + if name == 'correios': + from .correios import SERVICES + setting, default, _ = SERVICES[service] + code = (os.environ.get(setting) or default).strip() + frete = next((f for f in options if str(f.get('codigo', '')).strip() == code), None) + else: + frete = options[0] if options else None + found = {'formaEnvio': {'id': int(method['id'])}} + if frete: + found['formaFrete'] = {'id': int(frete['id'])} + return found + + def configured_pickup(orders): """The forma de envio used for pickup orders, or why there is none.""" value = os.environ.get(PICKUP_SETTING, '') @@ -531,7 +602,7 @@ class TinyOrders: self.http = httpx.Client(base_url=API, transport=transport, timeout=30) self.today = today self.skus = {} - self.pickup = None + self.carriers = {} # The company's names by CNPJ, for new contacts (app.cnpj.company). self.names = names @@ -544,13 +615,11 @@ class TinyOrders: raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}') return response.json() if response.content else {} - def pickup_id(self): - """The pickup forma de envio's id, looked up once; None when Tiny has no - single one (the order still goes, without it).""" - if self.pickup is None: - found, _ = configured_pickup(self) - self.pickup = (found or {}).get('id') or 0 - return self.pickup or None + def shipping(self, service): + """The forma de envio and de frete of a service, looked up once.""" + if service not in self.carriers: + self.carriers[service] = find_shipping(self, service) + return self.carriers[service] def product_id(self, code): """The id of the active product with this SKU code, remembered once found.""" @@ -621,10 +690,8 @@ class TinyOrders: tiny_id, situacao = existing.get('id'), existing.get('situacao') else: contact_id = self.contact(payload['order']) - pickup = (payload['order'].get('freight') or {}).get('service') == 'pickup' created = self.request('POST', '/pedidos', json=order_payload( - payload, contact_id, self.today, product_id=self.product_id, - pickup_id=self.pickup_id() if pickup else None)) + payload, contact_id, self.today, product_id=self.product_id, shipping=self.shipping)) 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 9cba979..b866cc7 100644 --- a/app/tiny_probe.py +++ b/app/tiny_probe.py @@ -178,7 +178,7 @@ def pedido(orders, payload, confirm, out, wait=time.sleep): out(f'Contato {cnpj}: não existe; será criado como "{name}"') out('Pedido que será enviado:') out(json.dumps(tiny.order_payload(payload, known[0]['id'] if known else 0, product_id=orders.product_id, - pickup_id=orders.pickup_id()), + shipping=orders.shipping), ensure_ascii=False, indent=2)) if not confirm: out('Nada foi criado. Repita com --confirmar para criar este pedido no Tiny.') diff --git a/tests/test_tiny.py b/tests/test_tiny.py index 8eaaf6e..f0d1957 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -49,8 +49,13 @@ class FakeTinyCase(unittest.TestCase): self.orders = [] self.calls = [] self.refuse_status = 0 - self.methods = {'77': {'id': 77, 'nome': 'Retirar pessoalmente', 'tipo': '6'}, - '78': {'id': 78, 'nome': 'Correios', 'tipo': '1'}} + self.methods = {'77': {'id': 77, 'nome': 'Retirar pessoalmente', 'tipo': '6', + 'formasFrete': [{'id': 771, 'nome': 'Retirar em loja'}]}, + '78': {'id': 78, 'nome': 'Correios', 'tipo': '1', + 'formasFrete': [{'id': 782, 'nome': 'SEDEX CONTRATO AG (03220)', 'codigo': '03220'}, + {'id': 781, 'nome': 'PAC CONTRATO AG (03298)', 'codigo': '03298'}]}, + '80': {'id': 80, 'nome': 'Jadlog', 'tipo': '7', + 'formasFrete': [{'id': 801, 'nome': '.PACKAGE', 'codigo': '3'}]}} self.products = {value: {'id': int(value), 'sku': f'DTF-{value}', 'descricao': f'Produto {value}', 'situacao': 'A', 'precos': {'preco': 14.9}} for value in PRODUCTS.values()} @@ -299,17 +304,39 @@ class TinyStatusTests(FakeTinyCase): 'not-applicable') self.assertEqual(self.calls, []) - def test_pickup_orders_carry_the_pickup_forma_de_envio(self): - self.assertEqual(order_payload(PICKUP, 1)['transportador'], {'formaEnvio': {'id': 77}}) - self.assertNotIn('transportador', order_payload(PAID, 1)) - with mock.patch.dict(os.environ, {'TINY_FORMA_ENVIO_RETIRADA': ''}): - self.assertNotIn('transportador', order_payload(PICKUP, 1)) + def test_orders_are_filled_in_as_the_store_s_own(self): + from datetime import date + from app.tiny import 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) + # Pickup: the DropStar carrier, "Retirar pessoalmente" and "Retirar em loja", ready after production. + 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']}, + '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)): + order = {**PAID['order'], 'freight': {'service': service, 'total_cents': 1500, 'days': 6}} + sent = order_payload({**PAID, 'order': order, 'payment': {'method': 'card'}}, 1, thursday, + shipping=self.tiny.shipping) + self.assertEqual(sent['transportador'], {'fretePorConta': 'R', 'formaEnvio': {'id': method}, + 'formaFrete': {'id': frete}}, service) + self.assertEqual(sent['dataPrevista'], '2026-10-02') + 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. + plain = order_payload(PAID, 1, thursday, shipping=self.tiny.shipping) + self.assertNotIn('transportador', plain) + self.assertNotIn('pagamento', plain) def test_pickup_forma_de_envio_is_found_by_name(self): from app.tiny import check, find_pickup with mock.patch.dict(os.environ, {'TINY_FORMA_ENVIO_RETIRADA': ''}): self.tiny.deliver('k1', PICKUP) - self.assertEqual(self.orders[0]['transportador'], {'formaEnvio': {'id': 77}}) + self.assertEqual(self.orders[0]['transportador']['formaEnvio'], {'id': 77}) self.assertEqual(check(orders=self.tiny)['forma de envio de retirada'], 'ok') # Dropstar's account also has "Retirar na loja": the exact name wins. self.methods['79'] = {'id': 79, 'nome': 'Retirar na loja', 'tipo': '6'}