diff --git a/app/tiny.py b/app/tiny.py index a76a0e2..9c85729 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -55,6 +55,13 @@ STEP_SETTINGS = {'file': 'TINY_SKU10_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU10_TEXTIL 'uvfile': 'TINY_SKU10_UV_FOLHA', 'uv': 'TINY_SKU10_UV_AVULSA'} METRE_SETTINGS = {'file': 'TINY_SKU_METRO_TEXTIL_FOLHA', 'avulsa': 'TINY_SKU_METRO_TEXTIL_AVULSA', 'uvfile': 'TINY_SKU_METRO_UV_FOLHA', 'uv': 'TINY_SKU_METRO_UV_AVULSA'} +# Dropstar's own catalogue (checked against its Tiny export, 2026-10-14): Têxtil +# as DTFIMP.TX.100CM per metre and DTFIMP.TX.0010CM to 0090CM for the rest, UV +# as DTFIMP.UV.1MT per metre and DTFIMP.UV.010CM per 10 cm, the ready sheet and +# loose artwork alike. The settings above only override these. +SKU_DEFAULTS = {'file': 'DTFIMP.TX', 'avulsa': 'DTFIMP.TX'} +STEP_DEFAULTS = {'uvfile': 'DTFIMP.UV.010CM', 'uv': 'DTFIMP.UV.010CM'} +METRE_DEFAULTS = {'uvfile': 'DTFIMP.UV.1MT', 'uv': 'DTFIMP.UV.1MT'} 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', @@ -72,9 +79,11 @@ SITUACOES = {0: 'Aberta', 3: 'Aprovada', 4: 'Preparando envio', 1: 'Faturada', 7 # designer message for DTFIMP products on "Aprovado", setting it would reach # Site customers. STATUS_UPDATES_SETTING = 'TINY_STATUS_UPDATES' -# The id of the client's custom "retirar pessoalmente" forma de envio (v2 code -# X), which the pickup notice is keyed on. Find it with the console tool. +# The client's custom "retirar pessoalmente" forma de envio (v2 code X), which +# the pickup notice is keyed on. Found in Tiny by name; this setting, an id, +# only overrides that. PICKUP_SETTING = 'TINY_FORMA_ENVIO_RETIRADA' +PICKUP_NAME = 'retir' 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. @@ -110,17 +119,25 @@ def required_settings(): setting for mode, setting in PRODUCT_SETTINGS.items() if not (sku_prefix(mode) or step_sku(mode))] +# The stack passes every setting, empty when unset, so empty means "the +# default". A setting given for a mode replaces its default, in either form. +def setting(name): + return os.environ.get(name, '').strip() + + def sku_prefix(mode): - return os.environ.get(SKU_SETTINGS[mode], '').strip() + return setting(SKU_SETTINGS[mode]) or ('' if setting(STEP_SETTINGS[mode]) else SKU_DEFAULTS.get(mode, '')) def step_sku(mode): - return os.environ.get(STEP_SETTINGS[mode], '').strip() + return setting(STEP_SETTINGS[mode]) or ('' if setting(SKU_SETTINGS[mode]) else STEP_DEFAULTS.get(mode, '')) def metre_sku(mode): """The metre SKU paired with a 10 cm SKU, or '' when the 10 cm one goes alone.""" - return os.environ.get(METRE_SETTINGS[mode], '').strip() if step_sku(mode) else '' + if not step_sku(mode): + return '' + return setting(METRE_SETTINGS[mode]) or ('' if setting(STEP_SETTINGS[mode]) else METRE_DEFAULTS.get(mode, '')) def mode_codes(mode): @@ -363,7 +380,7 @@ def address(destination): 'uf': destination['state'], 'pais': 'Brasil'} -def order_payload(payload, contact_id, today=None, product_id=None): +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.""" order = payload['order'] @@ -399,7 +416,8 @@ def order_payload(payload, contact_id, today=None, product_id=None): '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, '') - if pickup and pickup_method.isdigit(): + pickup_method = int(pickup_method) if pickup_method.isdigit() else pickup_id + if pickup and pickup_method: pedido['transportador'] = {'formaEnvio': {'id': int(pickup_method)}} destination = order.get('destination') if destination: @@ -435,17 +453,29 @@ def configured_skus(orders, mode): return 'ok' if not missing else 'SKU não encontrado entre os produtos ativos: ' + ', '.join(missing) +def find_pickup(orders): + """The one forma de envio named like "retirar", or why there is not one.""" + found = orders.request('GET', '/formas-envio', params={'nome': PICKUP_NAME, 'limit': 100}).get('itens') or [] + named = [f for f in found if PICKUP_NAME in str(f.get('nome', '')).lower()] + if len(named) == 1: + return named[0], 'ok' + if not named: + return None, 'nenhuma forma de envio com "retir" no nome no Tiny' + return None, 'mais de uma forma de envio com "retir" no nome: ' + ', '.join( + f"{f.get('nome')} ({f.get('id')})" for f in named) + f'; escolha uma em {PICKUP_SETTING}' + + def configured_pickup(orders): - """The forma de envio the pickup setting points at, or why it cannot be used.""" + """The forma de envio used for pickup orders, or why there is none.""" value = os.environ.get(PICKUP_SETTING, '') - if not value.isdigit(): - return None, f'{PICKUP_SETTING} sem id' - return orders.request('GET', f'/formas-envio/{value}'), 'ok' + if value.isdigit(): + return orders.request('GET', f'/formas-envio/{value}'), 'ok' + return find_pickup(orders) def check(auth=None, transport=None, orders=None): """Read-only proof that the connection and permissions work: one order and - one contact listed, each configured product found active and the pickup + one contact listed, each product's SKUs found active and the pickup forma de envio found, nothing created. Raises TinyNotConnected when there is no usable connection; otherwise reports each read separately.""" orders = orders or TinyOrders(auth=auth or TinyAuth(), transport=transport) @@ -483,6 +513,7 @@ class TinyOrders: self.http = httpx.Client(base_url=API, transport=transport, timeout=30) self.today = today self.skus = {} + self.pickup = None # The company's names by CNPJ, for new contacts (app.cnpj.company). self.names = names @@ -495,6 +526,14 @@ 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 product_id(self, code): """The id of the active product with this SKU code, remembered once found.""" if code not in self.skus: @@ -559,8 +598,10 @@ 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, - product_id=self.product_id)) + 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)) 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 2825447..2558b74 100644 --- a/app/tiny_probe.py +++ b/app/tiny_probe.py @@ -104,7 +104,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, product_id=orders.product_id), + out(json.dumps(tiny.order_payload(payload, known[0]['id'] if known else 0, product_id=orders.product_id, + pickup_id=orders.pickup_id()), ensure_ascii=False, indent=2)) if not confirm: out('Nada foi criado. Repita com --confirmar para criar este pedido no Tiny.') diff --git a/docker-compose.yml b/docker-compose.yml index 139fb72..b8efbaf 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -72,6 +72,9 @@ x-app-environment: &app-environment TINY_CLIENT_ID: ${TINY_CLIENT_ID:-} TINY_CLIENT_SECRET: ${TINY_CLIENT_SECRET:-} TINY_REDIRECT_URI: ${TINY_REDIRECT_URI:-} + # Products, SKUs and the pickup forma de envio need no settings: the SKUs are + # Dropstar's catalogue (DTFIMP.TX…, DTFIMP.UV.1MT, DTFIMP.UV.010CM) and the + # pickup is found in Tiny by its name. These only override them. TINY_PRODUCT_TEXTIL_FOLHA: ${TINY_PRODUCT_TEXTIL_FOLHA:-} TINY_PRODUCT_TEXTIL_AVULSA: ${TINY_PRODUCT_TEXTIL_AVULSA:-} TINY_PRODUCT_UV_FOLHA: ${TINY_PRODUCT_UV_FOLHA:-} diff --git a/tests/test_tiny.py b/tests/test_tiny.py index 6669ee9..d270a64 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -28,6 +28,13 @@ PICKUP = {**PAID, 'order': {**PAID['order'], 'destination': None, 'freight': {'s READY = {'order_id': PAID['order_id'], 'number': 42, 'event': 'ready', 'reason': '', 'order': PICKUP['order']} +def product_ids(cls): + """These tests sell by product id: without Dropstar's SKU defaults.""" + for name in ('SKU_DEFAULTS', 'STEP_DEFAULTS', 'METRE_DEFAULTS'): + cls = mock.patch.dict(f'app.tiny.{name}', {}, clear=True)(cls) + return cls + + class FakeAuth: def access_token(self): return 'access-1' @@ -95,6 +102,7 @@ class FakeTinyCase(unittest.TestCase): today=date(2026, 9, 24)) +@product_ids @mock.patch.dict(os.environ, PRODUCTS) class TinyTests(FakeTinyCase): def test_payload_carries_contact_products_address_and_freight(self): @@ -170,6 +178,7 @@ class TinyTests(FakeTinyCase): tiny.deliver('k4', PAID) +@product_ids @mock.patch.dict(os.environ, PRODUCTS) class TinyStatusTests(FakeTinyCase): """Situações that the client's Tiny -> n8n notices turn into WhatsApp messages.""" @@ -249,11 +258,23 @@ class TinyStatusTests(FakeTinyCase): with mock.patch.dict(os.environ, {'TINY_FORMA_ENVIO_RETIRADA': ''}): self.assertNotIn('transportador', order_payload(PICKUP, 1)) + def test_pickup_forma_de_envio_is_found_by_name(self): + from app.tiny import check + 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(check(orders=self.tiny)['forma de envio de retirada'], 'ok') + self.methods['79'] = {'id': 79, 'nome': 'Retirada na loja', 'tipo': '6'} + self.assertIn('mais de uma', check(orders=self.tiny)['forma de envio de retirada']) + del self.methods['77'], self.methods['79'] + self.assertIn('nenhuma', check(orders=self.tiny)['forma de envio de retirada']) + TEXTIL = {**PAID, 'order': {**PAID['order'], 'items': [ {'mode': 'file', 'grade': 100, 'billed_metres': '2.8', 'unit_cents': 1490, 'total_cents': 4172}]}} +@product_ids @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.""" @@ -318,6 +339,7 @@ UV = {**PAID, 'order': {**PAID['order'], 'items': [ {'mode': 'uvfile', 'grade': 100, 'billed_metres': '2.3', 'unit_cents': 6990, 'total_cents': 16077}]}} +@product_ids @mock.patch.dict(os.environ, {**PRODUCTS, 'TINY_SKU10_UV_FOLHA': 'DTFIMP.UV.010CM'}) class TinyStepSkuTests(FakeTinyCase): """UV sold as one SKU per 10 cm, the only UV SKU the client has.""" @@ -346,6 +368,7 @@ class TinyStepSkuTests(FakeTinyCase): self.assertIn('DTFIMP.UV.010CM', check(orders=self.tiny)['DTF UV 28,5 cm · folha montada']) +@product_ids @mock.patch.dict(os.environ, {**PRODUCTS, 'TINY_SKU10_UV_FOLHA': 'DTFIMP.UV.010CM', 'TINY_SKU_METRO_UV_FOLHA': 'DTFIMP.UV.1MT'}) class TinyMetreAndStepSkuTests(FakeTinyCase): @@ -372,6 +395,7 @@ class TinyMetreAndStepSkuTests(FakeTinyCase): self.assertIn('DTFIMP.UV.1MT', check(orders=self.tiny)['DTF UV 28,5 cm · folha montada']) +@product_ids @mock.patch.dict(os.environ, PRODUCTS) class TinyProbeTests(FakeTinyCase): """The supervised console tool run against the fake Tiny.""" @@ -424,5 +448,23 @@ class TinyProbeTests(FakeTinyCase): self.assertIn('o 2º envio não foi feito', lines[-1]) +class DefaultSkuTests(unittest.TestCase): + """Dropstar's catalogue needs no settings; a setting replaces a default.""" + + def test_defaults_and_overrides(self): + from app import tiny + empty = {name: '' for name in [*tiny.SKU_SETTINGS.values(), *tiny.STEP_SETTINGS.values(), + *tiny.METRE_SETTINGS.values(), *tiny.PRODUCT_SETTINGS.values()]} + with mock.patch.dict(os.environ, empty): + self.assertEqual(tiny.mode_codes('file'), tiny.sku_codes('DTFIMP.TX')) + self.assertEqual(tiny.mode_codes('avulsa'), tiny.sku_codes('DTFIMP.TX')) + self.assertEqual(tiny.mode_codes('uv'), ['DTFIMP.UV.1MT', 'DTFIMP.UV.010CM']) + self.assertEqual(tiny.required_settings(), ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI']) + with mock.patch.dict(os.environ, {'TINY_SKU10_UV_FOLHA': 'UV.X'}): + self.assertEqual(tiny.mode_codes('uvfile'), ['UV.X']) + with mock.patch.dict(os.environ, {'TINY_SKU_UV_FOLHA': 'UV.P'}): + self.assertEqual(tiny.mode_codes('uvfile'), tiny.sku_codes('UV.P')) + + if __name__ == '__main__': unittest.main()