-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaster.py
435 lines (375 loc) · 15.4 KB
/
master.py
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
import os
import csv
from datetime import datetime
# File paths
ITEMS_FILE = "items.csv"
TRANSACTIONS_FILE = "transactions.csv"
# Initialize CSV files
def initialize_files():
try:
with open(ITEMS_FILE, mode="x", newline="") as file:
writer = csv.writer(file)
writer.writerow(["ID", "Name", "Price"])
except FileExistsError:
pass
try:
with open(TRANSACTIONS_FILE, mode="x", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Bill No", "Date", "Time", "Transaction Type", "Total Amount", "Details"])
except FileExistsError:
pass
# Clear screen
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
# Read CSV file
def read_csv(file_path):
try:
with open(file_path, mode="r") as file:
reader = csv.reader(file)
return list(reader)
except FileNotFoundError:
print(f"Error: {file_path} not found. Please initialize the system.")
return []
# Write CSV file
def write_csv(file_path, rows, mode="w"):
try:
with open(file_path, mode=mode, newline="") as file:
writer = csv.writer(file)
writer.writerows(rows)
except Exception as e:
print(f"Error writing to {file_path}: {e}")
# Main Menu
def main_menu():
while True:
clear_screen()
print("Main Menu")
print("1. Admin Dashboard")
print("2. Bill Generator")
print("3. History")
print("4. Exit")
choice = input("Select an option: ").strip()
if choice == "1":
admin_dashboard()
elif choice == "2":
bill_generator()
elif choice == "3":
view_history()
elif choice == "4":
print("Exiting the system...")
break
else:
print("Invalid option. Please try again.")
# Admin Dashboard
def admin_dashboard():
clear_screen()
username = input("Username: ")
password = input("Password: ")
if username == "admin" and password == "admin":
print("Login Successful!")
input("Press Enter to continue to the Admin Panel...")
admin_panel()
else:
print("Incorrect username or password. Try again.")
input("Press Enter to return to the main menu...")
# Admin Panel
def admin_panel():
global cgst_rate, sgst_rate
while True:
clear_screen()
print("Admin Dashboard")
print(f"CGST Rate: {cgst_rate}% | SGST Rate: {sgst_rate}%")
print("1. Show Existing Items")
print("2. Add New Item")
print("3. Modify Existing Item")
print("4. Delete Existing Item")
print("5. Update CGST Rate")
print("6. Update SGST Rate")
print("7. Go Back to Main Menu")
choice = input("Select an option: ").strip()
if choice == "1":
show_existing_items()
elif choice == "2":
add_new_item()
elif choice == "3":
modify_existing_item()
elif choice == "4":
delete_existing_item()
elif choice == "5":
update_cgst_rate()
elif choice == "6":
update_sgst_rate()
elif choice == "7":
break
else:
print("Invalid option. Please try again.")
# Show Existing Items
def show_existing_items():
clear_screen()
items = read_csv(ITEMS_FILE)
if len(items) <= 1:
print("No items found.")
else:
print("Existing Items:")
for item in items[1:]: # Skip the header row
print(f"ID: {item[0]}, Name: {item[1]}, Price: {item[2]}")
input("Press Enter to return to the admin dashboard...")
# Modify Existing Item
def modify_existing_item():
clear_screen()
items = read_csv(ITEMS_FILE)
if len(items) <= 1:
print("No items found.")
input("Press Enter to return to the admin dashboard...")
return
print("Existing Items:")
for item in items[1:]: # Skip the header row
print(f"ID: {item[0]}, Name: {item[1]}, Price: {item[2]}")
item_id = input("Enter the ID of the item you want to modify: ").strip()
# Find item to modify
for i, item in enumerate(items[1:], start=1): # Skip header row
if item[0] == item_id:
print(f"Selected Item: ID: {item[0]}, Name: {item[1]}, Price: {item[2]}")
new_name = input(f"Enter new name (leave blank to keep '{item[1]}'): ").strip()
new_price = input(f"Enter new price (leave blank to keep '{item[2]}'): ").strip()
# Update name and price only if values are provided
if new_name:
items[i][1] = new_name
if new_price:
try:
items[i][2] = f"{float(new_price):.2f}"
except ValueError:
print("Invalid price. No changes made to the price.")
write_csv(ITEMS_FILE, items)
print("Item modified successfully!")
input("Press Enter to return to the admin dashboard...")
return
print("Invalid item ID. No changes made.")
input("Press Enter to return to the admin dashboard...")
# Delete Existing Item
def delete_existing_item():
clear_screen()
items = read_csv(ITEMS_FILE)
if len(items) <= 1:
print("No items found.")
input("Press Enter to return to the admin dashboard...")
return
print("Existing Items:")
for item in items[1:]: # Skip header row
print("ID: {}, Name: {}, Price: {}".format(item[0], item[1], item[2]))
item_id = input("Enter the ID of the item you want to delete: ").strip()
# Check if item ID exists
for i, item in enumerate(items[1:], start=1): # Skip header row
if item[0] == item_id:
print("Selected Item: ID: {}, Name: {}, Price: {}".format(item[0], item[1], item[2]))
confirm = input("Are you sure you want to delete this item? (yes/no): ").strip().lower()
if confirm == "yes":
del items[i] # Remove the selected item
write_csv(ITEMS_FILE, items)
print("Item deleted successfully.")
else:
print("Deletion canceled.")
input("Press Enter to return to the admin dashboard...")
return
print("Item ID not found. No items were deleted.")
input("Press Enter to return to the admin dashboard...")
# Add New Item
def add_new_item():
clear_screen()
items = read_csv(ITEMS_FILE)
new_id = len(items)
name = input("Enter item name: ").strip()
price = input("Enter item price: ").strip()
items.append([new_id, name, price])
write_csv(ITEMS_FILE, items)
print(f"Item '{name}' added successfully.")
input("Press Enter to return to the admin dashboard...")
#Bill Generator function
def bill_generator():
clear_screen()
# Read items from the items file
items = read_csv(ITEMS_FILE)
if len(items) <= 1:
print("No items available for billing.")
input("Press Enter to return to the main menu...")
return
# Display available items
print("Available Items:")
for item in items[1:]: # Skip header row
print(f"ID: {item[0]}, Name: {item[1]}, Price: {item[2]}")
# Cart and item selection
cart = []
while True:
item_id = input("Enter item ID to add to the bill (or 'done' to finish): ").strip()
if item_id.lower() == 'done':
break
quantity = input("Enter quantity: ").strip()
for item in items[1:]:
if item[0] == item_id:
cart.append((item[1], float(item[2]), int(quantity)))
print(f"Added {quantity} x {item[1]} to the cart.")
break
else:
print("Invalid item ID. Please try again.")
if not cart:
print("No items added to the bill.")
input("Press Enter to return to the main menu...")
return
# Get customer details
customer_name = input("Enter customer's name: ").strip()
customer_phone = input("Enter customer's phone number: ").strip()
# Get discount (if any)
discount_input = input("Enter discount (in % or 'n' for no discount): ").strip()
discount = 0
if discount_input.lower() != 'n':
try:
discount = float(discount_input)
except ValueError:
print("Invalid discount value. No discount will be applied.")
# Generate bill summary
subtotal = sum(price * qty for _, price, qty in cart)
cgst = subtotal * cgst_rate / 100
sgst = subtotal * sgst_rate / 100
discount_amount = subtotal * discount / 100
grand_total = subtotal + cgst + sgst - discount_amount
# Clear screen and print bill summary
clear_screen()
bill_no = len(read_csv(TRANSACTIONS_FILE)) # Generate Bill No.
print("--- Bill Summary ---")
print(f"Bill No. {bill_no}")
print(f"Time: {datetime.now().strftime('%H:%M:%S')}")
print(f"Date: {datetime.now().strftime('%d-%m-%Y')}")
print(f"Customer Name: {customer_name}")
print(f"Phone Number: {customer_phone}")
for name, price, qty in cart:
print(f"{qty} x {name} @ {price:.2f} = {price * qty:.2f}")
print(f"Subtotal: {subtotal:.2f}")
print(f"CGST ({cgst_rate}%): {cgst:.2f}")
print(f"SGST ({sgst_rate}%): {sgst:.2f}")
if discount > 0:
print(f"Discount: {discount}% = {discount_amount:.2f}")
else:
print("Discount: No discount available")
print(f"Grand Total: {grand_total:.2f}")
# Save the transaction to the file
transactions = read_csv(TRANSACTIONS_FILE)
transaction_details = [{"Item": name, "Price": price, "Quantity": qty} for name, price, qty in cart]
transactions.append([
bill_no,
datetime.now().strftime("%Y-%m-%d"),
datetime.now().strftime("%H:%M:%S"),
"Sale",
f"{grand_total:.2f}",
str(transaction_details),
customer_name,
customer_phone
])
write_csv(TRANSACTIONS_FILE, transactions)
print("Generated and saved successfully!")
input("Press Enter to return to the main menu...")
# Clear Screen Function
def clear_screen():
import os
os.system('cls' if os.name == 'nt' else 'clear')
# View History Function
def view_history():
clear_screen()
transactions = read_csv(TRANSACTIONS_FILE)
if len(transactions) <= 1:
print("No transaction history found.")
input("Press Enter to return to the main menu...")
else:
while True:
clear_screen()
print("Transaction History")
print("1. View Detailed Bill of a Specific Transaction")
print("2. View Summary of All Bills")
print("3. Return to Main Menu")
choice = input("Select an option: ").strip()
if choice == "1":
while True:
clear_screen()
# Show list of all bills before selecting one
print("---- Available Bills ----")
print("{:<10} {:<15} {:<15} {:<20} {:<10}".format("Bill No", "Date", "Time", "Customer Name", "Total Amount"))
print("-" * 70)
for row in transactions[1:]:
print(f"{row[0]:<10} {row[1]:<15} {row[2]:<15} {row[6]:<20} {row[4]:<10}")
print("-" * 70)
bill_no = input("Enter the Bill No to view full details (or type 'exit' to go back): ").strip()
if bill_no.lower() == "exit":
break
# Display details of the selected bill
for row in transactions[1:]:
if row[0] == bill_no:
clear_screen()
print(f"---- Detailed Bill for Bill No. {row[0]} ----")
print(f"Date: {row[1]}")
print(f"Time: {row[2]}")
print(f"Customer Name: {row[6]}")
print(f"Transaction Type: {row[3]}")
print("\n--- Purchased Items ---")
details = eval(row[5]) # Convert string representation of list to actual list
subtotal = 0
total_cgst = 0
total_sgst = 0
for idx, item in enumerate(details, start=1):
product_total = item['Price'] * item['Quantity']
item_cgst = product_total * cgst_rate / 100
item_sgst = product_total * sgst_rate / 100
subtotal += product_total
total_cgst += item_cgst
total_sgst += item_sgst
print(f"{idx}. {item['Item']} | Price: {item['Price']:.2f} | Quantity: {item['Quantity']}")
print(f" Product price x quantity: {item['Price']} x {item['Quantity']} = {product_total:.2f}")
print(f" GST (CGST + SGST): {item_cgst:.2f} + {item_sgst:.2f} = {item_cgst + item_sgst:.2f}")
print(f" Total (with GST): {product_total + item_cgst + item_sgst:.2f}\n")
grand_total = subtotal + total_cgst + total_sgst
print("--- Bill Summary ---")
print(f"Subtotal: {subtotal:.2f}")
print(f"CGST ({cgst_rate}%): {total_cgst:.2f}")
print(f"SGST ({sgst_rate}%): {total_sgst:.2f}")
print(f"Grand Total: {grand_total:.2f}")
input("\nPress Enter to return to the history menu...")
break
else:
print("Bill No not found. Please try again.")
input("Press Enter to continue...")
elif choice == "2":
# Display summary of all bills
clear_screen()
print("---- Bill Summary ----")
print("{:<10} {:<15} {:<15} {:<20} {:<10}".format("Bill No", "Date", "Time", "Customer Name", "Total Amount"))
print("-" * 70)
for row in transactions[1:]:
print(f"{row[0]:<10} {row[1]:<15} {row[2]:<15} {row[6]:<20} {row[4]:<10}")
print("-" * 70)
input("\nPress Enter to return to the history menu...")
elif choice == "3":
break
else:
print("Invalid option. Please try again.")
# Update CGST Rate
def update_cgst_rate():
global cgst_rate
try:
cgst_rate = float(input(f"Enter new CGST rate (current: {cgst_rate}%): ").strip())
print("CGST rate updated successfully.")
except ValueError:
print("Invalid rate. No changes made.")
input("Press Enter to return to the admin dashboard...")
# Update SGST Rate
def update_sgst_rate():
global sgst_rate
try:
sgst_rate = float(input(f"Enter new SGST rate (current: {sgst_rate}%): ").strip())
print("SGST rate updated successfully.")
except ValueError:
print("Invalid rate. No changes made.")
input("Press Enter to return to the admin dashboard...")
# Global variables for CGST and SGST rates
cgst_rate = 6.0
sgst_rate = 6.0
# Main execution
if __name__ == "__main__":
initialize_files()
main_menu()