kmr24 commited on
Commit
3b7e8a2
·
verified ·
1 Parent(s): 7c4a59b

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +552 -0
app.py ADDED
@@ -0,0 +1,552 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from pymongo import MongoClient
3
+ from datetime import datetime
4
+ import pandas as pd
5
+
6
+ # MongoDB connection details
7
+ MONGO_URI = "mongodb+srv://kmrlogistics:[email protected]/"
8
+ DB_NAME = "trucking"
9
+ COLLECTION_NAME_DRIVERS = "drivers"
10
+ COLLECTION_NAME_TRUCKS = "trucks"
11
+ COLLECTION_NAME_OWNER_OPERATORS = "owner_operators"
12
+
13
+ # Establish a connection to MongoDB
14
+ client = MongoClient(MONGO_URI)
15
+ db = client[DB_NAME]
16
+ drivers_collection = db[COLLECTION_NAME_DRIVERS]
17
+ trucks_collection = db[COLLECTION_NAME_TRUCKS]
18
+ owner_operators_collection = db[COLLECTION_NAME_OWNER_OPERATORS]
19
+
20
+ # User authentication function
21
+ def login(username, password):
22
+ """Check the provided username and password."""
23
+ return username == "KMR LOGISTICS" and password == "kmr2024"
24
+
25
+ # Initialize Streamlit session state for login
26
+ if "logged_in" not in st.session_state:
27
+ st.session_state.logged_in = False
28
+
29
+ # Streamlit app layout
30
+ st.title("Kmr Logistics Management")
31
+
32
+ # Login section
33
+ st.sidebar.header("User Login")
34
+
35
+ if not st.session_state.logged_in:
36
+ username = st.sidebar.text_input("Username")
37
+ password = st.sidebar.text_input("Password", type="password")
38
+
39
+ if st.sidebar.button("Login"):
40
+ if login(username, password):
41
+ st.session_state.logged_in = True
42
+ st.sidebar.success("Logged in successfully!")
43
+ else:
44
+ st.sidebar.error("Invalid username or password.")
45
+ else:
46
+ st.sidebar.success("Logged in as kmr logistics.")
47
+
48
+ # Show the main application only if the user is logged in
49
+ if st.session_state.logged_in:
50
+ # Page navigation
51
+ page = st.sidebar.selectbox("Select a page", [
52
+ "Add Truck",
53
+ "Delete Truck",
54
+ "Add Driver",
55
+ "Delete Driver",
56
+ "Add Owner Operator",
57
+ "Delete Owner Operator",
58
+ "Assign Truck",
59
+ "Add Load",
60
+ "Update/Delete Load",
61
+ "View Owner Operator Info",
62
+ "View Information"
63
+ ])
64
+
65
+ if page == "Add Truck":
66
+ st.header("Add Truck Information")
67
+ truck_name = st.text_input("Truck Name")
68
+ truck_plate_number = st.text_input("Truck Plate Number")
69
+
70
+ if st.button("Save Truck Info"):
71
+ if truck_name and truck_plate_number:
72
+ # Check if truck exists
73
+ existing_truck = trucks_collection.find_one({"truck_plate_number": truck_plate_number})
74
+ if existing_truck:
75
+ st.warning(f"Truck with Plate Number {truck_plate_number} already exists.")
76
+ else:
77
+ truck_data = {
78
+ "truck_name": truck_name,
79
+ "truck_plate_number": truck_plate_number
80
+ }
81
+ trucks_collection.insert_one(truck_data)
82
+ st.success(f"Truck {truck_name} added successfully!")
83
+ else:
84
+ st.error("Please fill in all fields.")
85
+
86
+ elif page == "Delete Truck":
87
+ st.header("Delete Truck")
88
+ trucks = list(trucks_collection.find({}, {"truck_name": 1, "truck_plate_number": 1}))
89
+ truck_names = [f"{t.get('truck_name', '')} ({t.get('truck_plate_number', '')})" for t in trucks]
90
+
91
+ selected_truck = st.selectbox("Select Truck to Delete", truck_names)
92
+
93
+ if st.button("Delete Truck"):
94
+ if selected_truck:
95
+ truck_plate_number = selected_truck.split(" (")[1][:-1]
96
+ trucks_collection.delete_one({"truck_plate_number": truck_plate_number})
97
+ st.success(f"Truck {selected_truck} deleted successfully!")
98
+ else:
99
+ st.error("Please select a truck to delete.")
100
+
101
+ elif page == "Add Driver":
102
+ st.header("Add Driver Information")
103
+ first_name = st.text_input("First Name")
104
+ last_name = st.text_input("Last Name")
105
+ contact_info = st.text_input("Contact Info")
106
+ pay_per_mile = st.number_input("Driver Pay per Mile", min_value=0.0, format="%f")
107
+
108
+ if st.button("Save Driver Info"):
109
+ if first_name and last_name and contact_info and pay_per_mile:
110
+ full_name = f"{first_name} {last_name}"
111
+
112
+ # Check if driver exists
113
+ existing_driver = drivers_collection.find_one({"contact_info": contact_info})
114
+ if existing_driver:
115
+ st.warning(f"Driver with Contact Info {contact_info} already exists.")
116
+ else:
117
+ driver_data = {
118
+ "first_name": first_name,
119
+ "last_name": last_name,
120
+ "contact_info": contact_info,
121
+ "pay_per_mile": pay_per_mile,
122
+ "trucks": [],
123
+ "loads": []
124
+ }
125
+ drivers_collection.insert_one(driver_data)
126
+ st.success(f"Driver {full_name} added successfully!")
127
+ else:
128
+ st.error("Please fill in all fields.")
129
+
130
+ elif page == "Delete Driver":
131
+ st.header("Delete Driver")
132
+ drivers = list(drivers_collection.find({}, {"first_name": 1, "last_name": 1}))
133
+ driver_names = [f"{d.get('first_name', '')} {d.get('last_name', '')}" for d in drivers]
134
+
135
+ selected_driver = st.selectbox("Select Driver to Delete", driver_names)
136
+
137
+ if st.button("Delete Driver"):
138
+ if selected_driver:
139
+ first_name, last_name = selected_driver.split()
140
+ drivers_collection.delete_one({"first_name": first_name, "last_name": last_name})
141
+ st.success(f"Driver {selected_driver} deleted successfully!")
142
+ else:
143
+ st.error("Please select a driver to delete.")
144
+
145
+ elif page == "Add Owner Operator":
146
+ st.header("Add Owner Operator")
147
+ name = st.text_input("Owner Operator Name")
148
+ contact_info = st.text_input("Contact Number")
149
+ company_percentage = st.number_input("Company Percentage", min_value=0.0, max_value=100.0, format="%f")
150
+
151
+ if st.button("Save Owner Operator Info"):
152
+ if name and contact_info and company_percentage:
153
+ # Check if owner operator exists
154
+ existing_owner_operator = owner_operators_collection.find_one({"contact_info": contact_info})
155
+ if existing_owner_operator:
156
+ st.warning(f"Owner Operator with Contact Number {contact_info} already exists.")
157
+ else:
158
+ owner_operator_data = {
159
+ "name": name,
160
+ "contact_info": contact_info,
161
+ "company_percentage": company_percentage,
162
+ "trucks": [],
163
+ "loads": []
164
+ }
165
+ owner_operators_collection.insert_one(owner_operator_data)
166
+ st.success(f"Owner Operator {name} added successfully!")
167
+ else:
168
+ st.error("Please fill in all fields.")
169
+
170
+ elif page == "Delete Owner Operator":
171
+ st.header("Delete Owner Operator")
172
+ owner_operators = list(owner_operators_collection.find({}, {"name": 1}))
173
+ owner_operator_names = [o.get('name', '') for o in owner_operators]
174
+
175
+ selected_owner_operator = st.selectbox("Select Owner Operator to Delete", owner_operator_names)
176
+
177
+ if st.button("Delete Owner Operator"):
178
+ if selected_owner_operator:
179
+ owner_operators_collection.delete_one({"name": selected_owner_operator})
180
+ st.success(f"Owner Operator {selected_owner_operator} deleted successfully!")
181
+ else:
182
+ st.error("Please select an owner operator to delete.")
183
+
184
+ elif page == "Assign Truck":
185
+ st.header("Assign Truck to Driver or Owner Operator")
186
+ drivers = list(drivers_collection.find({}, {"first_name": 1, "last_name": 1}))
187
+ owner_operators = list(owner_operators_collection.find({}, {"name": 1}))
188
+
189
+ driver_names = [f"Driver: {d.get('first_name', '')} {d.get('last_name', '')}" for d in drivers]
190
+ owner_operator_names = [f"Owner Operator: {o.get('name', '')}" for o in owner_operators]
191
+
192
+ all_names = driver_names + owner_operator_names
193
+
194
+ selected_name = st.selectbox("Select Driver or Owner Operator", all_names)
195
+ trucks = list(trucks_collection.find({}, {"truck_name": 1, "truck_plate_number": 1}))
196
+ truck_names = [f"{t.get('truck_name', '')} ({t.get('truck_plate_number', '')})" for t in trucks]
197
+
198
+ selected_truck_name = st.selectbox("Select Truck", truck_names)
199
+
200
+ if st.button("Assign Truck"):
201
+ if selected_name and selected_truck_name:
202
+ selected_truck = next(t for t in trucks if f"{t.get('truck_name', '')} ({t.get('truck_plate_number', '')})" == selected_truck_name)
203
+ truck_plate_number = selected_truck["truck_plate_number"]
204
+
205
+ if selected_name.startswith("Driver:"):
206
+ selected_driver = next(d for d in drivers if f"Driver: {d.get('first_name', '')} {d.get('last_name', '')}" == selected_name)
207
+ # Update driver record to include truck
208
+ drivers_collection.update_one(
209
+ {"_id": selected_driver["_id"]},
210
+ {"$addToSet": {"trucks": truck_plate_number}}
211
+ )
212
+ st.success(f"Truck {selected_truck_name} assigned to Driver {selected_name.split(': ')[1]} successfully!")
213
+
214
+ elif selected_name.startswith("Owner Operator:"):
215
+ selected_owner_operator = next(o for o in owner_operators if f"Owner Operator: {o.get('name', '')}" == selected_name)
216
+ # Update owner operator record to include truck
217
+ owner_operators_collection.update_one(
218
+ {"_id": selected_owner_operator["_id"]},
219
+ {"$addToSet": {"trucks": truck_plate_number}}
220
+ )
221
+ st.success(f"Truck {selected_truck_name} assigned to Owner Operator {selected_name.split(': ')[1]} successfully!")
222
+ else:
223
+ st.error("Please select both a driver/owner operator and a truck.")
224
+
225
+ elif page == "Add Load":
226
+ st.header("Add Load Information")
227
+
228
+ # Fetch drivers, owner operators, and trucks
229
+ drivers = list(drivers_collection.find({}, {"first_name": 1, "last_name": 1, "trucks": 1, "contact_info": 1, "pay_per_mile": 1}))
230
+ owner_operators = list(owner_operators_collection.find({}, {"name": 1, "trucks": 1, "contact_info": 1, "company_percentage": 1}))
231
+
232
+ driver_names = [f"Driver: {d.get('first_name', '')} {d.get('last_name', '')}" for d in drivers]
233
+ owner_operator_names = [f"Owner Operator: {o.get('name', '')}" for o in owner_operators]
234
+
235
+ all_names = driver_names + owner_operator_names
236
+
237
+ selected_names = st.multiselect("Select Driver(s) or Owner Operator(s)", all_names, max_selections=2)
238
+
239
+ if selected_names:
240
+ involved_drivers = []
241
+ involved_owner_operators = []
242
+ truck_numbers = []
243
+
244
+ for selected_name in selected_names:
245
+ if selected_name.startswith("Driver:"):
246
+ selected_driver = next(d for d in drivers if f"Driver: {d.get('first_name', '')} {d.get('last_name', '')}" == selected_name)
247
+ involved_drivers.append(selected_driver)
248
+ truck_numbers.extend(selected_driver.get('trucks', []))
249
+ elif selected_name.startswith("Owner Operator:"):
250
+ selected_owner_operator = next(o for o in owner_operators if f"Owner Operator: {o.get('name', '')}" == selected_name)
251
+ involved_owner_operators.append(selected_owner_operator)
252
+ truck_numbers.extend(selected_owner_operator.get('trucks', []))
253
+
254
+ trucks_display = [
255
+ f"{t['truck_name']} ({t['truck_plate_number']})"
256
+ for t in trucks_collection.find({"truck_plate_number": {"$in": truck_numbers}})
257
+ ]
258
+
259
+ selected_truck_display = st.selectbox("Select Truck for Load", trucks_display)
260
+
261
+ if selected_truck_display:
262
+ selected_truck_no = selected_truck_display.split(" (")[1][:-1]
263
+
264
+ load_id = st.text_input("Load ID")
265
+ date_from = st.date_input("Date From", datetime.now())
266
+ date_to = st.date_input("Date To", datetime.now())
267
+ original_miles = st.number_input("Original Miles", min_value=0)
268
+ bobtail = st.number_input("Bobtail Miles", min_value=0)
269
+ payout = st.number_input("Payout", min_value=0.0, format="%f")
270
+ fuel_cost = st.number_input("Fuel Cost", min_value=0.0, format="%f")
271
+
272
+ actual_miles = original_miles - bobtail
273
+
274
+ driver_payments = []
275
+ final_payout = payout
276
+
277
+ if involved_drivers:
278
+ for driver in involved_drivers:
279
+ driver_pay_per_mile = driver.get("pay_per_mile", 0)
280
+ driver_pay = actual_miles * driver_pay_per_mile / len(involved_drivers) # Split pay between drivers
281
+ driver_payments.append(driver_pay)
282
+ final_payout -= driver_pay
283
+
284
+ if involved_owner_operators:
285
+ for owner_operator in involved_owner_operators:
286
+ company_percentage = owner_operator.get("company_percentage", 0)
287
+ pay_percent = (payout * company_percentage) / 100
288
+ driver_payments.append(pay_percent)
289
+ final_payout -= pay_percent
290
+
291
+ if st.button("Save Load Info"):
292
+ # Check if the load ID already exists
293
+ existing_load = drivers_collection.find_one({"loads.load_id": load_id}) or owner_operators_collection.find_one({"loads.load_id": load_id})
294
+ if existing_load:
295
+ st.warning(f"Load ID {load_id} already exists. Please use a unique Load ID.")
296
+ else:
297
+ load_data = {
298
+ "truck_no": selected_truck_no,
299
+ "truck_name": selected_truck_display.split(" (")[0],
300
+ "load_id": load_id,
301
+ "date_from": date_from.strftime("%Y-%m-%d"),
302
+ "date_to": date_to.strftime("%Y-%m-%d"),
303
+ "original_miles": original_miles,
304
+ "bobtail": bobtail,
305
+ "actual_miles": actual_miles,
306
+ "payout": payout,
307
+ "fuel_cost": fuel_cost,
308
+ "driver_pay": sum(driver_payments),
309
+ "final_payout": final_payout
310
+ }
311
+
312
+ # Assign the load to each driver involved
313
+ for driver in involved_drivers:
314
+ drivers_collection.update_one(
315
+ {"_id": driver["_id"]},
316
+ {"$push": {"loads": load_data}}
317
+ )
318
+ # Assign the load to each owner operator involved
319
+ for owner_operator in involved_owner_operators:
320
+ owner_operators_collection.update_one(
321
+ {"_id": owner_operator["_id"]},
322
+ {"$push": {"loads": load_data}}
323
+ )
324
+
325
+ st.success(f"Load information added successfully for the selected drivers/owner operators with Truck {selected_truck_display.split(' (')[0]}!")
326
+
327
+ elif page == "Update/Delete Load":
328
+ st.header("Update or Delete Load")
329
+
330
+ load_id = st.text_input("Enter Load ID to Update or Delete")
331
+
332
+ if load_id:
333
+ # Search for the load across all drivers and owner operators
334
+ driver_record = drivers_collection.find_one({"loads.load_id": load_id}, {"loads.$": 1, "first_name": 1, "last_name": 1})
335
+ owner_operator_record = owner_operators_collection.find_one({"loads.load_id": load_id}, {"loads.$": 1, "name": 1})
336
+
337
+ if driver_record:
338
+ load_data = driver_record["loads"][0]
339
+ entity_type = "driver"
340
+ entity_name = f"{driver_record['first_name']} {driver_record['last_name']}"
341
+ elif owner_operator_record:
342
+ load_data = owner_operator_record["loads"][0]
343
+ entity_type = "owner_operator"
344
+ entity_name = owner_operator_record["name"]
345
+ else:
346
+ load_data = None
347
+
348
+ if load_data:
349
+ st.write(f"Load found for {entity_type.capitalize()}: {entity_name}")
350
+
351
+ # Display load information
352
+ load_data_display = {
353
+ "Truck No": load_data["truck_no"],
354
+ "Load ID": load_data["load_id"],
355
+ "Date From": load_data["date_from"],
356
+ "Date To": load_data["date_to"],
357
+ "Original Miles": load_data["original_miles"],
358
+ "Bobtail Miles": load_data["bobtail"],
359
+ "Payout": load_data["payout"],
360
+ "Fuel Cost": load_data["fuel_cost"],
361
+ "Driver/Owner Operator Pay": load_data["driver_pay"],
362
+ "Final Payout": load_data["final_payout"]
363
+ }
364
+
365
+ for key, value in load_data_display.items():
366
+ st.write(f"{key}: {value}")
367
+
368
+ # Input fields for updating the load
369
+ st.subheader("Update Load Information")
370
+ date_from = st.date_input("Date From", datetime.strptime(load_data["date_from"], "%Y-%m-%d"))
371
+ date_to = st.date_input("Date To", datetime.strptime(load_data["date_to"], "%Y-%m-%d"))
372
+ original_miles = st.number_input("Original Miles", value=load_data["original_miles"], min_value=0)
373
+ bobtail = st.number_input("Bobtail Miles", value=load_data["bobtail"], min_value=0)
374
+ payout = st.number_input("Payout", value=load_data["payout"], min_value=0.0, format="%f")
375
+ fuel_cost = st.number_input("Fuel Cost", value=load_data["fuel_cost"], min_value=0.0, format="%f")
376
+
377
+ actual_miles = original_miles - bobtail
378
+
379
+ if entity_type == "driver":
380
+ driver_pay = actual_miles * driver_record["loads"][0]["driver_pay"] / load_data["actual_miles"]
381
+ final_payout = payout - driver_pay
382
+
383
+ elif entity_type == "owner_operator":
384
+ company_percentage = owner_operator_record["loads"][0].get("company_percentage", 0)
385
+ pay_percent = (payout * company_percentage) / 100
386
+ driver_pay = pay_percent
387
+ final_payout = payout - pay_percent
388
+
389
+ if st.button("Update Load"):
390
+ # Update the load with new values
391
+ updated_load_data = {
392
+ "loads.$.date_from": date_from.strftime("%Y-%m-%d"),
393
+ "loads.$.date_to": date_to.strftime("%Y-%m-%d"),
394
+ "loads.$.original_miles": original_miles,
395
+ "loads.$.bobtail": bobtail,
396
+ "loads.$.actual_miles": actual_miles,
397
+ "loads.$.payout": payout,
398
+ "loads.$.fuel_cost": fuel_cost,
399
+ "loads.$.driver_pay": driver_pay,
400
+ "loads.$.final_payout": final_payout
401
+ }
402
+
403
+ if entity_type == "driver":
404
+ drivers_collection.update_one(
405
+ {"_id": driver_record["_id"], "loads.load_id": load_id},
406
+ {"$set": updated_load_data}
407
+ )
408
+ st.success(f"Load ID {load_id} updated successfully!")
409
+ elif entity_type == "owner_operator":
410
+ owner_operators_collection.update_one(
411
+ {"_id": owner_operator_record["_id"], "loads.load_id": load_id},
412
+ {"$set": updated_load_data}
413
+ )
414
+ st.success(f"Load ID {load_id} updated successfully!")
415
+
416
+ if st.button("Delete Load"):
417
+ # Remove the load from the driver's or owner operator's record
418
+ if entity_type == "driver":
419
+ drivers_collection.update_one(
420
+ {"_id": driver_record["_id"]},
421
+ {"$pull": {"loads": {"load_id": load_id}}}
422
+ )
423
+ st.success(f"Load ID {load_id} deleted successfully!")
424
+ elif entity_type == "owner_operator":
425
+ owner_operators_collection.update_one(
426
+ {"_id": owner_operator_record["_id"]},
427
+ {"$pull": {"loads": {"load_id": load_id}}}
428
+ )
429
+ st.success(f"Load ID {load_id} deleted successfully!")
430
+ else:
431
+ st.warning(f"No load found with Load ID {load_id}.")
432
+
433
+ elif page == "View Owner Operator Info":
434
+ st.header("View Owner Operator Information")
435
+
436
+ owner_operators = list(owner_operators_collection.find({}))
437
+ owner_operator_names = [o.get('name', '') for o in owner_operators]
438
+
439
+ selected_owner_operator_name = st.selectbox("Select Owner Operator to View", owner_operator_names)
440
+
441
+ if selected_owner_operator_name:
442
+ owner_operator_record = owner_operators_collection.find_one({"name": selected_owner_operator_name})
443
+
444
+ if owner_operator_record:
445
+ st.write(f"**Name**: {owner_operator_record['name']}")
446
+ st.write(f"**Contact Number**: {owner_operator_record['contact_info']}")
447
+ st.write(f"**Company Percentage**: {owner_operator_record['company_percentage']}%")
448
+ st.write(f"**Trucks Assigned**: {', '.join(owner_operator_record['trucks']) if owner_operator_record['trucks'] else 'None'}")
449
+
450
+ # Date range input
451
+ date_from = st.date_input("Date From", datetime.now())
452
+ date_to = st.date_input("Date To", datetime.now())
453
+
454
+ # Convert the date input from Streamlit to Pandas datetime
455
+ date_from = pd.to_datetime(date_from)
456
+ date_to = pd.to_datetime(date_to)
457
+
458
+ # Display loads associated with this owner operator within the date range
459
+ if "loads" in owner_operator_record and owner_operator_record["loads"]:
460
+ load_df = pd.DataFrame(owner_operator_record["loads"])
461
+ load_df["date_from"] = pd.to_datetime(load_df["date_from"])
462
+ load_df["date_to"] = pd.to_datetime(load_df["date_to"])
463
+
464
+ # Filter by date range
465
+ filtered_load_df = load_df[(load_df["date_from"] >= date_from) & (load_df["date_to"] <= date_to)]
466
+
467
+ if not filtered_load_df.empty:
468
+ st.subheader("Load Information")
469
+ st.dataframe(filtered_load_df)
470
+
471
+ # Total Calculations
472
+ total_payout = filtered_load_df["payout"].sum()
473
+ total_company_fee = filtered_load_df["driver_pay"].sum()
474
+ total_final_payout = filtered_load_df["final_payout"].sum()
475
+ total_fuel_cost = filtered_load_df["fuel_cost"].sum()
476
+ total_final_payout_after_fuel = total_final_payout - total_fuel_cost
477
+
478
+ st.subheader("Total Calculations")
479
+ st.write(f"Total Payout: ${total_payout:.2f}")
480
+ st.write(f"Total Company Fee: ${total_company_fee:.2f}")
481
+ st.write(f"Total Final Payout after Fuel Cost: ${total_final_payout_after_fuel:.2f}")
482
+ st.write(f"Total Fuel Cost: ${total_fuel_cost:.2f}")
483
+ else:
484
+ st.write("No loads found in the selected date range.")
485
+ else:
486
+ st.write("No loads associated with this Owner Operator.")
487
+
488
+ elif page == "View Information":
489
+ st.header("View Load Information by Truck Name")
490
+
491
+ trucks = list(trucks_collection.find({}, {"truck_name": 1, "truck_plate_number": 1}))
492
+ truck_names = [f"{t.get('truck_name', '')} ({t.get('truck_plate_number', '')})" for t in trucks]
493
+
494
+ selected_truck_name_view = st.selectbox("Select Truck Name to View Records", truck_names)
495
+
496
+ if selected_truck_name_view:
497
+ truck_record = trucks_collection.find_one({"truck_name": selected_truck_name_view.split(" ")[0]})
498
+ if truck_record:
499
+ truck_plate_number = truck_record["truck_plate_number"]
500
+
501
+ date_from = st.date_input("Date From", datetime.now())
502
+ date_to = st.date_input("Date To", datetime.now())
503
+
504
+ # Filter load records for the selected truck and date range
505
+ loads_view = drivers_collection.aggregate([
506
+ {"$match": {"trucks": truck_plate_number}},
507
+ {"$unwind": "$loads"},
508
+ {"$match": {
509
+ "loads.truck_no": truck_plate_number,
510
+ "loads.date_from": {"$gte": date_from.strftime("%Y-%m-%d")},
511
+ "loads.date_to": {"$lte": date_to.strftime("%Y-%m-%d")}
512
+ }}
513
+ ])
514
+
515
+ # Group loads by driver or owner operator
516
+ load_data_view = list(loads_view)
517
+ if load_data_view:
518
+ # Create a dataframe for each driver/owner operator
519
+ entity_data = {}
520
+ for load in load_data_view:
521
+ driver_name = f"{load['first_name']} {load['last_name']}" if "first_name" in load else load.get("name", "")
522
+ if driver_name not in entity_data:
523
+ entity_data[driver_name] = []
524
+ entity_data[driver_name].append(load['loads'])
525
+
526
+ for entity_name, loads in entity_data.items():
527
+ st.subheader(f"Driver : {entity_name}")
528
+
529
+ load_df = pd.DataFrame(loads)
530
+
531
+ st.dataframe(load_df)
532
+
533
+ total_original_miles = load_df["original_miles"].sum()
534
+ total_actual_miles = load_df["actual_miles"].sum()
535
+ total_payout = load_df["payout"].sum()
536
+ total_driver_pay = load_df["driver_pay"].sum()
537
+ total_fuel_cost = load_df["fuel_cost"].sum()
538
+
539
+ st.subheader("Total Calculations")
540
+ st.write(f"Total Original Miles: {total_original_miles}")
541
+ st.write(f"Total Actual Miles: {total_actual_miles}")
542
+ st.write(f"Total Payout: ${total_payout:.2f}")
543
+ st.write(f"Total Pay to Driver: ${total_driver_pay:.2f}")
544
+ st.write(f"Total Fuel Cost: ${total_fuel_cost:.2f}")
545
+
546
+ # Option to save the results to a CSV file
547
+ if st.button(f"Save Results to CSV for {entity_name}"):
548
+ csv_filename = f"{entity_name.replace(' ', '_')}_load_data_summary.csv"
549
+ load_df.to_csv(csv_filename, index=False)
550
+ st.success(f"Results saved to {csv_filename}")
551
+ else:
552
+ st.warning(f"No load records found for Truck {selected_truck_name_view.split(' ')[0]} between {date_from} and {date_to}.")