att
This commit is contained in:
parent
a00fedd78f
commit
736016ea99
99
draft_mar.py
99
draft_mar.py
@ -353,6 +353,97 @@ def fetch_and_insert_data(store_code, index, total, cursor, retry_count=1):
|
|||||||
print(f"{index}/{total}: Falha ao processar a loja {store_code} após {retry_count} tentativas.")
|
print(f"{index}/{total}: Falha ao processar a loja {store_code} após {retry_count} tentativas.")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def finalize_tables(cursor):
|
||||||
|
"""
|
||||||
|
Finaliza o processo:
|
||||||
|
1. Exclui a tabela dbo.draft
|
||||||
|
2. Renomeia dbo.draft_temp para dbo.draft
|
||||||
|
3. Atualiza dbo.draft_historico com os dados do dia
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
print("\n=== Iniciando finalização das tabelas ===")
|
||||||
|
|
||||||
|
# Passo 1: Excluir a tabela draft se existir
|
||||||
|
print("Passo 1: Excluindo tabela dbo.draft...")
|
||||||
|
cursor.execute("""
|
||||||
|
IF EXISTS (SELECT * FROM sys.tables WHERE name = 'draft' AND schema_id = SCHEMA_ID('dbo'))
|
||||||
|
BEGIN
|
||||||
|
DROP TABLE dbo.draft
|
||||||
|
END
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
print("Tabela dbo.draft excluída com sucesso.")
|
||||||
|
|
||||||
|
# Passo 2: Renomear draft_temp para draft
|
||||||
|
print("Passo 2: Renomeando dbo.draft_temp para dbo.draft...")
|
||||||
|
cursor.execute("EXEC sp_rename 'dbo.draft_temp', 'draft'")
|
||||||
|
conn.commit()
|
||||||
|
print("Tabela renomeada com sucesso: dbo.draft_temp -> dbo.draft")
|
||||||
|
|
||||||
|
# Passo 3: Atualizar draft_historico
|
||||||
|
print("Passo 3: Atualizando dbo.draft_historico...")
|
||||||
|
|
||||||
|
# Obter a data de hoje
|
||||||
|
today = datetime.now().strftime("%Y-%m-%d")
|
||||||
|
print(f"Data de hoje: {today}")
|
||||||
|
|
||||||
|
# Verificar se já existem dados para hoje
|
||||||
|
cursor.execute("SELECT COUNT(*) FROM dbo.draft_historico WHERE CAST(data AS DATE) = ?", (today,))
|
||||||
|
count = cursor.fetchone()[0]
|
||||||
|
|
||||||
|
if count > 0:
|
||||||
|
print(f"Encontrados {count} registros para a data {today}. Excluindo...")
|
||||||
|
cursor.execute("DELETE FROM dbo.draft_historico WHERE CAST(data AS DATE) = ?", (today,))
|
||||||
|
conn.commit()
|
||||||
|
print(f"Registros da data {today} excluídos com sucesso.")
|
||||||
|
else:
|
||||||
|
print(f"Nenhum registro encontrado para a data {today}.")
|
||||||
|
|
||||||
|
# Inserir dados da tabela draft na draft_historico
|
||||||
|
print("Inserindo dados da dbo.draft na dbo.draft_historico...")
|
||||||
|
cursor.execute("""
|
||||||
|
INSERT INTO dbo.draft_historico (
|
||||||
|
loja_id, code, description, launch, deactivation,
|
||||||
|
thirdtolastcyclesales, secondtolastcyclesales, lastcyclesales,
|
||||||
|
currentcyclesales, nextcycleprojection, secondtonextcycleprojection,
|
||||||
|
stock_actual, stock_intransit, purchasesuggestion,
|
||||||
|
smartpurchase_purchasesuggestioncycle, smartpurchase_nextcyclepurchasesuggestion,
|
||||||
|
pendingorder, salescurve,
|
||||||
|
promotions_description, promotions_discountpercent,
|
||||||
|
pricesellin, businessunit, codcategory,
|
||||||
|
criticalitem_dtprovidedregularization, criticalitem_blockedwallet, criticalitem_iscritical,
|
||||||
|
codsubcategory, isproductdeactivated, brandgroupcode,
|
||||||
|
dayswithoutsales, coveragedays, hascoverage, data
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
loja_id, code, description, launch, deactivation,
|
||||||
|
thirdToLastCycleSales, secondToLastCycleSales, lastCycleSales,
|
||||||
|
currentCycleSales, nextCycleProjection, secondToNextCycleProjection,
|
||||||
|
stock_actual, stock_inTransit, purchaseSuggestion,
|
||||||
|
smartPurchase_purchaseSuggestionCycle, smartPurchase_nextCyclePurchaseSuggestion,
|
||||||
|
pendingOrder, salesCurve,
|
||||||
|
promotions_description, promotions_discountPercent,
|
||||||
|
priceSellin, businessUnit, codCategory,
|
||||||
|
criticalItem_dtProvidedRegularization, criticalItem_blockedWallet, criticalItem_isCritical,
|
||||||
|
codSubCategory, isProductDeactivated, brandGroupCode,
|
||||||
|
daysWithoutSales, coverageDays, hasCoverage, date
|
||||||
|
FROM dbo.draft
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
# Verificar quantos registros foram inseridos
|
||||||
|
cursor.execute("SELECT @@ROWCOUNT")
|
||||||
|
inserted_count = cursor.fetchone()[0]
|
||||||
|
print(f"{inserted_count} registros inseridos na dbo.draft_historico com sucesso.")
|
||||||
|
|
||||||
|
print("=== Finalização das tabelas concluída com sucesso ===\n")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Erro ao finalizar tabelas: {e}")
|
||||||
|
conn.rollback()
|
||||||
|
return False
|
||||||
|
|
||||||
def update_api_status(status):
|
def update_api_status(status):
|
||||||
"""Atualiza o status da API"""
|
"""Atualiza o status da API"""
|
||||||
try:
|
try:
|
||||||
@ -421,7 +512,11 @@ def main():
|
|||||||
failed_stores = retry_failed_stores
|
failed_stores = retry_failed_stores
|
||||||
if not failed_stores:
|
if not failed_stores:
|
||||||
print("\nTodos os arquivos foram processados com sucesso.")
|
print("\nTodos os arquivos foram processados com sucesso.")
|
||||||
|
# Finalizar tabelas antes de atualizar status
|
||||||
|
if finalize_tables(cursor):
|
||||||
update_api_status("OK")
|
update_api_status("OK")
|
||||||
|
else:
|
||||||
|
update_api_status("FAIL")
|
||||||
break
|
break
|
||||||
|
|
||||||
if failed_stores:
|
if failed_stores:
|
||||||
@ -434,7 +529,11 @@ def main():
|
|||||||
update_api_status("FAIL")
|
update_api_status("FAIL")
|
||||||
else:
|
else:
|
||||||
print("\nTodos os arquivos foram processados com sucesso.")
|
print("\nTodos os arquivos foram processados com sucesso.")
|
||||||
|
# Finalizar tabelas antes de atualizar status
|
||||||
|
if finalize_tables(cursor):
|
||||||
update_api_status("OK")
|
update_api_status("OK")
|
||||||
|
else:
|
||||||
|
update_api_status("FAIL")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Erro durante a execução: {e}")
|
print(f"Erro durante a execução: {e}")
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user