-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasket.py
More file actions
167 lines (132 loc) · 5.97 KB
/
basket.py
File metadata and controls
167 lines (132 loc) · 5.97 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
import csv
import os
import re
from datetime import datetime
from item import Item
class Basket:
def __init__(self):
self.items = []
self.bills = []
self.exported_bill_ids = self.load_exported_bills() # Avoid re-exporting the same bill
def add_item(self, item_code, internal_price, discount, sales_price, quantity):
item = Item(item_code, internal_price, discount, sales_price, quantity)
self.items.append(item)
def delete_item(self, line_number):
if 0 <= line_number <len(self.items):
del self.items[line_number]
print(f"Item at line {line_number + 1} has been deleted.")
else:
print ("Invalid line numbers.")
def update_item(self, line_number, sale_price = None, discount = None, quantity = None):
if 0 <= line_number < len(self.items):
item = self.items[line_number]
if sale_price is not None:
item.sale_price = sale_price
if discount is not None:
item.discount = discount
if quantity is not None:
item.quantity = quantity
print (f"Item at line {line_number + 1} has been updated.")
else:
print ("Invalid line number")
def show_items(self):
if not self.items:
print("Basket is empty.")
for idx, item in enumerate(self.items):
print(f"{idx + 1}: {item}")
def generate_bill(self):
if not self.items:
print("Basket is empty. Cannot generate bill.")
return
if not hasattr(self, 'bills'):
self.bills = []
# Load persistent bill counter
counter_path = "bills/bill_counter.txt"
if os.path.exists(counter_path):
with open(counter_path, "r") as f:
bill_number = int(f.read().strip()) + 1
else:
bill_number = 1 # First bill
# Save the updated bill number
with open(counter_path, "w") as f:
f.write(str(bill_number))
bill_total = sum(item.line_total() for item in self.items)
bill = {
'bill_number': bill_number,
'items': self.items.copy(),
'total': bill_total
}
self.bills.append(bill)
# Create the folder if it doesn't exist
bill_folder = "bills"
os.makedirs(bill_folder, exist_ok=True)
# Save inside the folder
bill_filename = os.path.join(bill_folder, f"bill_{bill_number}.txt")
with open(bill_filename, 'w') as file:
file.write(f"Bill Number: {bill_number}\n")
for item in bill['items']:
file.write(f"{item}\n")
file.write(f"Grand Total: {bill_total}\n")
self.items = []
print(f"Bill {bill_number} generated and saved to '{bill_filename}'. Total: {bill_total}")
def load_exported_bills(self):
exported_path = "bills/exported_bills.txt"
if os.path.exists(exported_path):
with open(exported_path, "r") as f:
return set(line.strip() for line in f.readlines())
return set()
def save_exported_bill(self, bill_id):
exported_path = "bills/exported_bills.txt"
with open(exported_path, "a") as f:
f.write(bill_id + "\n")
def search_bill(self, bill_number):
bill_folder = "bills"
bill_filename = os.path.join(bill_folder, f"bill_{bill_number}.txt")
if os.path.exists(bill_filename):
print(f"\n--- Contents of Bill {bill_number} ---")
with open(bill_filename, 'r') as file:
for line in file:
print(line.strip())
print("----------------------------\n")
else:
print(f"Bill with number {bill_number} not found in '{bill_folder}/'.")
def generate_tax_transaction_file(self, filename="tax_transactions.csv"):
if not hasattr(self, 'bills') or not self.bills:
print("No bills to generate tax transaction file.")
return
folder = "bills"
os.makedirs(folder, exist_ok=True)
filepath = os.path.join(folder, filename)
file_exists = os.path.exists(filepath)
is_empty = not file_exists or os.path.getsize(filepath) == 0
with open(filepath, mode='a', newline='') as file:
writer = csv.writer(file)
# Updated header
if is_empty:
writer.writerow(["ItemCode", "InternalPrice", "Discount", "SalesPrice", "Quantity", "Checksum"])
for bill in self.bills:
bill_id = f"BILL{datetime.now().strftime('%Y%m%d')}-{bill['bill_number']:03d}"
# Skip if already exported
if bill_id in self.exported_bill_ids:
continue
for item in bill['items']:
item_code = item.item_code
internal_price = item.internal_price
discount = item.discount
sales_price = item.sales_price
qty = item.quantity
# Build the transaction string based on these fields
transaction = f"{item_code},{internal_price},{discount},{sales_price},{qty}"
checksum = self.calculate_checksum(transaction)
# Write all fields without including the bill_id
writer.writerow([item_code, internal_price, discount, sales_price, qty, checksum])
# Mark this bill as exported
self.exported_bill_ids.add(bill_id)
self.save_exported_bill(bill_id)
print(f"Tax transaction file '{filename}' has been updated with new records.")
@staticmethod
def calculate_checksum(transaction_line):
uppercase = sum(1 for c in transaction_line if c.isupper())
lowercase = sum(1 for c in transaction_line if c.islower())
numbers = sum(1 for c in transaction_line if c.isdigit() or c == '.')
return uppercase + lowercase + numbers