File size: 26,631 Bytes
6a808d5
21db5e9
34e5fc6
72726e0
dda1cd6
 
21db5e9
 
 
a23c7e1
dda1cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72726e0
21db5e9
dda1cd6
21db5e9
72726e0
 
 
21db5e9
9e93492
3f2e2d5
 
72726e0
6a808d5
afaddb4
 
 
21db5e9
 
 
afaddb4
 
21db5e9
 
6a808d5
dda1cd6
6a808d5
 
 
21db5e9
6a808d5
dda1cd6
6a808d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21db5e9
6a808d5
 
 
 
 
 
 
21db5e9
 
 
 
 
 
 
 
 
 
 
 
6a808d5
21db5e9
 
 
 
 
 
6a808d5
 
21db5e9
6a808d5
 
 
 
 
 
21db5e9
 
 
 
 
 
6a808d5
 
21db5e9
6a808d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21db5e9
 
 
6a808d5
 
 
 
 
 
 
21db5e9
 
6a808d5
 
3a7f864
21db5e9
6a808d5
21db5e9
3a7f864
 
21db5e9
 
3a7f864
 
 
 
 
 
6a808d5
 
 
21db5e9
3a7f864
21db5e9
 
 
 
 
 
 
 
 
 
dda1cd6
 
 
 
21db5e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
463d47b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21db5e9
463d47b
21db5e9
 
 
 
 
3a7f864
 
 
 
463d47b
21db5e9
463d47b
 
21db5e9
dda1cd6
21db5e9
 
 
 
 
dda1cd6
21db5e9
 
 
 
 
dda1cd6
21db5e9
 
 
 
 
 
 
dda1cd6
21db5e9
 
 
 
 
 
 
dda1cd6
 
21db5e9
 
 
dda1cd6
21db5e9
dda1cd6
 
 
21db5e9
 
 
 
 
 
dda1cd6
21db5e9
dda1cd6
21db5e9
 
dda1cd6
21db5e9
 
 
 
 
 
 
 
dda1cd6
21db5e9
 
 
 
 
 
 
 
 
 
dda1cd6
 
21db5e9
 
 
 
 
 
463d47b
21db5e9
463d47b
21db5e9
463d47b
 
 
 
 
21db5e9
 
 
 
3a7f864
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21db5e9
 
 
 
 
 
 
 
 
6a808d5
21db5e9
 
 
 
3a7f864
 
 
 
 
21db5e9
3a7f864
21db5e9
 
 
 
 
 
 
 
 
dda1cd6
 
 
21db5e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a7f864
dda1cd6
 
21db5e9
6a808d5
21db5e9
27f5c8d
21db5e9
 
3a7f864
 
 
 
 
 
 
6a808d5
 
 
 
3a7f864
dda1cd6
 
3a7f864
3dd9d64
21db5e9
 
 
463d47b
 
21db5e9
463d47b
 
 
 
 
dda1cd6
 
463d47b
dda1cd6
 
21db5e9
 
27f5c8d
21db5e9
dda1cd6
 
21db5e9
dda1cd6
21db5e9
dda1cd6
 
21db5e9
dda1cd6
21db5e9
dda1cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a7f864
dda1cd6
3a7f864
 
 
dda1cd6
3a7f864
dda1cd6
 
 
 
 
 
 
3a7f864
 
dda1cd6
 
 
21db5e9
 
 
 
dda1cd6
 
 
21db5e9
dda1cd6
 
21db5e9
 
dda1cd6
27f5c8d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
import pandas as pd
from itertools import permutations, combinations
from fastapi import FastAPI, File, UploadFile, Form, HTTPException, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from typing import List, Dict, Any, Optional
import uuid
import requests
import json

from fastapi.responses import RedirectResponse
import pyodbc
import os
from dotenv import load_dotenv
from datetime import datetime

# Load environment variables from .env file
load_dotenv()

