File size: 5,021 Bytes
0239bce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import gradio as gr
import pandas as pd

# ---------- Inventory ----------
# ID -> (Name, Price per KG)
INVENTORY = {
    1: ("Apples", 250),
    2: ("Cherry", 650),
    3: ("Chickoo", 50),
    4: ("Grapes", 90),
    5: ("Mangoes", 150),
}

def inventory_markdown():
    items = "\n".join([f"({pid}) **{name}**, {price}"
                        for pid, (name, price) in INVENTORY.items()])
    return f"### Inventory\n{items}"

# ---------- Cart helpers ----------
def summarize_cart(cart):
    """Return (DataFrame, total_cost) for the cart.
    Cart structure: list of dicts with keys: id, name, unit_price, qty
    """
    if not cart:
        return pd.DataFrame(columns=["Index","Name","Quantity","Price Per KG"]), 0
    rows = []
    total = 0
    for idx, item in enumerate(cart):
        rows.append({
            "Index": idx,
            "Name": item["name"],
            "Quantity": item["qty"],
            "Price Per KG": f"${item['unit_price']:.2f}",
        })
        total += item["qty"] * item["unit_price"]
    df = pd.DataFrame(rows)
    return df, total

def add_item_to_cart(pid, cart):
    add_msg = ""
    if pid is None:
        return *summarize_cart(cart), add_msg, ""
    if pid not in INVENTORY:
        add_msg = f":warning: Invalid ID {pid}. Please use one of: {list(INVENTORY.keys())}"
        return *summarize_cart(cart), add_msg, ""
    name, price = INVENTORY[pid]
    # Check if already in cart -> increment quantity
    for item in cart:
        if item["id"] == pid:
            item["qty"] += 1
            df, total = summarize_cart(cart)
            add_msg = f">>>>>>>>>> The item '{name}' has been added to the cart. <<<<<<<<<<"
            return df, total, add_msg, ""
    # Otherwise append new
    cart.append({"id": pid, "name": name, "unit_price": float(price), "qty": 1})
    df, total = summarize_cart(cart)
    add_msg = f">>>>>>>>>> The item '{name}' has been added to the cart. <<<<<<<<<<"
    return df, total, add_msg, ""

def remove_item_from_cart(index, cart):
    rm_msg = ""
    if index is None:
        return *summarize_cart(cart), "", rm_msg
    if not cart:
        rm_msg = ":warning: Cart is empty."
        return *summarize_cart(cart), "", rm_msg
    if index < 0 or index >= len(cart):
        rm_msg = f":warning: Invalid index {index}. Must be 0..{max(0,len(cart)-1)}"
        return *summarize_cart(cart), "", rm_msg
    removed = cart.pop(index)
    df, total = summarize_cart(cart)
    rm_msg = f"Removed '{removed['name']}' from the cart."
    return df, total, "", rm_msg

with gr.Blocks(title="Fruit Shopping Cart System") as demo:
    gr.Markdown("## Fruit Shopping Cart System")

    # App state: the cart
    cart_state = gr.State([])

    with gr.Row():
        with gr.Column(scale=2):
            pid_in = gr.Number(label="Enter Product ID to Add to Cart", value=2, precision=0)
        with gr.Column(scale=2):
            rm_index_in = gr.Number(label="Enter Index ID to Remove from Cart", value=0, precision=0)
        with gr.Column(scale=1):
            add_btn = gr.Button("Add to Cart", variant="primary")
        with gr.Column(scale=1):
            rm_btn = gr.Button("Remove from Cart", variant="secondary")

    with gr.Row():
        with gr.Column(scale=3):
            gr.Markdown("### Your Cart\n_Use 0-based index for removal_ :shopping_trolley:")
            cart_df = gr.Dataframe(headers=["Index","Name","Quantity","Price Per KG"],
                                   interactive=False,
                                   wrap=True,
                                   height=220)
            add_msg_out = gr.Textbox(label="Add Item Message", interactive=False)
            rm_msg_out = gr.Textbox(label="Remove Item Message", interactive=False)
            total_cost_out = gr.Textbox(label="Total Cost", interactive=False)
        with gr.Column(scale=2):
            inv_md = gr.Markdown(inventory_markdown())
            gr.Markdown("""
### Business Requirements
1. **Add Products to the Shopping Cart**: Add by ID from the inventory; quantities aggregate automatically.  
2. **Remove Unwanted Items**: Remove by 0-based index shown in the cart table.  
3. **Calculate the Total Bill**: Total updates automatically after each action.
""")

    def handle_add(pid, cart):
        df, total, add_msg, rm_msg = add_item_to_cart(int(pid), cart)
        total_str = f"$ {total:,.2f}"
        return df, add_msg, rm_msg, total_str, cart

    def handle_remove(index, cart):
        df, total, add_msg, rm_msg = remove_item_from_cart(int(index), cart)
        total_str = f"$ {total:,.2f}"
        return df, add_msg, rm_msg, total_str, cart

    add_btn.click(
        handle_add,
        inputs=[pid_in, cart_state],
        outputs=[cart_df, add_msg_out, rm_msg_out, total_cost_out, cart_state]
    )

    rm_btn.click(
        handle_remove,
        inputs=[rm_index_in, cart_state],
        outputs=[cart_df, add_msg_out, rm_msg_out, total_cost_out, cart_state]
    )

if __name__ == "__main__":
    demo.launch()