Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +113 -88
src/streamlit_app.py
CHANGED
|
@@ -2,6 +2,7 @@ import pandas as pd
|
|
| 2 |
from datetime import datetime
|
| 3 |
import os
|
| 4 |
import streamlit as st
|
|
|
|
| 5 |
|
| 6 |
def generate_poste_dat_file(df_shipping_mark_input, df_shipment_order_input):
|
| 7 |
"""
|
|
@@ -31,12 +32,9 @@ def generate_poste_dat_file(df_shipping_mark_input, df_shipment_order_input):
|
|
| 31 |
st.error(f"Il file delle shipping mark deve contenere le colonne: {required_shipping_mark_cols}")
|
| 32 |
return None, None
|
| 33 |
|
| 34 |
-
#
|
| 35 |
-
#
|
| 36 |
-
#
|
| 37 |
-
# nel tuo file ShipmentOrder_.xlsx, ignorando maiuscole/minuscole.
|
| 38 |
-
# Ad esempio, se nel tuo Excel hai 'Contatto Destinatario', e qui è 'consignee_contact',
|
| 39 |
-
# la mappatura `rename` si occuperà di questo.
|
| 40 |
column_mapping = {
|
| 41 |
'contatto destinatario': 'consignee_contact',
|
| 42 |
'nome contatto presso il destinatario': 'consignee_contact_name',
|
|
@@ -56,11 +54,11 @@ def generate_poste_dat_file(df_shipping_mark_input, df_shipment_order_input):
|
|
| 56 |
'codice rif. prodotto': 'product_ref_code',
|
| 57 |
'codice rif. destinatario': 'consignee_ref_code',
|
| 58 |
'valuta': 'currency',
|
| 59 |
-
'importo contrassegno': 'cash_on_delivery_amount',
|
| 60 |
'tipo pagamento': 'payment_type',
|
| 61 |
'note': 'notes',
|
| 62 |
'importo assicurata': 'insured_amount',
|
| 63 |
-
'identificativo collo': 'package_id',
|
| 64 |
'filiale': 'branch_code',
|
| 65 |
'contenuto': 'content_description',
|
| 66 |
'tipo contenuto': 'content_type',
|
|
@@ -87,8 +85,8 @@ def generate_poste_dat_file(df_shipping_mark_input, df_shipment_order_input):
|
|
| 87 |
}
|
| 88 |
|
| 89 |
# Applica il mapping delle colonne a df_shipment_order, convertendo le chiavi in minuscolo
|
| 90 |
-
|
| 91 |
-
|
| 92 |
|
| 93 |
# Assicurati che 'orderref' sia presente in df_shipment_order dopo il rename
|
| 94 |
if 'orderref' not in df_shipment_order.columns:
|
|
@@ -104,108 +102,140 @@ def generate_poste_dat_file(df_shipping_mark_input, df_shipment_order_input):
|
|
| 104 |
# 'how=left' assicura che tutte le shipping mark vengano mantenute.
|
| 105 |
df_merged = pd.merge(df_shipping_mark, df_shipment_order_unique, on='orderref', how='left')
|
| 106 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
# Definizione del layout del file .dat
|
| 108 |
-
# Ogni tupla contiene (nome_campo_interno, lunghezza, è_numerico_zero_padded, numero_decimali)
|
| 109 |
# è_numerico_zero_padded: True significa che il campo deve essere allineato a destra e riempito con '0' a sinistra.
|
| 110 |
# numero_decimali: Per i campi di valuta, indica quanti decimali considerare (moltiplicando il valore).
|
| 111 |
-
#
|
| 112 |
dat_format = [
|
| 113 |
# Dettagli del destinatario (colonne 21-28)
|
| 114 |
-
('consignee_contact', 20, False, 0),
|
| 115 |
-
('consignee_contact_name', 20, False, 0),
|
| 116 |
-
('consignee_street_type', 5, False, 0),
|
| 117 |
-
('consignee_address', 30, False, 0),
|
| 118 |
-
('consignee_house_number', 5, False, 0),
|
| 119 |
-
('consignee_phone', 15, False, 0),
|
| 120 |
-
('consignee_zip_code', 9, False, 0),
|
| 121 |
-
('consignee_city', 30, False, 0),
|
| 122 |
-
('consignee_province', 2, False, 0),
|
| 123 |
|
| 124 |
# Dettagli colli e spedizione (colonne 29-33) - zero-padded a sinistra
|
| 125 |
-
('num_packages', 3, True, 0),
|
| 126 |
-
('package_weight', 7, True, 0),
|
| 127 |
-
('package_width', 5, True, 0),
|
| 128 |
-
('package_height', 5, True, 0),
|
| 129 |
-
('package_depth', 5, True, 0),
|
| 130 |
|
| 131 |
# Servizio e riferimenti (colonne 34-36)
|
| 132 |
-
('service_code', 3, False, 0),
|
| 133 |
-
('product_ref_code', 20, False, 0),
|
| 134 |
-
('consignee_ref_code', 20, False, 0),
|
| 135 |
|
| 136 |
# Pagamento e note (colonne 37-41)
|
| 137 |
-
('currency', 2, False, 0),
|
| 138 |
-
('cash_on_delivery_amount', 9, True, 2),
|
| 139 |
-
('payment_type', 3, False, 0),
|
| 140 |
-
('notes', 30, False, 0),
|
| 141 |
-
('insured_amount', 10, True, 2),
|
| 142 |
|
| 143 |
# Identificativi e filiale (colonne 42-43)
|
| 144 |
-
('shippingmark', 25, False, 0),
|
| 145 |
-
('branch_code', 2, False, 0),
|
| 146 |
|
| 147 |
# Contenuto e paesi (colonne 44-48)
|
| 148 |
-
('content_description', 30, False, 0),
|
| 149 |
-
('content_type', 1, False, 0),
|
| 150 |
-
('sender_country', 3, False, 0),
|
| 151 |
-
('consignee_country', 3, False, 0),
|
| 152 |
-
('shipment_value', 10, True, 2),
|
| 153 |
|
| 154 |
# Tipo cliente e classe spedizione (colonne 49-50)
|
| 155 |
-
('client_type', 4, False, 0),
|
| 156 |
-
('shipment_class', 5, False, 0),
|
| 157 |
|
| 158 |
# Oneri, imballo, fiscale (colonne 51-53)
|
| 159 |
-
('duty_charge', 1, False, 0),
|
| 160 |
-
('packaging_type', 2, False, 0),
|
| 161 |
-
('fiscal_id', 20, False, 0),
|
| 162 |
|
| 163 |
# Barcode servizio e contatti aggiuntivi (colonne 54-57)
|
| 164 |
-
('barcode_service', 3, False, 0),
|
| 165 |
-
('consignee_email', 50, False, 0),
|
| 166 |
-
('consignee_mobile_prefix', 4, False, 0),
|
| 167 |
-
('consignee_mobile_number', 10, False, 0),
|
| 168 |
|
| 169 |
# Altri campi (colonne 58-65)
|
| 170 |
-
('is_insured_percentage', 1, False, 0),
|
| 171 |
-
('barcode_service_return', 3, False, 0),
|
| 172 |
-
('shipment_type_id', 2, False, 0),
|
| 173 |
-
('detail_bs', 6, False, 0),
|
| 174 |
-
('notes_2', 50, False, 0),
|
| 175 |
-
('fractional_office_code', 11, False, 0),
|
| 176 |
-
('customer_post_box', 11, False, 0),
|
| 177 |
-
('undelivered_action', 1, False, 0)
|
| 178 |
]
|
| 179 |
|
| 180 |
# Genera il contenuto del file .dat
|
| 181 |
dat_content = []
|
| 182 |
-
for index, row in df_merged.iterrows():
|
| 183 |
record_parts = []
|
| 184 |
-
for field_name, length, is_numeric_zero_padded, dec_places in dat_format:
|
| 185 |
value = row.get(field_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
|
| 187 |
-
#
|
| 188 |
-
|
| 189 |
-
value = ''
|
| 190 |
-
|
| 191 |
-
value = str(value).strip() # Converti in stringa e rimuovi spazi
|
| 192 |
|
| 193 |
if is_numeric_zero_padded:
|
| 194 |
try:
|
| 195 |
-
# Pulizia del valore numerico
|
| 196 |
-
|
| 197 |
-
clean_value = value.replace(',', '.')
|
| 198 |
|
| 199 |
if dec_places > 0: # Campi valuta (38, 41, 48)
|
| 200 |
-
# Converti in float, moltiplica per 10^dec_places per spostare i decimali,
|
| 201 |
-
# poi converti in intero per ottenere la stringa senza punto
|
| 202 |
num_value = float(clean_value) * (10**dec_places)
|
| 203 |
-
# Arrotonda per evitare problemi di floating point
|
| 204 |
formatted_value = str(int(round(num_value))).rjust(length, '0')
|
| 205 |
else: # Campi numerici interi (29,30,31,32,33)
|
| 206 |
formatted_value = str(int(float(clean_value))).rjust(length, '0')
|
| 207 |
except ValueError:
|
| 208 |
-
|
|
|
|
| 209 |
else: # Default: allinea a sinistra con spazi
|
| 210 |
formatted_value = value.ljust(length)
|
| 211 |
|
|
@@ -220,8 +250,8 @@ def generate_poste_dat_file(df_shipping_mark_input, df_shipment_order_input):
|
|
| 220 |
dat_filename = f"SDA{filename_timestamp}.dat"
|
| 221 |
dis_filename = f"SDA{filename_timestamp}.dis"
|
| 222 |
|
| 223 |
-
#
|
| 224 |
-
temp_dir = "
|
| 225 |
os.makedirs(temp_dir, exist_ok=True)
|
| 226 |
|
| 227 |
dat_filepath = os.path.join(temp_dir, dat_filename)
|
|
@@ -239,14 +269,14 @@ def generate_poste_dat_file(df_shipping_mark_input, df_shipment_order_input):
|
|
| 239 |
return dat_filepath, dis_filepath
|
| 240 |
|
| 241 |
except pd.errors.EmptyDataError:
|
| 242 |
-
st.error("Errore: Uno dei file Excel è vuoto o non contiene dati validi.")
|
| 243 |
return None, None
|
| 244 |
except FileNotFoundError as e:
|
| 245 |
st.error(f"Errore: File non trovato - {e}. Assicurati che i file siano caricati correttamente.")
|
| 246 |
return None, None
|
| 247 |
except Exception as e:
|
| 248 |
st.error(f"Si è verificato un errore inatteso durante l'elaborazione: {e}")
|
| 249 |
-
st.warning("Verifica che i nomi delle colonne nei tuoi file Excel corrispondano alle aspettative del programma, specialmente 'orderRef' e i campi relativi al destinatario.")
|
| 250 |
return None, None
|
| 251 |
|
| 252 |
# --- Sezione App Streamlit ---
|
|
@@ -259,6 +289,7 @@ def app():
|
|
| 259 |
Carica i tuoi due file Excel per generare il file .DAT nel formato richiesto da Poste Italiane.
|
| 260 |
Ogni "shipping mark" (LDV) nel file `ShippingMark_` genererà un record nel file di output.
|
| 261 |
I dettagli dell'ordine verranno presi dalla prima occorrenza di ciascun 'orderRef' nel file `ShipmentOrder_`.
|
|
|
|
| 262 |
""")
|
| 263 |
|
| 264 |
shipping_mark_file = st.file_uploader("Carica il file ShippingMark_ (con 'shippingMark' e 'orderRef')", type=["xlsx"])
|
|
@@ -270,14 +301,15 @@ def app():
|
|
| 270 |
if shipping_mark_file and shipment_order_file:
|
| 271 |
st.subheader("Processando i file...")
|
| 272 |
try:
|
| 273 |
-
|
| 274 |
-
|
|
|
|
| 275 |
|
| 276 |
dat_filepath, dis_filepath = generate_poste_dat_file(df_shipping_mark, df_shipment_order)
|
| 277 |
|
| 278 |
except Exception as e:
|
| 279 |
st.error(f"Errore nella lettura dei file Excel: {e}")
|
| 280 |
-
st.warning("Assicurati che i file siano in formato .xlsx
|
| 281 |
|
| 282 |
if dat_filepath and dis_filepath:
|
| 283 |
st.subheader("Download dei file generati:")
|
|
@@ -302,15 +334,8 @@ def app():
|
|
| 302 |
|
| 303 |
st.markdown("---")
|
| 304 |
st.info("""
|
| 305 |
-
**
|
| 306 |
-
|
| 307 |
-
- Il file `ShippingMark_` deve contenere le colonne 'shippingMark' e 'orderRef'.
|
| 308 |
-
- Il file `ShipmentOrder_` deve contenere 'orderRef' e i campi specifici per il destinatario e la spedizione (es. 'Contatto Destinatario', 'Via Destinatario', 'Numero colli', 'Peso colli', ecc.).
|
| 309 |
-
I nomi delle colonne nel tuo file `ShipmentOrder_` devono corrispondere **esattamente** (ignorando maiuscole/minuscole) a quelli indicati nel documento delle specifiche per un corretto mapping. In caso di dubbi, puoi stampare i `df.columns` per verificare.
|
| 310 |
-
|
| 311 |
-
**Riguardo il warning `Running pip as the 'root' user` su Hugging Face:**
|
| 312 |
-
Questo è un messaggio standard di `pip` che indica che il processo di installazione dei pacchetti sta avvenendo con privilegi di root.
|
| 313 |
-
Generalmente, **non è un problema critico** per la distribuzione su piattaforme come Hugging Face Spaces, dove l'ambiente di esecuzione è isolato e gestito. Puoi ignorarlo tranquillamente; non impedisce il funzionamento della tua applicazione.
|
| 314 |
""")
|
| 315 |
|
| 316 |
if __name__ == "__main__":
|
|
|
|
| 2 |
from datetime import datetime
|
| 3 |
import os
|
| 4 |
import streamlit as st
|
| 5 |
+
import numpy as np # Importa numpy per np.nan
|
| 6 |
|
| 7 |
def generate_poste_dat_file(df_shipping_mark_input, df_shipment_order_input):
|
| 8 |
"""
|
|
|
|
| 32 |
st.error(f"Il file delle shipping mark deve contenere le colonne: {required_shipping_mark_cols}")
|
| 33 |
return None, None
|
| 34 |
|
| 35 |
+
# Mapping dei nomi delle colonne dal PDF ai nomi interni/standardizzati.
|
| 36 |
+
# **IMPORTANTE**: Adatta queste chiavi ai nomi effettivi delle colonne
|
| 37 |
+
# nel tuo file ShipmentOrder_.xlsx, ignorando maiuscole/minuscole per la chiave.
|
|
|
|
|
|
|
|
|
|
| 38 |
column_mapping = {
|
| 39 |
'contatto destinatario': 'consignee_contact',
|
| 40 |
'nome contatto presso il destinatario': 'consignee_contact_name',
|
|
|
|
| 54 |
'codice rif. prodotto': 'product_ref_code',
|
| 55 |
'codice rif. destinatario': 'consignee_ref_code',
|
| 56 |
'valuta': 'currency',
|
| 57 |
+
'importo contrassegno': 'cash_on_delivery_amount',
|
| 58 |
'tipo pagamento': 'payment_type',
|
| 59 |
'note': 'notes',
|
| 60 |
'importo assicurata': 'insured_amount',
|
| 61 |
+
'identificativo collo': 'package_id',
|
| 62 |
'filiale': 'branch_code',
|
| 63 |
'contenuto': 'content_description',
|
| 64 |
'tipo contenuto': 'content_type',
|
|
|
|
| 85 |
}
|
| 86 |
|
| 87 |
# Applica il mapping delle colonne a df_shipment_order, convertendo le chiavi in minuscolo
|
| 88 |
+
# e poi mappando ai nomi standardizzati.
|
| 89 |
+
df_shipment_order = df_shipment_order.rename(columns=lambda x: column_mapping.get(x.lower(), x))
|
| 90 |
|
| 91 |
# Assicurati che 'orderref' sia presente in df_shipment_order dopo il rename
|
| 92 |
if 'orderref' not in df_shipment_order.columns:
|
|
|
|
| 102 |
# 'how=left' assicura che tutte le shipping mark vengano mantenute.
|
| 103 |
df_merged = pd.merge(df_shipping_mark, df_shipment_order_unique, on='orderref', how='left')
|
| 104 |
|
| 105 |
+
# Dizionario per i valori di default/fissi per i campi obbligatori o predeterminati
|
| 106 |
+
default_fixed_values = {
|
| 107 |
+
'currency': 'EU',
|
| 108 |
+
'client_type': 'MGCS',
|
| 109 |
+
'sender_country': 'ITA', # Fisso per Poste Logistics, Italia
|
| 110 |
+
# Valori di default per campi obbligatori se non presenti
|
| 111 |
+
'consignee_contact': 'SCONOSCIUTO',
|
| 112 |
+
'consignee_contact_name': 'SCONOSCIUTO',
|
| 113 |
+
'consignee_street_type': 'VIA',
|
| 114 |
+
'consignee_address': 'INDIRIZZO SCONOSCIUTO',
|
| 115 |
+
'consignee_house_number': 'SN', # Senza Numero
|
| 116 |
+
'consignee_phone': '00000000000',
|
| 117 |
+
'consignee_zip_code': '00000',
|
| 118 |
+
'consignee_city': 'CITTA SCONOSCIUTA',
|
| 119 |
+
'consignee_province': 'XX',
|
| 120 |
+
'num_packages': 1, # Default 1 collo se non specificato
|
| 121 |
+
'package_weight': 1, # Default 1 grammo se non specificato
|
| 122 |
+
'service_code': 'STD', # Esempio di default per servizio
|
| 123 |
+
'branch_code': '00', # Esempio di default per filiale
|
| 124 |
+
'package_id': 'NON_DEFINITO', # Sarà sovrascritto da shippingmark
|
| 125 |
+
'id_tipo_spedizione': 'C', # Default Collo
|
| 126 |
+
'is_insured_percentage': 'N', # Default Non assicurata
|
| 127 |
+
'undelivered_action': 'R' # Default Restituire
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
# Definizione del layout del file .dat
|
| 131 |
+
# Ogni tupla contiene (nome_campo_interno, lunghezza, è_numerico_zero_padded, numero_decimali, è_obbligatorio)
|
| 132 |
# è_numerico_zero_padded: True significa che il campo deve essere allineato a destra e riempito con '0' a sinistra.
|
| 133 |
# numero_decimali: Per i campi di valuta, indica quanti decimali considerare (moltiplicando il valore).
|
| 134 |
+
# è_obbligatorio: True se il campo è contrassegnato con * nel PDF.
|
| 135 |
dat_format = [
|
| 136 |
# Dettagli del destinatario (colonne 21-28)
|
| 137 |
+
('consignee_contact', 20, False, 0, True), # 21 Contatto Destinatario
|
| 138 |
+
('consignee_contact_name', 20, False, 0, False), # 21 Nome Contatto (se distinta) - non * ma spesso presente
|
| 139 |
+
('consignee_street_type', 5, False, 0, True), # 22 Tipo Via Destinatario
|
| 140 |
+
('consignee_address', 30, False, 0, True), # 23 Via Destinatario
|
| 141 |
+
('consignee_house_number', 5, False, 0, True), # 24 Numero Civico Destinatario
|
| 142 |
+
('consignee_phone', 15, False, 0, True), # 25 Numero di telefono Destinatario
|
| 143 |
+
('consignee_zip_code', 9, False, 0, True), # 26 CAP Destinatario
|
| 144 |
+
('consignee_city', 30, False, 0, True), # 27 Località Destinatario
|
| 145 |
+
('consignee_province', 2, False, 0, True), # 28 Provincia Destinatario
|
| 146 |
|
| 147 |
# Dettagli colli e spedizione (colonne 29-33) - zero-padded a sinistra
|
| 148 |
+
('num_packages', 3, True, 0, True), # 29 Numero colli
|
| 149 |
+
('package_weight', 7, True, 0, True), # 30 Peso colli (in grammi)
|
| 150 |
+
('package_width', 5, True, 0, False), # 31 Dimensioni (Larghezza)
|
| 151 |
+
('package_height', 5, True, 0, False), # 32 Dimensioni (Altezza)
|
| 152 |
+
('package_depth', 5, True, 0, False), # 33 Dimensioni (Profondità)
|
| 153 |
|
| 154 |
# Servizio e riferimenti (colonne 34-36)
|
| 155 |
+
('service_code', 3, False, 0, True), # 34 Codice Servizio
|
| 156 |
+
('product_ref_code', 20, False, 0, False), # 35 Codice Rif. Prodotto
|
| 157 |
+
('consignee_ref_code', 20, False, 0, False), # 36 Codice Rif. Destinatario
|
| 158 |
|
| 159 |
# Pagamento e note (colonne 37-41)
|
| 160 |
+
('currency', 2, False, 0, True), # 37 Valuta (Valore costante: EU)
|
| 161 |
+
('cash_on_delivery_amount', 9, True, 2, False), # 38 Importo contrassegno (C)
|
| 162 |
+
('payment_type', 3, False, 0, False), # 39 Tipo pagamento (C)
|
| 163 |
+
('notes', 30, False, 0, False), # 40 Note
|
| 164 |
+
('insured_amount', 10, True, 2, False), # 41 Importo Assicurata (A)
|
| 165 |
|
| 166 |
# Identificativi e filiale (colonne 42-43)
|
| 167 |
+
('shippingmark', 25, False, 0, True), # 42 Identificativo collo (usa 'shippingmark')
|
| 168 |
+
('branch_code', 2, False, 0, True), # 43 Filiale
|
| 169 |
|
| 170 |
# Contenuto e paesi (colonne 44-48)
|
| 171 |
+
('content_description', 30, False, 0, False), # 44 Contenuto (I)
|
| 172 |
+
('content_type', 1, False, 0, False), # 45 Tipo contenuto (I)
|
| 173 |
+
('sender_country', 3, False, 0, False), # 46 Nazione mittente (I)
|
| 174 |
+
('consignee_country', 3, False, 0, False), # 47 Nazione destinatario (I)
|
| 175 |
+
('shipment_value', 10, True, 2, False), # 48 Valore spedizione (I)
|
| 176 |
|
| 177 |
# Tipo cliente e classe spedizione (colonne 49-50)
|
| 178 |
+
('client_type', 4, False, 0, True), # 49 Tipo cliente (Valore costante: MGCS)
|
| 179 |
+
('shipment_class', 5, False, 0, False), # 50 Classe spedizione
|
| 180 |
|
| 181 |
# Oneri, imballo, fiscale (colonne 51-53)
|
| 182 |
+
('duty_charge', 1, False, 0, False), # 51 Addebito Oneri (I)
|
| 183 |
+
('packaging_type', 2, False, 0, False), # 52 Tipo imballo (I, E)
|
| 184 |
+
('fiscal_id', 20, False, 0, False), # 53 Identificativo Fiscale
|
| 185 |
|
| 186 |
# Barcode servizio e contatti aggiuntivi (colonne 54-57)
|
| 187 |
+
('barcode_service', 3, False, 0, False), # 54 Barcode Servizio (X)
|
| 188 |
+
('consignee_email', 50, False, 0, False), # 55 Indirizzo email destinatario
|
| 189 |
+
('consignee_mobile_prefix', 4, False, 0, False), # 56 Prefisso cellulare destinatario
|
| 190 |
+
('consignee_mobile_number', 10, False, 0, False), # 57 Numero cellulare destinario
|
| 191 |
|
| 192 |
# Altri campi (colonne 58-65)
|
| 193 |
+
('is_insured_percentage', 1, False, 0, False), # 58 is_ass_percentuale (A%)
|
| 194 |
+
('barcode_service_return', 3, False, 0, False), # 59 barcode_servizio_rit
|
| 195 |
+
('shipment_type_id', 2, False, 0, True), # 60 id_tipo_spedizione
|
| 196 |
+
('detail_bs', 6, False, 0, False), # 61 dettaglio_bs
|
| 197 |
+
('notes_2', 50, False, 0, False), # 62 Note 2
|
| 198 |
+
('fractional_office_code', 11, False, 0, False), # 63 Codice ufficio frazionario
|
| 199 |
+
('customer_post_box', 11, False, 0, False), # 64 Casella postale cliente
|
| 200 |
+
('undelivered_action', 1, False, 0, False) # 65 Mancata consegna
|
| 201 |
]
|
| 202 |
|
| 203 |
# Genera il contenuto del file .dat
|
| 204 |
dat_content = []
|
| 205 |
+
for index, row in df_merged.iterrows():
|
| 206 |
record_parts = []
|
| 207 |
+
for field_name, length, is_numeric_zero_padded, dec_places, is_mandatory in dat_format:
|
| 208 |
value = row.get(field_name)
|
| 209 |
+
|
| 210 |
+
# Gestione valori di default/fissi
|
| 211 |
+
if field_name in default_fixed_values:
|
| 212 |
+
value = default_fixed_values[field_name]
|
| 213 |
+
elif pd.isna(value) or value == '':
|
| 214 |
+
if is_mandatory:
|
| 215 |
+
# Se è obbligatorio e mancante, usa un default basato sul tipo di campo
|
| 216 |
+
if is_numeric_zero_padded:
|
| 217 |
+
value = '0' * length # Default numerico (zero)
|
| 218 |
+
else:
|
| 219 |
+
value = ' ' * length # Default stringa (spazi)
|
| 220 |
+
else:
|
| 221 |
+
value = '' # Se non obbligatorio, lascia vuoto
|
| 222 |
|
| 223 |
+
# Conversione in stringa e pulizia iniziale
|
| 224 |
+
value = str(value).strip()
|
|
|
|
|
|
|
|
|
|
| 225 |
|
| 226 |
if is_numeric_zero_padded:
|
| 227 |
try:
|
| 228 |
+
# Pulizia del valore numerico per assicurare la conversione
|
| 229 |
+
clean_value = value.replace(',', '.') # Sostituisce virgole con punti
|
|
|
|
| 230 |
|
| 231 |
if dec_places > 0: # Campi valuta (38, 41, 48)
|
|
|
|
|
|
|
| 232 |
num_value = float(clean_value) * (10**dec_places)
|
|
|
|
| 233 |
formatted_value = str(int(round(num_value))).rjust(length, '0')
|
| 234 |
else: # Campi numerici interi (29,30,31,32,33)
|
| 235 |
formatted_value = str(int(float(clean_value))).rjust(length, '0')
|
| 236 |
except ValueError:
|
| 237 |
+
# Se la conversione fallisce, usa '0' padato a sinistra
|
| 238 |
+
formatted_value = '0'.rjust(length, '0')
|
| 239 |
else: # Default: allinea a sinistra con spazi
|
| 240 |
formatted_value = value.ljust(length)
|
| 241 |
|
|
|
|
| 250 |
dat_filename = f"SDA{filename_timestamp}.dat"
|
| 251 |
dis_filename = f"SDA{filename_timestamp}.dis"
|
| 252 |
|
| 253 |
+
# Usa la directory temporanea /tmp che è scrivibile su Hugging Face Spaces
|
| 254 |
+
temp_dir = "/tmp"
|
| 255 |
os.makedirs(temp_dir, exist_ok=True)
|
| 256 |
|
| 257 |
dat_filepath = os.path.join(temp_dir, dat_filename)
|
|
|
|
| 269 |
return dat_filepath, dis_filepath
|
| 270 |
|
| 271 |
except pd.errors.EmptyDataError:
|
| 272 |
+
st.error("Errore: Uno dei file Excel è vuoto o non contiene dati validi. Assicurati che non siano completamente vuoti.")
|
| 273 |
return None, None
|
| 274 |
except FileNotFoundError as e:
|
| 275 |
st.error(f"Errore: File non trovato - {e}. Assicurati che i file siano caricati correttamente.")
|
| 276 |
return None, None
|
| 277 |
except Exception as e:
|
| 278 |
st.error(f"Si è verificato un errore inatteso durante l'elaborazione: {e}")
|
| 279 |
+
st.warning("Verifica che i nomi delle colonne nei tuoi file Excel corrispondano alle aspettative del programma, specialmente 'orderRef' e i campi relativi al destinatario. Ricorda che l'intestazione è alla seconda riga.")
|
| 280 |
return None, None
|
| 281 |
|
| 282 |
# --- Sezione App Streamlit ---
|
|
|
|
| 289 |
Carica i tuoi due file Excel per generare il file .DAT nel formato richiesto da Poste Italiane.
|
| 290 |
Ogni "shipping mark" (LDV) nel file `ShippingMark_` genererà un record nel file di output.
|
| 291 |
I dettagli dell'ordine verranno presi dalla prima occorrenza di ciascun 'orderRef' nel file `ShipmentOrder_`.
|
| 292 |
+
**Nota**: I file Excel devono avere l'intestazione sulla **seconda riga**.
|
| 293 |
""")
|
| 294 |
|
| 295 |
shipping_mark_file = st.file_uploader("Carica il file ShippingMark_ (con 'shippingMark' e 'orderRef')", type=["xlsx"])
|
|
|
|
| 301 |
if shipping_mark_file and shipment_order_file:
|
| 302 |
st.subheader("Processando i file...")
|
| 303 |
try:
|
| 304 |
+
# Leggi i file Excel, specificando che l'intestazione è alla seconda riga (indice 1)
|
| 305 |
+
df_shipping_mark = pd.read_excel(shipping_mark_file, header=1)
|
| 306 |
+
df_shipment_order = pd.read_excel(shipment_order_file, header=1)
|
| 307 |
|
| 308 |
dat_filepath, dis_filepath = generate_poste_dat_file(df_shipping_mark, df_shipment_order)
|
| 309 |
|
| 310 |
except Exception as e:
|
| 311 |
st.error(f"Errore nella lettura dei file Excel: {e}")
|
| 312 |
+
st.warning("Assicurati che i file siano in formato .xlsx, non siano corrotti e che l'intestazione sia effettivamente alla seconda riga.")
|
| 313 |
|
| 314 |
if dat_filepath and dis_filepath:
|
| 315 |
st.subheader("Download dei file generati:")
|
|
|
|
| 334 |
|
| 335 |
st.markdown("---")
|
| 336 |
st.info("""
|
| 337 |
+
**Carica il file di output su FTP**
|
| 338 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
""")
|
| 340 |
|
| 341 |
if __name__ == "__main__":
|