# Fetch credentials from environment variables
DB_DRIVER = os.getenv('DB_DRIVER')
DB_SERVER = os.getenv('DB_SERVER')
DB_DATABASE = os.getenv('DB_DATABASE')
DB_UID = os.getenv('DB_UID')
DB_PWD = os.getenv('DB_PWD')
DB_ENCRYPT = os.getenv('DB_ENCRYPT')
DB_NAME = os.getenv('DB_name')
DB_TABLE_NAME = os.getenv('DB_tableName')
frontend_url = os.getenv('FRONTEND_URL')
# Define connection string
conn_str = (
    f"Driver={DB_DRIVER};"
    f"Server={DB_SERVER};"
    f"Database={DB_NAME};"  # Use the target database
    f"UID={DB_UID};"
    f"PWD={DB_PWD};"
    f"Encrypt={DB_ENCRYPT};"
)

app = FastAPI()
stored_combinations = {}
destination_mapping_global = {}
processed_data_store: Dict[str, Dict[str, Any]] = {}  # Store processed data with session_id

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Adjust as needed for security
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.options("/{rest_of_path:path}")
async def preflight_handler(request: Request, rest_of_path: str) -> Response:
    return Response(headers={
        "Access-Control-Allow-Origin": "*",  # Adjust as needed for security
        "Access-Control-Allow-Methods": "POST, GET, OPTIONS, PUT, DELETE",
        "Access-Control-Allow-Headers": "*",
    })


# Box and Truck classes
class Box:
    def __init__(self, length, width, height, quantity, box_type, destination):
        self.length = length
        self.width = width
        self.height = height
        self.quantity = quantity if quantity > 0 else 1
        self.type = box_type
        self.destination = destination  # Added Destination

    def rotated_dimensions(self):
        possible_rotations = [
            (self.length, self.width, self.height),
            (self.length, self.height, self.width),
            (self.width, self.length, self.height),
            (self.width, self.height, self.length),
            (self.height, self.length, self.width),
            (self.height, self.width, self.length)
        ]
        return sorted(possible_rotations, key=lambda x: (x[0] * x[1], x[2]), reverse=True)

    def volume(self):
        return self.length * self.width * self.height


class Truck:
    def __init__(self, length, width, height):
        self.length = length
        self.width = width
        self.height = height
        self.volume = length * width * height
        self.placed_boxes = []
        self.available_space = [(0, 0, 0, length, width, height)]

    def is_space_supported(self, position, box):
        x, y, z = position
        bl, bw, bh = box

        if z == 0:
            return True

        for placed_box, placed_position in self.placed_boxes:
            px, py, pz = placed_position
            pl, pw, ph = placed_box

            if (x >= px and x + bl <= px + pl) and (y >= py and y + bw <= py + pw) and (z == pz + ph):
                return True

        return False

    def add_box_ffd(self, box):
        best_fit = None
        best_fit_space_index = -1
        best_fit_volume_waste = float('inf')

        for rotation in box.rotated_dimensions():
            for i, space in enumerate(self.available_space):
                x, y, z, l, w, h = space

                if rotation[0] <= l and rotation[1] <= w and rotation[2] <= h:
                    if not self.is_space_supported((x, y, z), rotation):
                        continue

                    leftover_volume = (l * w * h) - (rotation[0] * rotation[1] * rotation[2])

                    if leftover_volume < best_fit_volume_waste:
                        best_fit = rotation
                        best_fit_space_index = i
                        best_fit_volume_waste = leftover_volume

        if best_fit:
            x, y, z, l, w, h = self.available_space[best_fit_space_index]
            box_position = (x, y, z)

            self.placed_boxes.append((best_fit, box_position))

            self.available_space.pop(best_fit_space_index)
            self.update_space(best_fit, box_position, l, w, h)
            return box_position
        else:
            return None

    def update_space(self, box, position, l, w, h):
        x, y, z = position
        bl, bw, bh = box

        new_spaces = [
            (x + bl, y, z, l - bl, w, h),
            (x, y + bw, z, bl, w - bw, h),
            (x, y, z + bh, bl, bw, h - bh),
        ]

        new_spaces = [space for space in new_spaces if space[3] > 0 and space[4] > 0 and space[5] > 0]

        self.available_space.extend(new_spaces)
        self.available_space.sort(key=lambda space: (space[2], space[1], space[0]))


