Ninoglli/API-ORM
1
1import gradio as gr
2import requests
3import json
4import os
5
6# --- Funzioni di salvataggio/caricamento ---
7def save_data(api_key, cust_acc_number, rq_cust_acc_number):
8 """Salva i dati in un file di testo."""
9 with open("config.txt", "w") as f:
10 f.write(f"api_key={api_key}\n")
11 f.write(f"cust_acc_number={cust_acc_number}\n")
12 f.write(f"rq_cust_acc_number={rq_cust_acc_number}\n")
13
14def load_data():
15 """Carica i dati da un file di testo, se esiste."""
16 data = {
17 "api_key": "",
18 "cust_acc_number": "0497777",
19 "rq_cust_acc_number": "0497777000"
20 }
21 if os.path.exists("config.txt"):
22 with open("config.txt", "r") as f:
23 for line in f:
24 if "=" in line:
25 key, value = line.strip().split("=", 1)
26 if key in data:
27 data[key] = value
28 return data
29
30# Carica i dati all'avvio dello script
31config = load_data()
32
33# --- Funzione principale per l'API ---
34def send_api_request(
35 token,
36 cust_acc_number,
37 rq_cust_acc_number,
38 parcel_count,
39 # Campi del mittente (Sender)
40 comp_name_sender,
41 street_sender,
42 state_sender,
43 country_code_sender,
44 zip_code_sender,
45 city_sender,
46 phone_sender,
47 contact_person_sender,
48 # Campi del destinatario (Receiver)
49 comp_name_receiver,
50 street_receiver,
51 state_receiver,
52 country_code_receiver,
53 zip_code_receiver,
54 city_receiver,
55 # Altri campi
56 collection_date,
57 good_description,
58 weight_kg,
59 cash_on_delivery,
60 commissioned_status,
61 collection_time,
62 alert_type,
63 alert_mail,
64 alert_sms
65):
66 """
67 Raccoglie i dati, costruisce il payload JSON e invia la richiesta POST all'API.
68 """
69
70 save_data(token, cust_acc_number, rq_cust_acc_number)
71
72 try:
73 weight_kg = float(weight_kg)
74 parcel_count = int(parcel_count)
75 cash_on_delivery = float(cash_on_delivery) if cash_on_delivery is not None else 0
76 except (ValueError, TypeError):
77 return "Errore: Il peso, il numero di pacchi e il contrassegno devono essere numeri validi."
78
79 payload = [{
80 "requestInfos": {
81 "parcelCount": parcel_count,
82 "collectionDate": collection_date
83 },
84 "customerInfos": {
85 "custAccNumber": cust_acc_number
86 },
87 "stakeholders": [
88 {
89 "type": "RQ",
90 "customerInfos": {
91 "custAccNumber": rq_cust_acc_number
92 }
93 },
94 {
95 "type": "SE",
96 "address": {
97 "compName": comp_name_sender,
98 "street": street_sender,
99 "state": state_sender,
100 "countryCode": country_code_sender,
101 "zipCode": zip_code_sender,
102 "city": city_sender
103 },
104 "contact": {
105 "contactDetails": {
106 "phone": phone_sender,
107 "contactPerson": contact_person_sender
108 }
109 }
110 },
111 {
112 "type": "RE",
113 "address": {
114 "compName": comp_name_receiver,
115 "street": street_receiver,
116 "state": state_receiver,
117 "countryCode": country_code_receiver,
118 "zipCode": zip_code_receiver,
119 "city": city_receiver
120 }
121 }
122 ],
123 "brtSpec": {
124 "goodDescription": good_description,
125 "commissioned": commissioned_status,
126 "payerType": "Ordering",
127 "collectionTime": collection_time,
128 "alerts": [
129 {
130 "type": alert_type,
131 "sms": alert_sms,
132 "mail": alert_mail
133 }
134 ],
135 "weightKG": weight_kg,
136 "openingHours": [
137 {
138 "from": "10:00",
139 "to": "13:00"
140 },
141 {
142 "from": "15:00",
143 "to": "17:00"
144 }
145 ]
146 }
147 }]
148
149 if cash_on_delivery > 0:
150 payload[0]["brtSpec"]["cashOnDeliveryAmount"] = {
151 "value": cash_on_delivery,
152 "currency": "EUR"
153 }
154 payload[0]["brtSpec"]["payeeType"] = "Sender"
155
156 api_url = "https://api.brt.it/orm/api/geodata/v410/colreqs"
157 headers = {
158 'Content-Type': 'application/json',
159 'X-Api-Key': token
160 }
161
162 print("JSON che sta per essere inviato:\n")
163 print(json.dumps(payload, indent=4))
164 print("\n------------------------------\n")
165
166 try:
167 response = requests.post(api_url, data=json.dumps(payload), headers=headers)
168 response.raise_for_status()
169 return f"Richiesta inviata con successo!\n\nRisposta del server:\n{response.text}"
170 except requests.exceptions.RequestException as e:
171 return f"Errore di rete o del server: {e}"
172 except json.JSONDecodeError:
173 return f"Errore: La risposta dell'API non è un JSON valido.\n\nContenuto: {response.text}"
174
175# --- Creazione dell'interfaccia Gradio ---
176iface = gr.Interface(
177 fn=send_api_request,
178 inputs=[
179 gr.Textbox(label="API Key", type="password", value=config["api_key"]),
180 gr.Textbox(label="Codice cliente BRT", value=config["cust_acc_number"]),
181 gr.Textbox(label="Codice cliente Ordinante", value=config["rq_cust_acc_number"]),
182 gr.Number(label="Numero di pacchi", value=1),
183 # Mittente
184 gr.Textbox(label="Nome Azienda (Mittente)"),
185 gr.Textbox(label="Via (Mittente)"),
186 gr.Textbox(label="Provincia (Mittente)"),
187 gr.Textbox(label="Country Code (Mittente)", value="IT"),
188 gr.Textbox(label="CAP (Mittente)"),
189 gr.Textbox(label="Città (Mittente)"),
190 gr.Textbox(label="Telefono (Mittente)"),
191 gr.Textbox(label="Persona di contatto (Mittente)"),
192 # Destinatario
193 gr.Textbox(label="Nome Azienda (Destinatario)"),
194 gr.Textbox(label="Via (Destinatario)"),
195 gr.Textbox(label="Provincia (Destinatario)"),
196 gr.Textbox(label="Country Code (Destinatario)", value="IT"),
197 gr.Textbox(label="CAP (Destinatario)"),
198 gr.Textbox(label="Città (Destinatario)"),
199 # Altri campi
200 gr.Textbox(label="Data di ritiro (YYYY-MM-DD)", value="2025-01-10"),
201 gr.Textbox(label="Descrizione merce", value="Varie"),
202 gr.Number(label="Peso (KG)", value=1.0),
203 gr.Number(label="Contrassegno (€)", value=0),
204 gr.Checkbox(label="Commissionato", value=True),
205 gr.Textbox(label="Ora di ritiro (HH:mm)", value="10:00"),
206 # Alert
207 gr.Dropdown(label="Tipo Alert", choices=["COMMISSIONED", "CONFIRM"], value="COMMISSIONED"),
208 gr.Textbox(label="Email per alert", value="test@test.it"),
209 gr.Textbox(label="SMS per alert", value="")
210 ],
211 outputs="text",
212 title="Client API Gestione Ordini BRT",
213 description="Inserisci i dettagli dell'ordine per inviare una richiesta all'API BRT."
214)
215
216iface.launch(server_name="0.0.0.0", server_port=7860, share=True)