File size: 6,316 Bytes
4f40895
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import gradio as gr
import io
import sys

# Inventory data
Inventory  = [
    (1, "Apples", 250),
    (2, "Cherry", 650),
    (3, "Chickoo", 50),
    (4, "Grapes", 90),
    (5, "Mangoes", 150),
]

# Existing functions (ensure these are defined or imported in your final app.py)
# get_inventory_string
# get_cart_string
# add_item_to_cart
# remove_item_from_cart

def get_inventory_string(inventory_list):
    output_buffer = io.StringIO()
    print_func = lambda *args, **kwargs: print(*args, file=output_buffer, **kwargs)

    print_func("
" + "=" * 50)
    print_func(" " * 15 + "PRODUCT INVENTORY (PRICES)")
    print_func("=" * 50)
    print_func(f"{'ID':<5}{'Product Name':<20}{'Price/Kg':>15}")
    print_func("-" * 50)
    for item_id, product_name, price_per_kg in inventory_list:
        print_func(f"{item_id:<5}{product_name:<20}{price_per_kg:>15.2f}")
    print_func("=" * 50)
    return output_buffer.getvalue()

def get_cart_string(cart_dict):
    output_buffer = io.StringIO()
    print_func = lambda *args, **kwargs: print(*args, file=output_buffer, **kwargs)

    print_func("
" + "=" * 50)
    print_func(" " * 18 + "SHOPPING CART")
    print_func("=" * 50)
    print_func(f"{'Product Name':<15}{'Quantity(Kg)':>12}{'Price/Kg':>12}{'Subtotal':>11}")
    print_func("-" * 50)
    total_bill = 0
    if not cart_dict:
        print_func(" " * 18 + "Cart is empty!")
    else:
        for product_name, details in cart_dict.items():
            qty = details['quantity']
            price_per_kg = details['price_per_kg']
            item_total = qty * price_per_kg
            total_bill += item_total
            print_func(f"{product_name:<15}{qty:>12.2f}{price_per_kg:>12.2f}{item_total:>11.2f}")
    print_func("=" * 50)
    print_func(f"{'Total Bill:':<38}{total_bill:>11.2f}")
    print_func("=" * 50)
    return output_buffer.getvalue()

def add_item_to_cart(cart, item_id_to_add, quantity_to_add, inventory_list):
    found_in_inventory = False
    for item_id, product_name, price_per_kg in inventory_list:
        if item_id == item_id_to_add:
            found_in_inventory = True
            if product_name in cart:
                cart[product_name]['quantity'] += quantity_to_add
            else:
                cart[product_name] = {'quantity': quantity_to_add, 'price_per_kg': price_per_kg}
            return True, f"Added {quantity_to_add} Kg of {product_name} (ID: {item_id_to_add}) to cart. Price/Kg: ${price_per_kg:.2f}"

    if not found_in_inventory:
        return False, f"Error: Product with ID '{item_id_to_add}' not found in inventory."

def remove_item_from_cart(cart, item_id_to_remove, quantity_to_remove, inventory_list):
    product_name_to_remove = None
    for item_id, product_name, _ in inventory_list:
        if item_id == item_id_to_remove:
            product_name_to_remove = product_name
            break

    if not product_name_to_remove:
        return False, f"Error: Product with ID '{item_id_to_remove}' not found in inventory."

    if product_name_to_remove not in cart:
        return False, f"Error: '{product_name_to_remove}' (ID: {item_id_to_remove}) is not in the cart."

    current_quantity = cart[product_name_to_remove]['quantity']

    if quantity_to_remove >= current_quantity:
        del cart[product_name_to_remove]
        return True, f"Removed all {current_quantity} Kg of '{product_name_to_remove}' (ID: {item_id_to_remove}) from cart."
    else:
        cart[product_name_to_remove]['quantity'] -= quantity_to_remove
        return True, f"Removed {quantity_to_remove} Kg of '{product_name_to_remove}' (ID: {item_id_to_remove}) from cart. Remaining: {cart[product_name_to_remove]['quantity']} Kg."


def gradio_add_item(cart, item_id_to_add, quantity_to_add):
    success, message = add_item_to_cart(cart, item_id_to_add, quantity_to_add, Inventory)
    return cart, message, get_cart_string(cart)

def gradio_remove_item(cart, item_id_to_remove, quantity_to_remove):
    success, message = remove_item_from_cart(cart, item_id_to_remove, quantity_to_remove, Inventory)
    return cart, message, get_cart_string(cart)

def gradio_display_cart_wrapper(cart):
    return get_cart_string(cart)

with gr.Blocks() as demo:
    gr.Markdown("# Shopping Cart Management System")

    cart_state = gr.State(value={})

    with gr.Tab("Add/Remove Items"):
        gr.Markdown("## Inventory")
        gr.Textbox(value=get_inventory_string(Inventory), label="Available Products", interactive=False, lines=10)

        with gr.Row():
            with gr.Column():
                gr.Markdown("### Add Item to Cart")
                add_id = gr.Number(label="Product ID to Add", value=1)
                add_qty = gr.Number(label="Quantity (Kg)", value=1.0)
                add_btn = gr.Button("Add to Cart")
                add_output = gr.Textbox(label="Status", interactive=False)

            with gr.Column():
                gr.Markdown("### Remove Item from Cart")
                remove_id = gr.Number(label="Product ID to Remove", value=1)
                remove_qty = gr.Number(label="Quantity (Kg)", value=1.0)
                remove_btn = gr.Button("Remove from Cart")
                remove_output = gr.Textbox(label="Status", interactive=False)

        current_cart_display = gr.Textbox(label="Current Shopping Cart", interactive=False, lines=None)

        add_btn.click(
            gradio_add_item,
            inputs=[cart_state, add_id, add_qty],
            outputs=[cart_state, add_output, current_cart_display]
        )
        remove_btn.click(
            gradio_remove_item,
            inputs=[cart_state, remove_id, remove_qty],
            outputs=[cart_state, remove_output, current_cart_display]
        )
        
        demo.load(gradio_display_cart_wrapper, inputs=cart_state, outputs=current_cart_display)

    with gr.Tab("View Cart"):
        gr.Markdown("## Your Shopping Cart")
        view_cart_display = gr.Textbox(label="Shopping Cart Contents", interactive=False, lines=None)
        
        cart_state.change(
            gradio_display_cart_wrapper,
            inputs=cart_state,
            outputs=view_cart_display
        )
        # Initial load for the View Cart tab
        demo.load(gradio_display_cart_wrapper, inputs=cart_state, outputs=view_cart_display)

demo.launch(share=True)