def pack_boxes_ffd(truck, consignments):
    packed_positions = []

    # Sort consignments: priority consignments first, then by total volume (descending)
    consignments = sorted(consignments, key=lambda c: (not c[1], -sum(box.volume() * box.quantity for box in c[0])))

    for consignment in consignments:
        consignment_boxes = consignment[0]
        for box in consignment_boxes:
            for _ in range(box.quantity):
                position = truck.add_box_ffd(box)
                if position is not None:
                    # Box is packed
                    packed_positions.append((box, position))
                else:
                    # Box cannot be packed, include with position as None
                    packed_positions.append((box, None))

    return packed_positions



def find_max_consignments_combinations(truck, consignments, combination_limit=100):
    combinations_that_fit = []
    consignments_sorted = sorted(consignments, key=lambda c: (not c[1], -sum(box.volume() * box.quantity for box in c[0])))

    combo_count = 0
    max_consignments_fitted = 0

    for r in range(1, len(consignments_sorted) + 1):
        for combo in combinations(consignments_sorted, r):
            combo_count += 1
            # Corrected line: Access the first box's type
            if len(combo) == 0 or any(len(consignment[0]) == 0 for consignment in combo):
                # Skip if any consignment has no boxes
                continue
            print(f"Checking combination {combo_count}: {[f'Consignment {boxes[0].type}' for boxes, _ in combo]}")

            if combo_count > combination_limit:
                print(f"Reached combination limit of {combination_limit}. Stopping further checks.")
                break

            temp_truck = Truck(truck.length, truck.width, truck.height)

            total_volume = sum(sum(box.volume() * box.quantity for box in consignment[0]) for consignment in combo)

            if total_volume > temp_truck.volume:
                continue

            try:
                packed_positions = pack_boxes_ffd(temp_truck, combo)
                if packed_positions:
                    print(f"Combination {combo_count} fits with {len(combo)} consignments")
                    combinations_that_fit.append(combo)
                    max_consignments_fitted = max(max_consignments_fitted, len(combo))

                    if len(combinations_that_fit) >= 5:
                        break
            except HTTPException:
                print(f"Combination {combo_count} does not fit")
                continue

        if combo_count > combination_limit:
            break

    return combinations_that_fit[-5:]


def suggest_truck(consignments):
    trucks = {
        "TATA ACE": {"length": 7, "width": 4.8, "height": 4.8},
        "ASHOK LEYLAND DOST": {"length": 7, "width": 4.8, "height": 4.8},
        "MAHINDRA BOLERO PICK UP": {"length": 8, "width": 5, "height": 4.8},
        "ASHOK LEYLAND BADA DOST": {"length": 9.5, "width": 5.5, "height": 5},
        "TATA 407": {"length": 9, "width": 5.5, "height": 5},
        "EICHER 14 FEET": {"length": 14, "width": 6, "height": 6.5},
        "EICHER 17 FEET": {"length": 17, "width": 6, "height": 7},
        "EICHER 19 FEET": {"length": 19, "width": 7, "height": 7},
        "TATA 22 FEET": {"length": 22, "width": 7.5, "height": 7},
        "TATA TRUCK (6 TYRE)": {"length": 17.5, "width": 7, "height": 7},
        "TAURUS 16 T (10 TYRE)": {"length": 21, "width": 7.2, "height": 7},
        "TAURUS 21 T (12 TYRE)": {"length": 24, "width": 7.3, "height": 7},
        "TAURUS 25 T (14 TYRE)": {"length": 28, "width": 7.8, "height": 7},
        "CONTAINER 20 FT": {"length": 20, "width": 8, "height": 8},
        "CONTAINER 32 FT SXL": {"length": 32, "width": 8, "height": 8},
        "CONTAINER 32 FT MXL": {"length": 32, "width": 8, "height": 8},
        "CONTAINER 32 FT SXL / MXL HQ": {"length": 32, "width": 8, "height": 10},
        "20 FEET OPEN ALL SIDE (ODC)": {"length": 20, "width": 8, "height": 8},
        "28-32 FEET OPEN-TRAILOR JCB ODC": {"length": 28, "width": 8, "height": 8},
        "32 FEET OPEN-TRAILOR ODC": {"length": 32, "width": 8, "height": 8},
        "40 FEET OPEN-TRAILOR ODC": {"length": 40, "width": 8, "height": 8},
        "SCV": {"length": 5, "width": 12, "height": 6},
        "LCV": {"length": 11, "width": 5, "height": 5},
        "ICV": {"length": 16, "width": 6.5, "height": 6.5},
        "MCV": {"length": 19, "width": 7, "height": 7}
    }

    sorted_trucks = sorted(trucks.items(), key=lambda t: t[1]['length'] * t[1]['width'] * t[1]['height'])

    for truck_name, dimensions in sorted_trucks:
        truck = Truck(dimensions['length'] * 12, dimensions['width'] * 12, dimensions['height'] * 12)
        packed_positions = pack_boxes_ffd(truck, consignments)

        total_boxes = sum(box.quantity for consignment in consignments for box in consignment[0])

        # Count successfully packed boxes
        packed_boxes_count = sum(1 for _, pos in packed_positions if pos is not None)

        if packed_boxes_count == total_boxes:
            return {"name": truck_name, "dimensions": dimensions}

    return None


