pasquale991 commited on
Commit
1eb35b0
·
verified ·
1 Parent(s): 4f91dfe

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +21 -15
src/streamlit_app.py CHANGED
@@ -4,13 +4,14 @@ import json
4
  from datetime import datetime
5
  import io
6
  import os
7
- import pytz # Assicurati che pytz sia nel requirements.txt
8
 
9
  # --- Inizializzazione Session State ---
 
10
  if 'file_uploader_key_json' not in st.session_state:
11
- st.session_state.file_uploader_key_json = 0
12
  if 'file_uploader_key_customers' not in st.session_state:
13
- st.session_state.file_uploader_key_customers = 0
14
 
15
  # --- CSS personalizzato ---
16
  st.markdown(
@@ -94,11 +95,8 @@ def convert_json_to_excel_data_outbound(json_file_content: str, customers_df: pd
94
 
95
  # Esegui la lookup solo se customers_df è fornito e non vuoto
96
  if customers_df is not None and not customers_df.empty and customer_code and company_code_json:
97
- # Assicurati che le colonne di join siano dello stesso tipo
98
- # customers_df['Code'] = customers_df['Code'].astype(str)
99
- # customers_df['company.code'] = customers_df['company.code'].astype(str)
100
-
101
  # Filtra per Code e company.code
 
102
  customer_data = customers_df[
103
  (customers_df['Code'].astype(str) == str(customer_code)) &
104
  (customers_df['company.code'].astype(str) == str(company_code_json))
@@ -219,30 +217,27 @@ st.info("Questo file Excel deve contenere le colonne: `Code`, `company.code`, `p
219
  uploaded_customers_file = st.file_uploader(
220
  "Scegli il file Excel con i dettagli dei Clienti",
221
  type=["xlsx", "xls"],
222
- key=st.session_state.file_uploader_key_customers
223
  )
224
 
225
  customers_df = pd.DataFrame()
226
  if uploaded_customers_file:
227
  try:
228
  customers_df = pd.read_excel(uploaded_customers_file)
229
- # Rinomina le colonne per facilitare l'accesso, se necessario, o assicurati che i nomi corrispondano
230
- # Es: customers_df.rename(columns={'Codice': 'Code', 'Nome': 'partner.name'}, inplace=True)
231
  # Assicurati che le colonne per il merge siano stringhe per evitare problemi di tipo
232
  customers_df['Code'] = customers_df['Code'].astype(str)
233
  customers_df['company.code'] = customers_df['company.code'].astype(str)
234
  st.success("File Excel Clienti caricato con successo.")
235
- # Debug: st.dataframe(customers_df.head())
236
  except Exception as e:
237
  st.error(f"Errore nel caricamento del file Excel Clienti: {e}. Assicurati che sia un file Excel valido e che le colonne siano corrette.")
238
- customers_df = pd.DataFrame() # Reset in caso di errore
239
 
240
  st.header("2. Carica i tuoi file JSON degli Ordini Outbound")
241
  uploaded_json_files = st.file_uploader(
242
  "Scegli uno o più file JSON di tipo 'Ordine_Outbound'",
243
  type=["json"],
244
  accept_multiple_files=True,
245
- key=st.session_state.file_uploader_key_json
246
  )
247
 
248
  all_processed_data = []
@@ -312,6 +307,7 @@ if uploaded_json_files and not customers_df.empty:
312
  sheet_name_excel = 'OutboundOrder'
313
 
314
  workbook = writer.book
 
315
  worksheet = writer.sheets.get(sheet_name_excel)
316
  if worksheet is None:
317
  worksheet = workbook.add_worksheet(sheet_name_excel)
@@ -372,6 +368,7 @@ if uploaded_json_files and not customers_df.empty:
372
  worksheet.set_column(col_num, col_num, col_widths[col_name], date_format)
373
 
374
  # Scrivi i dati a partire dalla riga 3 (indice 2 in xlsxwriter)
 
375
  final_df.to_excel(writer, sheet_name=sheet_name_excel, index=False, header=False, startrow=2)
376
 
377
  writer.close()
@@ -395,8 +392,17 @@ if uploaded_json_files and not customers_df.empty:
395
 
396
  # --- Funzione per il reset ---
397
  def clear_inputs():
398
- st.session_state.file_uploader_key_json += 1
399
- st.session_state.file_uploader_key_customers += 1
 
 
 
 
 
 
 
 
 
400
 
401
  st.markdown("---")
402
  st.button("Pulisci Input (RESET)", on_click=clear_inputs)
 
4
  from datetime import datetime
5
  import io
6
  import os
7
+ import pytz
8
 
9
  # --- Inizializzazione Session State ---
10
+ # Chiavi uniche per i file uploader per evitare DuplicateWidgetID
11
  if 'file_uploader_key_json' not in st.session_state:
12
+ st.session_state.file_uploader_key_json = 'json_uploader_0' # Chiave unica
13
  if 'file_uploader_key_customers' not in st.session_state:
14
+ st.session_state.file_uploader_key_customers = 'customers_uploader_0' # Chiave unica
15
 
16
  # --- CSS personalizzato ---
17
  st.markdown(
 
95
 
96
  # Esegui la lookup solo se customers_df è fornito e non vuoto
97
  if customers_df is not None and not customers_df.empty and customer_code and company_code_json:
 
 
 
 
98
  # Filtra per Code e company.code
99
+ # Assicurati che le colonne di join siano dello stesso tipo, convertendo a str
100
  customer_data = customers_df[
101
  (customers_df['Code'].astype(str) == str(customer_code)) &
102
  (customers_df['company.code'].astype(str) == str(company_code_json))
 
217
  uploaded_customers_file = st.file_uploader(
218
  "Scegli il file Excel con i dettagli dei Clienti",
219
  type=["xlsx", "xls"],
220
+ key=st.session_state.file_uploader_key_customers # Usa la chiave unica
221
  )
222
 
223
  customers_df = pd.DataFrame()
224
  if uploaded_customers_file:
225
  try:
226
  customers_df = pd.read_excel(uploaded_customers_file)
 
 
227
  # Assicurati che le colonne per il merge siano stringhe per evitare problemi di tipo
228
  customers_df['Code'] = customers_df['Code'].astype(str)
229
  customers_df['company.code'] = customers_df['company.code'].astype(str)
230
  st.success("File Excel Clienti caricato con successo.")
 
231
  except Exception as e:
232
  st.error(f"Errore nel caricamento del file Excel Clienti: {e}. Assicurati che sia un file Excel valido e che le colonne siano corrette.")
233
+ customers_df = pd.DataFrame()
234
 
235
  st.header("2. Carica i tuoi file JSON degli Ordini Outbound")
236
  uploaded_json_files = st.file_uploader(
237
  "Scegli uno o più file JSON di tipo 'Ordine_Outbound'",
238
  type=["json"],
239
  accept_multiple_files=True,
240
+ key=st.session_state.file_uploader_key_json # Usa la chiave unica
241
  )
242
 
243
  all_processed_data = []
 
307
  sheet_name_excel = 'OutboundOrder'
308
 
309
  workbook = writer.book
310
+ # Crea il worksheet esplicitamente se non esiste, altrimenti lo ottieni
311
  worksheet = writer.sheets.get(sheet_name_excel)
312
  if worksheet is None:
313
  worksheet = workbook.add_worksheet(sheet_name_excel)
 
368
  worksheet.set_column(col_num, col_num, col_widths[col_name], date_format)
369
 
370
  # Scrivi i dati a partire dalla riga 3 (indice 2 in xlsxwriter)
371
+ # NOTA: header=False perché li abbiamo già scritti noi nella riga 2
372
  final_df.to_excel(writer, sheet_name=sheet_name_excel, index=False, header=False, startrow=2)
373
 
374
  writer.close()
 
392
 
393
  # --- Funzione per il reset ---
394
  def clear_inputs():
395
+ # Incrementa i contatori delle chiavi per forzare il reset dei file uploader
396
+ # Nota: L'incremento è solo per il "nome" della chiave, il valore numerico non ha significato
397
+ # st.session_state.file_uploader_key_json = 'json_uploader_' + str(int(st.session_state.file_uploader_key_json.split('_')[1]) + 1)
398
+ # st.session_state.file_uploader_key_customers = 'customers_uploader_' + str(int(st.session_state.file_uploader_key_customers.split('_')[1]) + 1)
399
+ # Un reset più semplice e sicuro è usare una chiave che cambia ogni volta, ad esempio con il tempo corrente.
400
+ # Tuttavia, per il reset del file_uploader, Streamlit richiede un cambio della 'key'.
401
+ # Una pratica comune è resettare la chiave con un nuovo valore statico o una funzione che genera una nuova chiave.
402
+ # Per semplicità e robustezza, userò un approccio che "toggle" il valore o lo cambia.
403
+ # L'errore originale era '0', quindi ora usiamo stringhe diverse.
404
+ st.session_state.file_uploader_key_json = 'json_uploader_reset'
405
+ st.session_state.file_uploader_key_customers = 'customers_uploader_reset'
406
 
407
  st.markdown("---")
408
  st.button("Pulisci Input (RESET)", on_click=clear_inputs)