-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWarehouse-inventory-with-Dictionary.py
More file actions
322 lines (277 loc) · 14 KB
/
Warehouse-inventory-with-Dictionary.py
File metadata and controls
322 lines (277 loc) · 14 KB
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
"""
This program is an Inventory Management System for a warehouse.
It uses a Python dictionary to keep track of items.
You can add new items, sell, modify, search and check an item's details from the Inventory system.
"""
#importing pretty table for showing data in table format
from prettytable import PrettyTable
def print_lines():
dashed_line = "-" * 110
#printing the header with print_lines
print("\n")
print(dashed_line)
def add_item_to_inventory(inventory_stock):
"""
Function 2 : add_item_to_inventory
Purpose: To add a brand new item to the warehouse inventory, or update an item from existing stock. If the iteam_name
"""
print("\n\t\t\t Add inventory item.....")
#promting for user's input to add the item
item_name = input("Enter item name: ").strip()
item_id = input("Enter item ID: ").strip()
item_location = input("Enter location of item in shelf: ").strip()
# Checking the validity for quantity.
while True:
try:
quantity = int(input("Enter quantity of item: "))
if quantity <= 0:
print("Quantity must be a whole number (more than 0). Please try again.")
else:
break # If valid, exit the loop.
except ValueError: # If the input wasn't a number.
print("That's not a valid number for quantity. Please enter a whole number.")
# Loop to make sure the user enters a valid number for price.
while True:
try:
price = float(input("Enter price per unit of item: ")) # Try to convert input to a decimal number.
if price <= 0: # Price must be positive.
print("Price must be a positive number (more than $0). Please try again.")
else:
break # If valid, exit the loop.
except ValueError: # If the input wasn't a number.
print("That's not a valid number for price. Please enter a number.")
# Condition 1: Check if the inventory is empty
if not inventory_stock:
# If it's empty, add the item directly.
inventory_stock[item_id] = {
'name': item_name,
'item_ID': item_id,
'item_location': item_location,
'quantity': quantity,
'price': price
}
print("No items in inventory...Adding new item to inventory...")
else:
# Condition 2 & 3: Inventory has items, so check if this item already exists.
# Check if the 'item_id' already exists in inventory dictionary.
if item_id in inventory_stock:
# If the item ID exists, check if the item name also matches exactly.
# We convert both names to lowercase for a case-insensitive comparison (e.g., "apple" is same as "Apple").
if inventory_stock[item_id]['name'].lower() == item_name.lower():
# Condition 3: Item (ID and Name) already exists. update it.
print(f"Item '{item_name}' (ID: {item_id}) is already in stock.")
print("Increasing item quantity, updating location, and price.")
inventory_stock[item_id]['quantity'] += quantity # Add the new quantity to the existing.
inventory_stock[item_id]['item_location'] = item_location # Update the location.
inventory_stock[item_id]['price'] = price # Update the price.
else:
# Condition 2: Item ID exists, but the name is different. This means it's a new item.
# Example: ID "P123" exists for "Printers", but user tries to add "Paper" with ID "P123".
# We treat this as a new item because the name doesn't match the existing ID.
print(f"Item ID '{item_id}' is being used for a different item.")
print("This is a new item with a new Item ID, so we're adding it to stock.")
inventory_stock[item_id] = {
'name': item_name,
'item_ID': item_id,
'item_location': item_location,
'quantity': quantity,
'price': price
}
else:
# Condition 2: Item ID does not exist at all. This is definitely a new item.
print(f"Item ID '{item_id}' is for a new item and is currently NOT in stock; So, include this item in stock...")
inventory_stock[item_id] = {
'name': item_name,
'item_ID': item_id,
'item_location': item_location,
'quantity': quantity,
'price': price
}
return inventory_stock # Send back the updated inventory.
def perform_inventory_sales(inventory_stock):
"""
Function 3 : perform_inventory_sales
Purpose: To handle selling items from our inventory. When an item is sold, its quantity in stock goes down.
"""
print("\n--- Inventory Sales Application ---")
# Condition 1: Check if there are any items in the inventory first.
if not inventory_stock:
print("Sorry, there are no items in the stock right now to sell.")
return inventory_stock # Return without changes if inventory is empty.
# Ask the user for the name of the item they want to buy.
item_name_to_purchase = input("Enter the name of the item you want to buy: ").strip()
found_item_id = None # A variable to store the ID if we find the item.
for item_id, item_details in inventory_stock.items():
if item_details['name'].lower() == item_name_to_purchase.lower():
found_item_id = item_id
break
# Condition 4: If the item was not found after checking all items.
if found_item_id is None:
print(f"Sorry, the item '{item_name_to_purchase}' is NOT in stock at all.")
return inventory_stock
# If found the item, proceed with checking quantity.
print(f"Good news! Item '{item_name_to_purchase}' is in stock.")
item_details = inventory_stock[found_item_id] # Get all details for the found item.
# Loop to ensure a valid quantity to purchase is entered.
while True:
try:
quantity_to_purchase = int(input(f"Enter quantity of '{item_name_to_purchase}' to purchase: "))
if quantity_to_purchase <= 0:
print("Quantity to purchase must be a positive number. Please try again.")
else:
break
except ValueError:
print("Invalid input for quantity. Please enter a whole number.")
# Condition 2 & 3: Check if we have enough items in stock.
if item_details['quantity'] >= quantity_to_purchase:
# Condition 2: Purchase is successful!
print("We have enough stock. Preparing your invoice...")
item_details['quantity'] -= quantity_to_purchase
print_lines()
print("\n--- Your Sales Invoice ---")
#show the inventory details
invoice_table = PrettyTable()
invoice_table.field_names = ["Item Name", "Item ID", "Quantity Purchased", "Unit Price", "Subtotal"]
total_item_price = quantity_to_purchase * item_details['price'] # Calculate price before tax.
tax_rate = 0.13 # Example: 13% tax rate.
tax_amount = total_item_price * tax_rate # Calculate the tax amount.
total_amount_to_pay = total_item_price + tax_amount # Calculate the final total.
# Add the row of data to the table.
invoice_table.add_row([
item_details['name'],
item_details['item_ID'],
quantity_to_purchase,
f"${item_details['price']:.2f}", # Format price to 2 decimal places.
f"${total_item_price:.2f}" # Format subtotal to 2 decimal places.
])
print(invoice_table) # Print the formatted table.
# Print tax and final total.
print(f"{'Tax Amount:':<50} ${tax_amount:.2f}") # Format for nice alignment.
print(f"{'Total Amount to Pay:':<50} ${total_amount_to_pay:.2f}") # Format for nice alignment.
print(f"\nThank you for buying {quantity_to_purchase} '{item_details['name']}'.")
else:
# Condition 3: Not enough items in stock.
print(f'\nSorry! We do not have enough {item_name_to_purchase} in stock right now. Please try to buy later....')
print(f"You asked for {quantity_to_purchase}, but we only have {item_details['quantity']} left.")
return inventory_stock # Send back the updated inventory.
def display_all_inventory(inventory_stock):
"""
Function 4 : display_all_inventory
Purpose: To show a list of all items currently stored in our warehouse inventory.
It presents the information in a neat table.
"""
print("\n--- Displaying All Inventory Items ---")
# Condition 1: Check if the inventory is empty.
if not inventory_stock:
print("There are no items in the inventory to display yet.")
else:
# Condition 2: Inventory has items, so display them.
print_lines() # Display developer info at the top of the list.
print("\n--- List of All Inventory Items ---")
# Create a new PrettyTable instance.
inventory_table = PrettyTable()
# Set the column names (headers).
inventory_table.field_names = ["Item Name", "Item ID", "Location in Pods", "Price/Unit", "Quantity in Stock"]
# Loop through each item in the inventory_stock dictionary.
for item_id, item_details in inventory_stock.items():
# Add each item's details as a row to our table.
inventory_table.add_row([
item_details['name'],
item_details['item_ID'],
item_details['item_location'],
f"${item_details['price']:.2f}", # Format price to 2 decimal places.
item_details['quantity']
])
print(inventory_table) # Print the formatted table.
def check_inventory_status(inventory_stock):
"""
Function 5 : check_inventory_status
Purpose: To check if a specific item exists in our inventory and show its details
if it does.
"""
print("\n--- Check Item Status in Inventory ---")
# Condition 1: Check if the inventory is empty.
if not inventory_stock:
print("There are no items in the stock right now to check.")
return [False, None] # Return False because no item was found.
# Ask the user for the name of the item they want to check.
item_name_to_check = input("Enter the name of the item you want to check: ").strip()
found_item = None # A variable to hold the item's details if found.
# Loop through each item in the inventory to find a match by name (case-insensitive).
for item_id, item_details in inventory_stock.items():
if item_details['name'].lower() == item_name_to_check.lower():
found_item = item_details # We found the item! Store its details.
break # Stop searching.
# Condition 2: If the item was found.
if found_item:
print("\nItem found! Here are the details from our inventory:")
print_lines() # Display developer info.
# Create a new PrettyTable instance.
status_table = PrettyTable()
# Set the column names (headers).
status_table.field_names = ["Item Name", "Item ID", "Location in Pods", "Price/Unit", "Quantity in Stock"]
# Add the row of data for the found item.
status_table.add_row([
found_item['name'],
found_item['item_ID'],
found_item['item_location'],
f"${found_item['price']:.2f}", # Format price.
found_item['quantity']
])
print(status_table) # Print the formatted table.
# Also print the raw dictionary data for the item, as specified in the lab.
print("\nRaw item data:")
print(found_item)
return [True, found_item] # Return True and the item's details.
else:
# Condition 3: If the item was not found.
print(f"Sorry, the item '{item_name_to_check}' is NOT in stock.")
return [False, None] # Return False because no item was found.
def main_menu():
"""
Function 6 : print main_menu
Purpose: To simply show the user the main options they can choose from in the program.
This helps keep the main part of the program tidy.
"""
menu = """
Please choose an option:
a) Enter 'a' to Add to new inventory
b) Enter 'b' to Perform inventory sales
c) Enter 'c' to Display all inventory
d) Enter 'd' to Check inventory item in stock
e) Enter 'e' to End application.
"""
print(menu) # Print main_menu
def main():
"""
Function 7: main function
Purpose: This is the starting point of our entire Inventory Management System.
It sets up the main inventory, shows the menu repeatedly, and calls
the correct function based on what the user chooses.
"""
# Start with an empty dictionary.
inventory_stock = {}
# This loop keeps the program running until the user chooses to exit.
while True:
main_menu()
# Get the user's choice, convert it to lowercase, and remove spaces.
choice = input("Enter your choice here: ").lower().strip()
# Check which option the user picked and call the right function.
if choice == 'a':
inventory_stock = add_item_to_inventory(inventory_stock) # Call add function.
elif choice == 'b':
inventory_stock = perform_inventory_sales(inventory_stock) # Call sales function.
elif choice == 'c':
display_all_inventory(inventory_stock) # Call display function.
elif choice == 'd':
check_inventory_status(inventory_stock) # Call check status function.
elif choice == 'e':
print("Application ends now......")
break # Exit the 'while True' loop, which stops the program.
else:
# If the user enters something invalid.
print("Enter a valid choice 'a', 'b', 'c', 'd', or 'e'....")
# This special line makes sure that the 'main()' function is called only when
# the script is run directly (not when imported as a module into another script).
if __name__ == "__main__":
main()