# Updated Pydantic Models with Destination Fields
class BoxData(BaseModel):
    PieceLength: float
    PieceBreadth: float
    PieceHeight: float
    Priority: int
    Destination: str  # Added Destination


class ConsignmentData(BaseModel):
    ConsignmentNo: str
    Priority: int
    Destination: str  # Added Destination
    boxes: List[BoxData]


class SubmitDataRequest(BaseModel):
    truck_name: str
    autoSuggest: bool
    consignments_data: List[ConsignmentData]
    destination_mapping: Dict[str, int]  # Added destination_mapping


@app.post("/submit_data/")
async def submit_data(request: SubmitDataRequest):
    """
    Endpoint to receive data from the client via API.
    """
    
    frontend_url = os.getenv('FRONTEND_URL')
    truck_name = request.truck_name
    autoSuggest = request.autoSuggest
    consignments_data = request.consignments_data  # This is already parsed from JSON
    destination_mapping = request.destination_mapping  # Received destination_mapping

    global stored_combinations, processed_data_store, destination_mapping_global
    
    destination_mapping_global = destination_mapping

    # Parse consignments and calculate total quantity based on box dimensions
    consignments = []
    for consignment_data in consignments_data:
        consignment_no = consignment_data.ConsignmentNo  # ConsignmentNo is now accessible as a string
        is_priority = consignment_data.Priority
        consignment_destination = consignment_data.Destination  # Get Destination for Consignment

        # Aggregate the boxes with same dimensions and destination
        box_aggregation = {}
        for box_data in consignment_data.boxes:
            dimensions = (box_data.PieceLength, box_data.PieceBreadth, box_data.PieceHeight, box_data.Destination)

            if dimensions in box_aggregation:
                box_aggregation[dimensions]['Quantity'] += 1  # Increment the count if dimensions are the same
            else:
                box_aggregation[dimensions] = {
                    'PieceLength': box_data.PieceLength,
                    'PieceBreadth': box_data.PieceBreadth,
                    'PieceHeight': box_data.PieceHeight,
                    'Destination': box_data.Destination,  # Include Destination
                    'Quantity': 1  # Initialize count to 1
                }

        # Convert aggregated boxes back to the expected list format
        consignment_boxes = [
            Box(
                box['PieceLength'] / 2.54,  # Convert cm to inches
                box['PieceBreadth'] / 2.54,
                box['PieceHeight'] / 2.54,
                box['Quantity'],
                f"Consignment {consignment_no} ({'Priority' if is_priority else 'Non-Priority'})",
                box['Destination']  # Pass Destination to Box
            )
            for box in box_aggregation.values()
        ]
        consignments.append((consignment_boxes, is_priority))

    # Handle autoSuggest logic and other functionality here
    if autoSuggest:
        suggested_truck = suggest_truck(consignments)
        if suggested_truck:
            truck_name = suggested_truck["name"]
            length = suggested_truck['dimensions']['length']
            width = suggested_truck['dimensions']['width']
            height = suggested_truck['dimensions']['height']
        else:
            raise HTTPException(status_code=400, detail="No suitable truck found")
    else:
        # Assuming truck dimensions are known based on truck_name
        trucks = {
            "TATA ACE": {"length": 7, "width": 4.8, "height": 4.8},
            "ASHOK LEYLAND DOST": {"length": 7, "width": 4.8, "height": 4.8},
            "MAHINDRA BOLERO PICK UP": {"length": 8, "width": 5, "height": 4.8},
            "ASHOK LEYLAND BADA DOST": {"length": 9.5, "width": 5.5, "height": 5},
            "TATA 407": {"length": 9, "width": 5.5, "height": 5},
            "EICHER 14 FEET": {"length": 14, "width": 6, "height": 6.5},
            "EICHER 17 FEET": {"length": 17, "width": 6, "height": 7},
            "EICHER 19 FEET": {"length": 19, "width": 7, "height": 7},
            "TATA 22 FEET": {"length": 22, "width": 7.5, "height": 7},
            "TATA TRUCK (6 TYRE)": {"length": 17.5, "width": 7, "height": 7},
            "TAURUS 16 T (10 TYRE)": {"length": 21, "width": 7.2, "height": 7},
            "TAURUS 21 T (12 TYRE)": {"length": 24, "width": 7.3, "height": 7},
            "TAURUS 25 T (14 TYRE)": {"length": 28, "width": 7.8, "height": 7},
            "CONTAINER 20 FT": {"length": 20, "width": 8, "height": 8},
            "CONTAINER 32 FT SXL": {"length": 32, "width": 8, "height": 8},
            "CONTAINER 32 FT MXL": {"length": 32, "width": 8, "height": 8},
            "CONTAINER 32 FT SXL / MXL HQ": {"length": 32, "width": 8, "height": 10},
            "20 FEET OPEN ALL SIDE (ODC)": {"length": 20, "width": 8, "height": 8},
            "28-32 FEET OPEN-TRAILOR JCB ODC": {"length": 28, "width": 8, "height": 8},
            "32 FEET OPEN-TRAILOR ODC": {"length": 32, "width": 8, "height": 8},
            "40 FEET OPEN-TRAILOR ODC": {"length": 40, "width": 8, "height": 8},
            "SCV": {"length": 5, "width": 12, "height": 6},
            "LCV": {"length": 11, "width": 5, "height": 5},
            "ICV": {"length": 16, "width": 6.5, "height": 6.5},
            "MCV": {"length": 19, "width": 7, "height": 7}
        }

        if truck_name not in trucks:
            raise HTTPException(status_code=400, detail="Invalid truck name provided")

        truck_dimensions = trucks[truck_name]
        length = truck_dimensions['length']
        width = truck_dimensions['width']
        height = truck_dimensions['height']

    # Initialize the Truck object and pack boxes
    truck = Truck(length * 12, width * 12, height * 12)  # Convert feet to inches
    packed_positions = pack_boxes_ffd(truck, consignments)

    # Count how many boxes were successfully packed
    packed_boxes_count = sum(1 for _, pos in packed_positions if pos is not None)

    # Total number of boxes
    total_boxes = len(packed_positions)  # Since we expanded quantities during packing

    if packed_boxes_count < total_boxes:
        stored_combinations = find_max_consignments_combinations(truck, consignments)
        if stored_combinations:
            combinations_info = []
            for index, combo in enumerate(stored_combinations):
                total_quantity = sum(box.quantity for boxes, _ in combo for box in boxes)
                combination_info = {
                    "combination_number": index + 1,
                    "consignments": [
                        {
                            "consignment_number": f"{boxes[0].type.split(' ')[1]}",  # Corrected access
                            "priority_status": boxes[0].type.split('(')[1].strip(')'),
                            "destination": boxes[0].destination  # Include Destination
                        }
                        for boxes, _ in combo
                    ],
                    "total_quantity": total_quantity  # Add total quantity for this combination
                }
                combinations_info.append(combination_info)

            # Generate a unique session_id
            session_id = str(uuid.uuid4())
            processed_data_store[session_id] = {
                "error": "Not all consignments fit.",
                "combinations_that_fit": combinations_info,
                "truck": {
                    "name": truck_name,
                    "dimensions": {
                        "length": length,
                        "width": width,
                        "height": height
                    }
                },
                "consignments_data": [consignment.dict() for consignment in consignments_data],  # **Includes Destination**
                "destination_mapping": destination_mapping  # Include destination_mapping
            }

            # Redirect to the visualization page
            return RedirectResponse(url=f"https://66efefa222edb77e90ad7cf5--radiant-elf-edf447.netlify.app?session_id={session_id}", status_code=302)

    # Prepare box data for visualization
    box_data = []
    for box, pos in packed_positions:
        if pos is not None:
            position = {'x': pos[0], 'y': pos[1], 'z': pos[2]}
        else:
            position = None  # Box could not be packed
        box_data.append({
            'length': box.length,
            'width': box.width,
            'height': box.height,
            'type': box.type,
            'quantity': 1,  # Since we're iterating over each individual box
            'position': position,
            'destination': box.destination  # Include Destination
        })

    # Generate a unique session_id
    session_id = str(uuid.uuid4())
    processed_data_store[session_id] = {
        "boxes": box_data,
        "truck": {
            "name": truck_name,
            "dimensions": {
                "length": length,
                "width": width,
                "height": height
            }
        },
        "destination_mapping": destination_mapping  # Include destination_mapping
    }
    
    print(" auto suggest data ", processed_data_store[session_id])

    # Redirect to the visualization page
    return RedirectResponse(url=f"https://66efefa222edb77e90ad7cf5--radiant-elf-edf447.netlify.app?session_id={session_id}", status_code=302)

