pasquale991 commited on
Commit
84f13c3
·
verified ·
1 Parent(s): 6965aa3

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +319 -39
src/streamlit_app.py CHANGED
@@ -1,40 +1,320 @@
1
- import altair as alt
2
- import numpy as np
3
  import pandas as pd
4
- import streamlit as st
5
-
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import pandas as pd
2
+ from datetime import datetime
3
+ import os
4
+
5
+ def generate_poste_dat_file(shipping_mark_file, shipment_order_file, output_dir="."):
6
+ """
7
+ Genera un file .dat per Poste Italiane unendo i dati da due file Excel.
8
+
9
+ Args:
10
+ shipping_mark_file (str): Percorso del file Excel contenente le shipping mark e i riferimenti d'ordine.
11
+ Deve contenere le colonne 'shippingMark' e 'orderRef'.
12
+ shipment_order_file (str): Percorso del file Excel contenente i dettagli dell'ordine.
13
+ Deve contenere 'orderRef' e i campi relativi al destinatario.
14
+ output_dir (str, optional): Directory dove salvare il file .dat e .dis. Default è la directory corrente.
15
+ """
16
+ try:
17
+ # Leggi i file Excel
18
+ print(f"Lettura del file: {shipping_mark_file}")
19
+ df_shipping_mark = pd.read_excel(shipping_mark_file)
20
+ print(f"Lettura del file: {shipment_order_file}")
21
+ df_shipment_order = pd.read_excel(shipment_order_file)
22
+
23
+ # Assicurati che i nomi delle colonne siano in minuscolo per una maggiore robustezza
24
+ df_shipping_mark.columns = df_shipping_mark.columns.str.lower()
25
+ df_shipment_order.columns = df_shipment_order.columns.str.lower()
26
+
27
+ # Verifica la presenza delle colonne necessarie
28
+ required_shipping_mark_cols = ['shippingmark', 'orderref']
29
+ if not all(col in df_shipping_mark.columns for col in required_shipping_mark_cols):
30
+ raise ValueError(f"Il file '{shipping_mark_file}' deve contenere le colonne: {required_shipping_mark_cols}")
31
+
32
+ required_shipment_order_cols = ['orderref', 'consignee_contact', 'consignee_street_type', 'consignee_address',
33
+ 'consignee_house_number', 'consignee_phone', 'consignee_zip_code',
34
+ 'consignee_city', 'consignee_province', 'num_packages', 'package_weight',
35
+ 'package_width', 'package_height', 'package_depth', 'service_code',
36
+ 'product_ref_code', 'consignee_ref_code', 'currency', 'cash_on_delivery_amount',
37
+ 'payment_type', 'notes', 'insured_amount', 'package_id', 'branch_code',
38
+ 'content_description', 'content_type', 'sender_country', 'consignee_country',
39
+ 'shipment_value', 'client_type', 'shipment_class', 'duty_charge',
40
+ 'packaging_type', 'fiscal_id', 'barcode_service', 'consignee_email',
41
+ 'consignee_mobile_prefix', 'consignee_mobile_number', 'is_insured_percentage',
42
+ 'barcode_service_return', 'shipment_type_id', 'detail_bs', 'notes_2',
43
+ 'fractional_office_code', 'customer_post_box', 'undelivered_action']
44
+
45
+ # Esempio di colonne che potrebbero non essere presenti ma sono necessarie per il formato DAT
46
+ # Vengono mappate a nomi generici che dovrai adattare ai tuoi file reali
47
+ # Qui mappo i nomi del documento PDF ai nomi delle colonne che mi aspetterei di trovare
48
+ # nel file ShipmentOrder_. Adatta questi nomi a quelli effettivi del tuo Excel.
49
+ # Ho usato placeholder come 'consignee_contact' che dovrai sostituire con il nome reale della colonna nel tuo Excel
50
+ # ad esempio, se hai una colonna 'Contatto Destinatario' nel tuo Excel, la mappa qui.
51
+ column_mapping = {
52
+ 'Contatto Destinatario': 'consignee_contact',
53
+ 'Nome Contatto presso il Destinatario': 'consignee_contact_name', # Assumo che sia lo stesso del contatto o un campo simile
54
+ 'Tipo Via Destinatario': 'consignee_street_type',
55
+ 'Via Destinatario': 'consignee_address',
56
+ 'Numero Civico Destinatario': 'consignee_house_number',
57
+ 'Numero di telefono Destinatario': 'consignee_phone',
58
+ 'CAP Destinatario': 'consignee_zip_code',
59
+ 'Località Destinatario': 'consignee_city',
60
+ 'Provincia Destinatario': 'consignee_province',
61
+ 'Numero colli': 'num_packages',
62
+ 'Peso colli': 'package_weight',
63
+ 'Dimensioni (Larghezza)': 'package_width',
64
+ 'Dimensioni (Altezza)': 'package_height',
65
+ 'Dimensioni (Profondità)': 'package_depth',
66
+ 'Codice Servizio': 'service_code',
67
+ 'Codice Rif. Prodotto': 'product_ref_code',
68
+ 'Codice Rif. Destinatario': 'consignee_ref_code',
69
+ 'Valuta': 'currency',
70
+ 'Importo contrassegno ': 'cash_on_delivery_amount',
71
+ 'Tipo pagamento': 'payment_type',
72
+ 'Note': 'notes',
73
+ 'Importo Assicurata': 'insured_amount',
74
+ 'Identificativo collo': 'package_id',
75
+ 'Filiale': 'branch_code',
76
+ 'Contenuto': 'content_description',
77
+ 'Tipo contenuto': 'content_type',
78
+ 'Nazione mittente': 'sender_country',
79
+ 'Nazione destinatario': 'consignee_country',
80
+ 'Valore spedizione': 'shipment_value',
81
+ 'Tipo cliente': 'client_type',
82
+ 'Classe spedizione': 'shipment_class',
83
+ 'Addebito Oneri': 'duty_charge',
84
+ 'Tipo imballo': 'packaging_type',
85
+ 'Identificativo Fiscale': 'fiscal_id',
86
+ 'Barcode Servizio': 'barcode_service',
87
+ 'Indirizzo email destinatario': 'consignee_email',
88
+ 'Prefisso cellulare destinatario': 'consignee_mobile_prefix',
89
+ 'Numero cellulare destinario': 'consignee_mobile_number',
90
+ 'is_ass_percentuale': 'is_insured_percentage',
91
+ 'barcode_servizio_rit': 'barcode_service_return',
92
+ 'id_tipo_spedizione': 'shipment_type_id',
93
+ 'dettaglio_bs': 'detail_bs',
94
+ 'Note 2': 'notes_2',
95
+ 'Codice ufficio frazionario': 'fractional_office_code',
96
+ 'Casella postale cliente': 'customer_post_box',
97
+ 'Mancata consegna': 'undelivered_action'
98
+ }
99
+
100
+ # Rinomina le colonne nel df_shipment_order per renderle conformi al mapping interno
101
+ # Converti le chiavi di column_mapping in minuscolo per il confronto
102
+ column_mapping_lower = {k.lower(): v for k, v in column_mapping.items()}
103
+ df_shipment_order = df_shipment_order.rename(columns=column_mapping_lower)
104
+
105
+ # Aggiungi eventuali colonne mancanti con valori di default se non sono obbligatorie
106
+ for col in required_shipment_order_cols:
107
+ if col not in df_shipment_order.columns:
108
+ df_shipment_order[col] = '' # Valore di default vuoto
109
+
110
+ # Fai la join dei due DataFrame
111
+ # La testata si ripete una volta per ordine, quindi non dobbiamo preoccuparci di duplicati qui
112
+ # useremo il primo occorrenza per l'ordine
113
+ df_merged = pd.merge(df_shipping_mark, df_shipment_order, on='orderref', how='left')
114
+
115
+ # Rimuovi i duplicati basati sull'orderRef per considerare solo la testata (la prima riga per ordine)
116
+ # Questo è importante se ci sono più righe per lo stesso orderRef nel ShipmentOrder_ ma la testata è unica.
117
+ df_merged_unique_orders = df_merged.drop_duplicates(subset=['orderref'])
118
+
119
+ # Definizione del layout del file .dat
120
+ # Ogni tupla contiene (nome_campo, lunghezza, allinea_a_sinistra_con_blank, riempi_con_zero_a_sinistra)
121
+ # I campi da riempire con zero a sinistra sono 29, 30, 31, 32, 33, 38, 41, 48
122
+ dat_format = [
123
+ # Dettagli del destinatario (colonne 21-28)
124
+ ('consignee_contact', 20, True, False), # 21 Contatto Destinatario
125
+ ('consignee_street_type', 5, True, False), # 22 Tipo Via Destinatario
126
+ ('consignee_address', 30, True, False), # 23 Via Destinatario
127
+ ('consignee_house_number', 5, True, False), # 24 Numero Civico Destinatario
128
+ ('consignee_phone', 15, True, False), # 25 Numero di telefono Destinatario
129
+ ('consignee_zip_code', 9, True, False), # 26 CAP Destinatario
130
+ ('consignee_city', 30, True, False), # 27 Località Destinatario
131
+ ('consignee_province', 2, True, False), # 28 Provincia Destinatario
132
+
133
+ # Dettagli colli e spedizione (colonne 29-33)
134
+ ('num_packages', 3, False, True), # 29 Numero colli (riempi con 0 a sinistra)
135
+ ('package_weight', 7, False, True), # 30 Peso colli (riempi con 0 a sinistra)
136
+ ('package_width', 5, False, True), # 31 Dimensioni (Larghezza) (riempi con 0 a sinistra)
137
+ ('package_height', 5, False, True), # 32 Dimensioni (Altezza) (riempi con 0 a sinistra)
138
+ ('package_depth', 5, False, True), # 33 Dimensioni (Profondità) (riempi con 0 a sinistra)
139
+
140
+ # Servizio e riferimenti (colonne 34-36)
141
+ ('service_code', 3, True, False), # 34 Codice Servizio
142
+ ('product_ref_code', 20, True, False), # 35 Codice Rif. Prodotto
143
+ ('consignee_ref_code', 20, True, False), # 36 Codice Rif. Destinatario
144
+
145
+ # Pagamento e note (colonne 37-41)
146
+ ('currency', 2, True, False), # 37 Valuta (Valore costante: EU)
147
+ ('cash_on_delivery_amount', 9, False, True), # 38 Importo contrassegno (riempi con 0 a sinistra)
148
+ ('payment_type', 3, True, False), # 39 Tipo pagamento
149
+ ('notes', 30, True, False), # 40 Note
150
+ ('insured_amount', 10, False, True), # 41 Importo Assicurata (riempi con 0 a sinistra)
151
+
152
+ # Identificativi e filiale (colonne 42-43)
153
+ ('package_id', 25, True, False), # 42 Identificativo collo (shippingMark)
154
+ ('branch_code', 2, True, False), # 43 Filiale
155
+
156
+ # Contenuto e paesi (colonne 44-48)
157
+ ('content_description', 30, True, False), # 44 Contenuto
158
+ ('content_type', 1, True, False), # 45 Tipo contenuto
159
+ ('sender_country', 3, True, False), # 46 Nazione mittente
160
+ ('consignee_country', 3, True, False), # 47 Nazione destinatario
161
+ ('shipment_value', 10, False, True), # 48 Valore spedizione (riempi con 0 a sinistra)
162
+
163
+ # Tipo cliente e classe spedizione (colonne 49-50)
164
+ ('client_type', 4, True, False), # 49 Tipo cliente (Valore costante: MGCS)
165
+ ('shipment_class', 5, True, False), # 50 Classe spedizione
166
+
167
+ # Oneri, imballo, fiscale (colonne 51-53)
168
+ ('duty_charge', 1, True, False), # 51 Addebito Oneri
169
+ ('packaging_type', 2, True, False), # 52 Tipo imballo
170
+ ('fiscal_id', 20, True, False), # 53 Identificativo Fiscale
171
+
172
+ # Barcode servizio e contatti aggiuntivi (colonne 54-57)
173
+ ('barcode_service', 3, True, False), # 54 Barcode Servizio
174
+ ('consignee_email', 50, True, False), # 55 Indirizzo email destinatario
175
+ ('consignee_mobile_prefix', 4, True, False), # 56 Prefisso cellulare destinatario
176
+ ('consignee_mobile_number', 10, True, False), # 57 Numero cellulare destinatario
177
+
178
+ # Altri campi (colonne 58-65)
179
+ ('is_insured_percentage', 1, True, False), # 58 is_ass_percentuale
180
+ ('barcode_service_return', 3, True, False), # 59 barcode_servizio_rit
181
+ ('shipment_type_id', 2, True, False), # 60 id_tipo_spedizione
182
+ ('detail_bs', 6, True, False), # 61 dettaglio_bs
183
+ ('notes_2', 50, True, False), # 62 Note 2
184
+ ('fractional_office_code', 11, True, False), # 63 Codice ufficio frazionario
185
+ ('customer_post_box', 11, True, False), # 64 Casella postale cliente
186
+ ('undelivered_action', 1, True, False) # 65 Mancata consegna
187
+ ]
188
+
189
+ # Genera il contenuto del file .dat
190
+ dat_content = []
191
+ for index, row in df_merged_unique_orders.iterrows():
192
+ record = []
193
+ for field_name, length, align_left, zero_fill in dat_format:
194
+ value = str(row.get(field_name, '')).strip() # Recupera il valore, converti in stringa e rimuovi spazi
195
+
196
+ # Gestione speciale per i campi numerici che potrebbero essere NaN
197
+ if field_name in ['num_packages', 'package_weight', 'package_width', 'package_height',
198
+ 'package_depth', 'cash_on_delivery_amount', 'insured_amount', 'shipment_value']:
199
+ try:
200
+ # Converti in float per gestire i decimali, poi formatta
201
+ num_value = float(value.replace('.', '')) # Rimuovi punti per la conversione
202
+ if field_name == 'cash_on_delivery_amount' or field_name == 'insured_amount' or field_name == 'shipment_value':
203
+ # Per importi con parte decimale, formatta con 2 decimali e il punto come separatore
204
+ value = f"{num_value:.2f}".replace('.', '') # Rimuovi il punto per il riempimento
205
+ value = value.replace(',','') # Rimuovi la virgola se presente
206
+ value = value.rjust(length, '0') # Riempi con zeri a sinistra
207
+ else:
208
+ value = str(int(num_value)).rjust(length, '0') # Per numeri interi, riempi con zeri
209
+ except ValueError:
210
+ value = '0'.rjust(length, '0') # Se non è un numero valido, riempi con zeri
211
+ else:
212
+ if align_left:
213
+ value = value.ljust(length)[:length] # Allinea a sinistra e tronca
214
+ else:
215
+ value = value.rjust(length)[:length] # Allinea a destra (default per non-zero-fill numerici), tronca
216
+
217
+ record.append(value)
218
+ dat_content.append("".join(record))
219
+
220
+ # Genera il nome del file
221
+ now = datetime.now()
222
+ filename_timestamp = now.strftime("%Y%m%d%H%M%S%f")[:-4] # AAAAMMGGhhmmsscc
223
+ dat_filename = f"SDA{filename_timestamp}.dat"
224
+ dis_filename = f"SDA{filename_timestamp}.dis"
225
+
226
+ dat_filepath = os.path.join(output_dir, dat_filename)
227
+ dis_filepath = os.path.join(output_dir, dis_filename)
228
+
229
+ # Scrivi il file .dat
230
+ with open(dat_filepath, 'w') as f:
231
+ for line in dat_content:
232
+ f.write(line + '\n')
233
+ print(f"File .dat generato con successo: {dat_filepath}")
234
+
235
+ # Crea il file .dis vuoto
236
+ with open(dis_filepath, 'w') as f:
237
+ pass # Crea un file vuoto
238
+ print(f"File .dis generato con successo: {dis_filepath}")
239
+
240
+ except FileNotFoundError as e:
241
+ print(f"Errore: File non trovato - {e}")
242
+ except ValueError as e:
243
+ print(f"Errore nei dati: {e}")
244
+ except Exception as e:
245
+ print(f"Si è verificato un errore inatteso: {e}")
246
+
247
+ # Esempio di utilizzo (assicurati di avere i tuoi file Excel nella stessa directory o specifica il percorso completo)
248
+ # Questi nomi di file sono esempi. Sostituiscili con i nomi reali dei tuoi file.
249
+ # shipping_mark_excel = "ShippingMark_Example.xlsx"
250
+ # shipment_order_excel = "ShipmentOrder_Example.xlsx"
251
+
252
+ # Per testare il codice, puoi creare dei file Excel fittizi con i nomi delle colonne come indicato
253
+ # e inserire alcuni dati di esempio.
254
+ # df_sm = pd.DataFrame({
255
+ # 'shippingMark': ['SM001', 'SM002'],
256
+ # 'orderRef': ['ORD123', 'ORD456']
257
+ # })
258
+ # df_sm.to_excel(shipping_mark_excel, index=False)
259
+
260
+ # df_so = pd.DataFrame({
261
+ # 'orderRef': ['ORD123', 'ORD456', 'ORD123'], # Esempio di riga duplicata per ORD123
262
+ # 'consignee_contact': ['Mario Rossi', 'Luigi Bianchi', 'Mario Rossi'],
263
+ # 'consignee_street_type': ['Via', 'Corso', 'Via'],
264
+ # 'consignee_address': ['Roma', 'Milano', 'Roma'],
265
+ # 'consignee_house_number': ['10', '5', '10'],
266
+ # 'consignee_phone': ['3331234567', '3457654321', '3331234567'],
267
+ # 'consignee_zip_code': ['00100', '20100', '00100'],
268
+ # 'consignee_city': ['Roma', 'Milano', 'Roma'],
269
+ # 'consignee_province': ['RM', 'MI', 'RM'],
270
+ # 'num_packages': [1, 2, 1],
271
+ # 'package_weight': [1000, 2500, 1000],
272
+ # 'package_width': [20, 30, 20],
273
+ # 'package_height': [15, 25, 15],
274
+ # 'package_depth': [10, 20, 10],
275
+ # 'service_code': ['EXT', 'INT', 'EXT'],
276
+ # 'product_ref_code': ['PRODXYZ', 'PRODABC', 'PRODXYZ'],
277
+ # 'consignee_ref_code': ['DEST001', 'DEST002', 'DEST001'],
278
+ # 'currency': ['EU', 'EU', 'EU'],
279
+ # 'cash_on_delivery_amount': [0.00, 50.50, 0.00],
280
+ # 'payment_type': ['', 'B', ''],
281
+ # 'notes': ['Note spedizione 1', 'Note spedizione 2', 'Note spedizione 1'],
282
+ # 'insured_amount': [0.00, 100.00, 0.00],
283
+ # 'package_id': ['SM001', 'SM002', 'SM001'],
284
+ # 'branch_code': ['01', '02', '01'],
285
+ # 'content_description': ['Libri', 'Abbigliamento', 'Libri'],
286
+ # 'content_type': ['D', 'P', 'D'],
287
+ # 'sender_country': ['ITA', 'ITA', 'ITA'],
288
+ # 'consignee_country': ['ITA', 'ITA', 'ITA'],
289
+ # 'shipment_value': [10.00, 150.00, 10.00],
290
+ # 'client_type': ['MGCS', 'MGCS', 'MGCS'],
291
+ # 'shipment_class': ['STD', 'EXP', 'STD'],
292
+ # 'duty_charge': ['M', 'D', 'M'],
293
+ # 'packaging_type': ['03', '02', '03'],
294
+ # 'fiscal_id': ['RSSMRA80A01H501F', 'BNCGGI80A01H501F', 'RSSMRA80A01H501F'],
295
+ # 'barcode_service': ['T12', '', 'T12'],
296
+ # 'consignee_email': ['mario.rossi@example.com', 'luigi.bianchi@example.com', 'mario.rossi@example.com'],
297
+ # 'consignee_mobile_prefix': ['+39', '+39', '+39'],
298
+ # 'consignee_mobile_number': ['1234567890', '0987654321', '1234567890'],
299
+ # 'is_insured_percentage': ['N', 'S', 'N'],
300
+ # 'barcode_service_return': ['', '', ''],
301
+ # 'shipment_type_id': ['C', 'C', 'C'],
302
+ # 'detail_bs': ['', '', ''],
303
+ # 'notes_2': ['Seconda nota 1', 'Seconda nota 2', 'Seconda nota 1'],
304
+ # 'fractional_office_code': ['', '', ''],
305
+ # 'customer_post_box': ['', '', ''],
306
+ # 'undelivered_action': ['R', 'A', 'R']
307
+ # })
308
+ # df_so.to_excel(shipment_order_excel, index=False)
309
+
310
+ # Esegui la funzione
311
+ # generate_poste_dat_file(shipping_mark_excel, shipment_order_excel)
312
+
313
+ # Esempio di come potresti richiamare la funzione con i nomi dei file effettivi
314
+ # Assicurati che i file .xlsx siano caricati nella stessa directory dello script o fornisci il percorso completo
315
+ # shipping_mark_file_path = "ShippingMark_Example.xlsx" # Sostituisci con il nome del tuo file shipping mark
316
+ # shipment_order_file_path = "ShipmentOrder_Example.xlsx" # Sostituisci con il nome del tuo file shipment order
317
+
318
+ # Esempio di utilizzo:
319
+ # generate_poste_dat_file(shipping_mark_file_path, shipment_order_file_path)
320
+