From 87568422b4fc2504740b6b9970991864a4d3cc69 Mon Sep 17 00:00:00 2001 From: "daniel.rodrigues" Date: Tue, 18 Nov 2025 16:20:20 -0300 Subject: [PATCH] teste --- draft_mar.py | 115 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 102 insertions(+), 13 deletions(-) diff --git a/draft_mar.py b/draft_mar.py index b513a9e..0490249 100644 --- a/draft_mar.py +++ b/draft_mar.py @@ -198,6 +198,89 @@ def create_draft_temp_table(cursor): conn.rollback() raise +def clear_promo_table(cursor): + """Limpa a tabela promo""" + try: + cursor.execute("DELETE FROM [GINSENG].[dbo].[promo]") + conn.commit() + print("Tabela 'promo' limpa com sucesso.") + except Exception as e: + print(f"Erro ao limpar a tabela promo: {e}") + conn.rollback() + raise + +def process_and_insert_promo_data(store_code, response_data, cursor): + """Processa os dados da API e insere na tabela promo (baseado no Atualizar_promo.py)""" + try: + base = response_data.get('data', {}) + + # Definir os ciclos normais e EUD + cycles = { + 'normal': { + 'thirdToLastCycle': base.get('thirdToLastCycle'), + 'secondToLastCycle': base.get('secondToLastCycle'), + 'lastCycle': base.get('lastCycle'), + 'currentCycle': base.get('currentCycle'), + 'nextCycle': base.get('nextCycle'), + 'secondToNextCycle': base.get('secondToNextCycle'), + }, + 'eud': { + 'secondToNextCycleEud': base.get('secondToNextCycleEud'), + 'nextCycleEud': base.get('nextCycleEud'), + 'thirdToLastCycleEud': base.get('thirdToLastCycleEud'), + 'secondToLastCycleEud': base.get('secondToLastCycleEud'), + 'lastCycleEud': base.get('lastCycleEud'), + 'currentCycleEud': base.get('currentCycleEud'), + } + } + + products = base.get('products', []) + if not products: + return 0 + + promo_count = 0 + for product in products: + code = product.get('code') + if not code: + continue + + business_unit = product.get('businessUnit', '').upper() + ciclo_usado = cycles['eud'] if business_unit == 'EUD' else cycles['normal'] + + for promotion in product.get('promotions', []): + cycle = promotion.get('cycle') + if not cycle: + continue + + for cycle_key, cycle_value in ciclo_usado.items(): + if cycle == cycle_value: + # Inserir dados na tabela promo + product_data = { + 'loja_id': store_code, + 'code': code, + 'type': promotion.get('type'), + 'target': promotion.get('target'), + f'{cycle_key}_discountPercent': promotion.get('discountPercent'), + f'{cycle_key}_description': promotion.get('description'), + } + + # Montar query de inserção + columns = ', '.join(product_data.keys()) + placeholders = ', '.join(['?' for _ in product_data]) + query = f""" + INSERT INTO [GINSENG].[dbo].[promo] ({columns}) + VALUES ({placeholders}) + """ + cursor.execute(query, list(product_data.values())) + promo_count += 1 + + conn.commit() + return promo_count + except Exception as e: + print(f"Erro ao processar dados de promoção da loja {store_code}: {e}") + conn.rollback() + return 0 + def process_and_insert_data(store_code, response_data, cursor): """Processa os dados da API e insere na tabela draft_temp""" try: @@ -319,7 +402,7 @@ def fetch_and_insert_data(store_code, index, total, cursor, retry_count=1): store_type = "QDB" else: store_type = "BOT" - + # Dados da requisição com o código da loja data = { "storeCode": store_code, @@ -327,29 +410,32 @@ def fetch_and_insert_data(store_code, index, total, cursor, retry_count=1): "storeType": store_type, "generateNew": False } - + # Fazendo a requisição POST response = requests.post(url, headers=headers, json=data) response.raise_for_status() - + # Requisição bem-sucedida response_data = response.json() - - # Processa e insere os dados diretamente no banco + + # Processa e insere os dados na tabela draft_temp num_products = process_and_insert_data(store_code, response_data, cursor) - - print(f"{index}/{total}: Loja {store_code} processada com sucesso ({num_products} produtos inseridos).") + + # Processa e insere os dados na tabela promo + num_promos = process_and_insert_promo_data(store_code, response_data, cursor) + + print(f"{index}/{total}: Loja {store_code} processada com sucesso ({num_products} produtos inseridos, {num_promos} promoções inseridas).") return True - + except RequestException as e: print(f"{index}/{total}: Erro na requisição para a loja {store_code}: {e}") except Exception as e: print(f"{index}/{total}: Erro inesperado para a loja {store_code}: {e}") - + attempt += 1 print(f"{index}/{total}: Tentativa {attempt} de {retry_count} para a loja {store_code}.") time.sleep(5) - + print(f"{index}/{total}: Falha ao processar a loja {store_code} após {retry_count} tentativas.") return False @@ -474,13 +560,16 @@ def main(): print("Sem conexão com a internet. Verifique sua conexão e tente novamente.") update_api_status("FAIL") return - + cursor = conn.cursor() - + try: # Criar a tabela draft_temp se não existir create_draft_temp_table(cursor) - + + # Limpar a tabela promo + clear_promo_table(cursor) + failed_stores = [] total = len(store_codes)