@app.get("/get_visualization/{session_id}/")
async def get_visualization(session_id: str):
    """
    Endpoint for the frontend to fetch processed data using session_id.
    """
    if session_id not in processed_data_store:
        raise HTTPException(status_code=404, detail="Session ID not found")

    return processed_data_store[session_id]

    
class SaveCombinationRequest(BaseModel):
    combination_number: int
    truck: str
    truck_length: float
    truck_width: float
    truck_height: float
    consignments: List[ConsignmentData]
    total_quantity: int
    utilization_percentage: Optional[float]

# Endpoint to save combination data
@app.post("/save_combination/", summary="Save a truck loading combination")
async def save_combination(data: SaveCombinationRequest):
    try:
        
        global destination_mapping_global
        # Establish a connection
        conn = pyodbc.connect(conn_str)
        cursor = conn.cursor()
        
        # Prepare data for insertion
        current_date = datetime.now().strftime("%d-%m-%Y") 
        truck_name = data.truck
        # Truck dimensions are now captured separately
        truck_length = data.truck_length
        truck_width = data.truck_width
        truck_height = data.truck_height
        total_consignments = len(data.consignments)
        total_boxes = sum(len(consignment.boxes) for consignment in data.consignments)

        # Prepare box data as payload for storage
        box_data = []
        for consignment in data.consignments:
            for box in consignment.boxes:
                box_entry = {
                    'length': box.PieceLength,
                    'width': box.PieceBreadth,
                    'height': box.PieceHeight,
                    'type': consignment.ConsignmentNo,
                    'quantity': 1,  # Assuming the quantity is handled individually in frontend
                    'position': "None",
                    'destination': box.Destination
                }
                box_data.append(box_entry)

        payload = {
            "boxes": box_data,
            "truck": {
                "name": truck_name,
                "dimensions": {
                    "length": truck_length,
                    "width": truck_width,
                    "height": truck_height
                }
            },
            "destination_mapping": destination_mapping_global,
            "total_boxes": total_boxes,
            "total_consignments": total_consignments
        }
        
        # print("payload ", payload)

        # Insert data into the table
        insert_query = f"""
        INSERT INTO {DB_TABLE_NAME} (Date, truckName, truckDimensions, totalConsignment, totalBoxes, payload)
        VALUES (?, ?, ?, ?, ?, ?)
        """
        cursor.execute(insert_query, (
            current_date,
            truck_name,
            f"{truck_length}L x {truck_width}W x {truck_height}H Feet",
            total_consignments,
            total_boxes,  # Total number of boxes calculated
            json.dumps(payload)  # Store the payload as a JSON string
        ))
        
        # Commit the transaction
        conn.commit()
        
        # Close the connection
        cursor.close()
        conn.close()
        
        return {"message": "Combination saved successfully.", "Date": current_date}
    except pyodbc.Error as e:
        error_message = str(e)
        raise HTTPException(status_code=500, detail=f"Database error: {error_message}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/visualize_payload/")
