-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
395 lines (303 loc) · 14.8 KB
/
Copy pathmain.py
File metadata and controls
395 lines (303 loc) · 14.8 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
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
import json
class Inventory:
def __init__(self):
self.database_path = "database/products.json"
def get_raw_inventory(self) -> dict[str, dict[str, str]]:
"""
Function to get the inventory from the database.
The returned format will be:
```json
{
"Product name": {
"Description": "A brief description of the product.",
"Comapny": "The name of the company that manufactures the product.",
"Price": "0.0",
"Stock": "0",
"Category": "The category of the product; e.g. AC, Battery, TV etc."
}
}
```
"""
try:
with open(self.database_path, "r") as file:
inventory = file.read()
return json.loads(inventory)
except json.JSONDecodeError:
print("Error decoding JSON from the database. Please check the file format.")
return {}
except FileNotFoundError:
print("Database file not found. Please ensure the database path is correct.")
with open(self.database_path, "w") as file:
file.write(json.dumps({}, indent=4))
return {}
def get_all_products_names(self) -> list[str]:
"""
Function to get all product names from the inventory.
Returns a list of product names.
"""
inventory = self.get_raw_inventory()
return list(inventory.keys())
def get_price_of_product(self, product_name: str) -> float:
"""
Function to get the price of a product.
Returns the price of the product if it exists, otherwise returns None.
"""
inventory = self.get_raw_inventory()
if not product_name in inventory:
return "Product not found."
try:
price = float(inventory[product_name]["Price"])
except ValueError:
return "Invalid price value. Please check the product data."
return price
def get_stock_of_product(self, product_name: str) -> int | str:
"""
Function to get the stock of a product.
Returns the stock of the product if it exists, otherwise returns None.
"""
inventory = self.get_raw_inventory()
if not product_name in inventory:
return "Product not found."
try:
stock = int(inventory[product_name]["Stock"])
except ValueError:
return "Invalid stock value. Please check the product data."
if stock == 0 or stock < 0:
return "Product is out of stock."
return stock
def get_details_of_product(self, product_name: str) -> dict[str, str] | None:
"""
Function to get the details of a product.
Returns a dictionary with the product details if it exists, otherwise returns None.
"""
inventory = self.get_raw_inventory()
if not product_name in inventory:
return None
return inventory[product_name]
def update_raw_inventory(self, new_inventory: dict[str, dict[str, str]]) -> None:
"""
Function to update the inventory with a new inventory.
The new inventory should be in the same format as the one returned by get_raw_inventory.
"""
with open(self.database_path, "w") as file:
file.write(json.dumps(new_inventory, indent=4))
def add_product(self, product_name: str, description: str, company: str, price: float | str, stock: str, category: str, raw_stock_value: bool = False) -> None:
"""
The product will be added with the given name, description, company, price, and stock.
If the product already exists, it will increment the stock and notify the user about it.
"""
inventory = self.get_raw_inventory()
if product_name in inventory:
inventory[product_name]["Description"] = description
inventory[product_name]["Company"] = company
inventory[product_name]["Price"] = str(price)
if raw_stock_value:
inventory[product_name]["Stock"] = stock
else:
inventory[product_name]["Stock"] = int(inventory[product_name]["Stock"]) + int(stock)
inventory[product_name]["Category"] = category
print(f"Product '{product_name}' already exists. Stock has been updated.")
print(f"New stock for '{product_name}': {inventory[product_name]['Stock']}")
else:
inventory[product_name] = {
"Description": description,
"Company": company,
"Price": str(price),
"Stock": str(stock),
"Category": category
}
self.update_raw_inventory(inventory)
def sell_product(self, product_name: str, quantity: int) -> str:
"""
Function to sell a product.
If the product exists and has enough stock, it will decrement the stock and return a success message.
If the product does not exist or has insufficient stock, it will return an error message.
"""
inventory = self.get_raw_inventory()
if product_name not in inventory:
return "Product not found."
current_stock = int(inventory[product_name]["Stock"])
if current_stock < quantity:
return "Insufficient stock available."
inventory[product_name]["Stock"] = str(current_stock - quantity)
self.update_raw_inventory(inventory)
return f"Sold {quantity} of '{product_name}'. New stock: {inventory[product_name]['Stock']}"
def get_all_categories(self) -> list[str]:
"""
Function to get all categories from the inventory.
Returns a list of unique categories.
"""
inventory = self.get_raw_inventory()
categories = set()
for product in inventory.values():
categories.add(product["Category"])
return list(categories)
class UserInteractionViaTerminal:
def __init__(self):
self.inventory = Inventory()
self.options: dict[str, function] = {
"View all products": self.option_view_all_products,
"Add a product": self.option_add_product,
"Sell a product": self.option_sell_product,
"View Price of all the products": self.option_view_price_of_all_products,
"View details of a product": self.option_view_product_details,
"Increase stock of a product": self.option_increase_stock_of_product,
"Update details of a product": self.option_update_product_details
}
self.options_list = list(self.options.keys())
def printOptions(self) -> None:
"""
Function to print the available options for the user.
"""
print("Available options:")
for index, option in enumerate(self.options_list, start=1):
print(f"{index}. {option}")
print("Type 'q' to quit")
def run(self):
print("\nWelcome to the Inventory Management System")
print("This app is made by Om Goyal.")
while True:
input("Press enter to continue\n")
self.printOptions()
choice = input("Enter your choice: ")
if choice.lower() == 'q':
print("Thank you for using the Inventory Management System. Goodbye!\n")
break
try:
choice = int(choice)
except ValueError:
print("Invalid input. Please enter a number corresponding to the option or 'q' to quit.")
print("\n")
self.handleUserInput(choice)
def handleUserInput(self, choice: int) -> None:
choice = choice - 1 # Adjust for zero-based index
if choice < 0 or choice >= len(self.options_list):
print("Invalid choice. Please try again.")
return
option_name = self.options_list[choice]
action = self.options[option_name]
action() # Call the corresponding method for the selected option
def option_view_all_products(self) -> None:
products = self.inventory.get_all_products_names()
print("Available products:")
for product in products:
stock = self.inventory.get_stock_of_product(product)
print(f"- {product}: {stock} in stock")
def option_add_product(self) -> None:
name = input("Enter product name: ")
description = input("Enter product description: ")
company = input("Enter company name: ")
price = float(input("Enter product price: "))
stock = input("Enter stock quantity: ")
formatted_categories = ""
for category in self.inventory.get_all_categories():
formatted_categories += f"- {category}\n"
print(f"Available categories:\n{formatted_categories}")
print("Please enter the category of the product from the above list or a new category.")
category = input("Enter product category: ")
self.inventory.add_product(name, description, company, price, stock, category)
print(f"Product '{name}' added successfully.")
def option_sell_product(self) -> None:
self.printAllProducts()
name = input("Enter product index to sell: ")
all_products = self.inventory.get_all_products_names()
if not name.isdigit() or int(name) < 0 or int(name) >= len(all_products):
print("Invalid product index. Please try again.")
return
name = all_products[int(name)]
print(f"Selected product: {name} with stock {self.inventory.get_stock_of_product(name)}")
quantity = int(input("Enter quantity to sell: "))
result = self.inventory.sell_product(name, quantity)
print(result)
def option_view_price_of_all_products(self) -> None:
all_products = self.inventory.get_all_products_names()
print("Price of all products:")
for product in all_products:
price = self.inventory.get_price_of_product(product)
print(f"- {product}: {price}")
def option_view_product_details(self) -> None:
all_products = self.inventory.get_all_products_names()
print("Price of all products:")
for product in all_products:
price = self.inventory.get_price_of_product(product)
print(f"{product}: {price}")
def option_increase_stock_of_product(self) -> None:
self.printAllProducts()
product_index = input("Enter the index of the product to increase stock or type 'new' to add a new product: ")
if product_index.lower() == 'new':
self.handleUserInput("2")
return
product_index = int(product_index)
all_products = self.inventory.get_all_products_names()
if not 0 <= product_index < len(all_products):
print("Invalid index. Please try again.")
return
product_name = all_products[product_index]
current_stock = self.inventory.get_stock_of_product(product_name)
print(f"Selected product: {product_name} with current stock {current_stock}")
stock_increase = int(input(f"Enter the amount to increase stock for '{product_name}': "))
if stock_increase < 0:
print("Stock increase cannot be negative. Please try again.")
return
product_details = self.inventory.get_details_of_product(product_name)
self.inventory.add_product(product_name,
product_details["Description"],
product_details["Company"],
self.inventory.get_price_of_product(product_name),
stock_increase,
product_details["Category"])
def option_update_product_details(self) -> None:
self.printAllProducts()
product_index = int(input("Enter the index of the product to update details: "))
all_products = self.inventory.get_all_products_names()
if not 0 <= product_index < len(all_products):
print("Invalid index. Please try again.")
return
product_name = all_products[product_index]
print(f"Selected product: {product_name}")
product_name = input(f"Enter new product name (or press Enter to keep {product_name}): ") or product_name
product_details = self.inventory.get_details_of_product(product_name)
old_description = product_details["Description"]
old_company = product_details["Company"]
old_price = self.inventory.get_price_of_product(product_name)
old_stock = product_details["Stock"]
old_category = product_details["Category"]
description = input(f"Enter new product description (or press Enter to keep '{old_description}'): ") or old_description
company = input(f"Enter new company name (or press Enter to keep '{old_company}'): ") or old_company
price_input = input(f"Enter new product price (or press Enter to keep '{old_price}'): ") or old_price
try:
float(price_input)
except ValueError:
print("Invalid price value. Please enter a valid price.")
return
stock = input(f"Enter new stock quantity (or press Enter to keep '{old_stock}'): ") or old_stock
try:
int(stock) # Validate stock input
except ValueError:
print("Invalid stock value. Please enter a valid stock quantity.")
return
category = input(f"Enter new product category (or press Enter to keep '{old_category}'): ") or old_category
self.inventory.add_product(product_name, description, company, price_input, stock, category, raw_stock_value=True)
def viewProductDetails(self, product_name: str) -> None:
"""
Function to view the details of a specific product.
"""
product_details = self.inventory.get_details_of_product(product_name)
if not product_details:
print(f"Product '{product_name}' not found in the inventory.")
return
print(f"Details of '{product_name}':\n")
print(f"Description: {product_details['Description']}")
print(f"Company: {product_details['Company']}")
print(f"Price: {product_details['Price']}")
print(f"Stock: {product_details['Stock']}")
print(f"Category: {product_details['Category']}")
def printAllProducts(self) -> None:
all_products = self.inventory.get_all_products_names()
for index, product in enumerate(all_products):
print(f"{index}: {product}")
def main():
user_interaction = UserInteractionViaTerminal()
user_interaction.run()
if __name__ == "__main__":
main()