async def visualize_payload(payload: Dict[str, Any]):
    """
    API to receive a payload and return the processed data to the frontend via session ID.
    """
    global processed_data_store
    
    frontend_url = os.getenv('FRONTEND_URL')
    destination_mapping = payload.get('destination_mapping')
    
    
    # Extract truck details from payload
    truck = payload.get('truck')
    if not truck or 'dimensions' not in truck:
        raise HTTPException(status_code=400, detail="Truck information or dimensions missing.")
    
    truck_name = truck.get('name')
    truck_dimensions = truck.get('dimensions')
    if not truck_dimensions:
        raise HTTPException(status_code=400, detail="Truck dimensions missing.")
    
    # Extract boxes from payload
    boxes = payload.get('boxes', [])
    if not boxes:
        raise HTTPException(status_code=400, detail="No boxes found in payload.")
    
    # Extract and process truck dimensions
    length = truck_dimensions.get('length')
    width = truck_dimensions.get('width')
    height = truck_dimensions.get('height')
    if not length or not width or not height:
        raise HTTPException(status_code=400, detail="Incomplete truck dimensions.")
    
    # Initialize Truck object
    truck_obj = Truck(length * 12, width * 12, height * 12)  # Convert feet to inches
    
    # Process the boxes for FFD packing
    packed_positions = []
    consignments = []
    
    for box in boxes:
        # Convert box dimensions to inches (assuming they are given in feet or inches depending on your context)
        box_obj = Box(
            length=box['length'], 
            width=box['width'], 
            height=box['height'], 
            quantity=box.get('quantity', 1),
            box_type=box['type'],
            destination=box['destination']
        )
        # Use pack_boxes_ffd method to find positions for boxes in truck
        position = truck_obj.add_box_ffd(box_obj)
        packed_positions.append((box_obj, position))
    
    # Prepare the box data for visualization
    box_data = []
    for box_obj, pos in packed_positions:
        if pos is not None:
            position = {'x': pos[0], 'y': pos[1], 'z': pos[2]}
        else:
            position = None  # Box could not be packed
        box_data.append({
            'length': box_obj.length / 2.54,
            'width': box_obj.width / 2.54,
            'height': box_obj.height / 2.54,
            'type': box_obj.type,
            'quantity': box_obj.quantity,
            'position': position,
            'destination': box_obj.destination
        })

    # Generate a unique session_id for storing the processed data
    session_id = str(uuid.uuid4())
    processed_data_store[session_id] = {
        "boxes": box_data,
        "truck": {
            "name": truck_name,
            "dimensions": {
                "length": length,
                "width": width,
                "height": height
            }
        },
        "destination_mapping": destination_mapping
    }

    # Return session ID and processed data to the frontend for visualization
    return {"session_id": session_id, "visualization_url": f"https://66efefa222edb77e90ad7cf5--radiant-elf-edf447.netlify.app?session_id={session_id}"}