-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
679 lines (493 loc) · 22.4 KB
/
app.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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
#*****************************************
# Maintainer : SHIVAM
#*****************************************
#Imports
from flask import Flask, render_template, request, redirect, url_for , session ,send_file
import hashlib
from datetime import datetime
import sqlite3
import os
from functools import wraps
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle , Paragraph
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet
app = Flask(__name__)
app.secret_key = os.urandom(24)
class Medicine:
def __init__(self, name, price, mrp, quantity, expiry,date ):
self.name = name
self.price = price
self.mrp = mrp
self.quantity = quantity
self.expiry = datetime.strptime(expiry, '%Y-%m-%d').date()
self.date = datetime.strptime(date, '%Y-%m-%d %H:%M:%S').date()
class Transaction_details:
def __init__(self,id, customer_name, phone_no, issued_by,name,quantity_sold,total_amount,datestamp):
self.id = id
self.customer_name = customer_name
self.phone_no = phone_no
self.issued_by = issued_by
self.name = name
self.quantity_sold = quantity_sold
self.total_amount = total_amount
self.datestamp = datestamp
class PharmacyManagementSystem:
def __init__(self):
self.initialize_database()
def initialize_database(self):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS medicines (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
price REAL NOT NULL,
mrp REAL NOT NULL,
quantity INTEGER NOT NULL,
expiry TEXT NOT NULL,
date TEXT NOT NULL
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS transaction_info(
id INTEGER PRIMARY KEY AUTOINCREMENT,
customer_name TEXT NOT NULL,
phone_no INTEGER NOT NULL,
issued_by TEXT NOT NULL,
medicine_name TEXT NOT NULL,
quantity_sold INTEGER NOT NULL,
total_amount REAL NOT NULL,
datestamp TEXT NOT NULL
)
''')
connection.commit()
connection.close()
def register_user(self, username, password):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
# Check if the username is already taken
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
if cursor.fetchone():
connection.close()
return "Username already taken. Please choose a different username."
# Hash the password before storing in the database
hashed_password = hashlib.sha256(password.encode()).hexdigest()
cursor.execute('''
INSERT INTO users (username, password)
VALUES (?, ?)
''', (username, hashed_password))
connection.commit()
connection.close()
return "Registration successful. You can now login."
def get_users(self):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
cursor.execute('SELECT * FROM users')
user_data = cursor.fetchall()
connection.close()
return user_data
def remove_user(self,username):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
cursor.execute('DELETE FROM users WHERE id = ?', (username,))
connection.commit()
connection.close()
return "User removed success"
def verify_user(self, username, password):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
# Hash the password for comparison with the hashed password in the database
hashed_password = hashlib.sha256(password.encode()).hexdigest()
cursor.execute('''
SELECT * FROM users WHERE username = ? AND password = ?
''', (username, hashed_password))
user_data = cursor.fetchone()
connection.close()
if user_data:
return True
else:
return False
def add_medicine(self, name, price, mrp, quantity, expiry):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
date=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
cursor.execute('''
INSERT INTO medicines (name, price, mrp, quantity, expiry , date)
VALUES (?, ?, ?, ?, ? , ?)
''', (name, price, mrp, quantity, expiry , date))
connection.commit()
connection.close()
def find_medicine(self, name):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
cursor.execute('''
SELECT * FROM medicines WHERE name = ?
''', (name,))
medicine_data = cursor.fetchone()
connection.close()
if medicine_data:
return Medicine(*medicine_data[1:])
else:
return None
def update_medicine_quantity(self, name, quantity):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
cursor.execute('''
UPDATE medicines SET quantity = quantity + ? WHERE name = ?
''', (quantity, name))
connection.commit()
connection.close()
def sell_medicine(self, name, quantity):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
cursor.execute('SELECT quantity FROM medicines WHERE name = ?', (name,))
current_quantity_row = cursor.fetchone()
if current_quantity_row is None:
connection.close()
print(f"Medicine '{name}' does not exist in the inventory.")
return
current_quantity = int(current_quantity_row[0])
cursor.execute('SELECT * FROM medicines WHERE name = ?', (name,))
medicine_data = cursor.fetchone()
if medicine_data is None:
connection.close()
print(f"Medicine '{name}' does not exist in the inventory.")
return
if current_quantity and current_quantity >= int(quantity):
total_amount = medicine_data[3] * int(quantity)
quantity_left = current_quantity - int(quantity)
datestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
cursor.execute('UPDATE medicines SET quantity = ? WHERE name = ?', (quantity_left, name))
# cursor.execute('INSERT INTO sales (medicine_name, quantity_sold, quantity_left, total_amount, datestamp) VALUES (?, ?, ?, ?, ?)',
# (name, quantity, quantity_left, total_amount, datestamp))
connection.commit()
connection.close()
print(f"Sold {quantity} units of '{name}' for ${total_amount:.2f} :")
else:
connection.close()
print(f"Not enough stock for '{name}'. Available: {current_quantity[0] if current_quantity else 0}")
def display_inventory(self):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
cursor.execute('''
SELECT * FROM medicines
''')
medicines_data = cursor.fetchall()
connection.close()
if not medicines_data:
return []
else:
medicines = []
for medicine_data in medicines_data:
medicine = Medicine(*medicine_data[1:])
medicines.append(medicine)
return medicines
def generate_pdf_report(self, start_date, end_date):
filename = "inventory_report.pdf"
doc = SimpleDocTemplate(filename, pagesize=letter)
elements = []
# Add title, generated by, and date
styles = getSampleStyleSheet()
title = Paragraph("PharmaCO : Inventory Report", styles['Title'])
generated_by = Paragraph(f"Generated by : {session.get('username', 'Anonymous')}", styles['Normal'])
current_date = Paragraph(f"Date : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", styles['Normal'])
signed_by = Paragraph(f"Signed by : {session.get('username', 'Anonymous')}", styles['Normal'])
elements.extend([title, generated_by, current_date])
# Generate the table data for the report
data = [['Medicine Name', 'Price', 'Quantity', 'MRP', 'Expiry', 'Date']]
all_medicines = self.display_inventory()
# Filter medicines based on start_date and end_date
filtered_medicines = [medicine for medicine in all_medicines if start_date <= medicine.date <= end_date]
for medicine in filtered_medicines:
data.append([medicine.name, medicine.price, medicine.quantity, medicine.mrp, medicine.expiry, medicine.date])
# Create the table and add it to the elements list
table = Table(data)
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('BOTTOMPADDING', (0, 0), (-1, 0), 12),
('BACKGROUND', (0, 1), (-1, -1), colors.beige),
('GRID', (0, 0), (-1, -1), 1, colors.black)
]))
elements.append(table)
elements.extend([signed_by])
# Build the PDF file
doc.build(elements)
return filename
def remove_medicine(self, name):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
cursor.execute('DELETE FROM medicines WHERE name = ?', (name,))
connection.commit()
connection.close()
print(f"Medicine '{name}' removed from the inventory.")
def recently_updated(self):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
cursor.execute('''
SELECT * FROM medicines
ORDER BY id DESC LIMIT 12
''')
medicines_data = cursor.fetchall()
connection.close()
if not medicines_data:
return []
else:
medicines = []
for medicine_data in medicines_data:
medicine = Medicine(*medicine_data[1:])
medicines.append(medicine)
return medicines
def add_transaction_deatils(self, customer_name,phone_no, issued_by,medicine_name, quantity_sold,total_amount):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
datestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
cursor.execute('''
INSERT INTO transaction_info(customer_name,phone_no, issued_by,medicine_name, quantity_sold,total_amount,datestamp)
VALUES (?, ?, ?, ?, ? , ? , ?)
''', (customer_name,phone_no, issued_by,medicine_name, quantity_sold,total_amount,datestamp))
connection.commit()
connection.close()
def get_transaction_details(self):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
cursor.execute('''
SELECT id, customer_name, phone_no, issued_by, medicine_name, quantity_sold, total_amount, datestamp
FROM transaction_info
''')
transaction_data = cursor.fetchall()
connection.close()
if not transaction_data:
return []
transactions = []
for row in transaction_data:
id, customer_name, phone_no, issued_by, medicine_name, quantity_sold, total_amount, datestamp = row
sale = Transaction_details(id, customer_name, phone_no, issued_by, medicine_name, quantity_sold, total_amount, datestamp)
transactions.append(sale)
return transactions
def remove_transaction_details(self, id):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
cursor.execute('DELETE FROM transaction_info WHERE id = ?', (id,))
connection.commit()
connection.close()
def get_customer_recent(self):
connection = sqlite3.connect('pharmacy.db')
cursor = connection.cursor()
cursor.execute('''
SELECT * FROM transaction_info
ORDER BY id DESC LIMIT 1
''')
customer_data = cursor.fetchone()
connection.close()
if not customer_data:
return None
else:
customer = Transaction_details(*customer_data[0:])
return customer
############################################################################################
pharmacy = PharmacyManagementSystem()
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'username' not in session:
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
# Login route
@app.route('/login', methods=['GET', 'POST'])
def login():
message = None
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if pharmacy.verify_user(username, password):
session['username'] = username
return redirect(url_for('home'))
else:
return render_template('login.html', message='Invalid!! username or password')
return render_template('login.html')
# Register route
@app.route('/register', methods=['GET', 'POST'])
def register():
message=None
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
result = pharmacy.register_user(username, password)
return render_template('register.html', result=result ,message='New User Register Sucessfully!!')
return render_template('register.html')
# Logout route
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect(url_for('login'))
#########################################################################
#HOME
@app.route('/')
@login_required
def home():
all_medicines = pharmacy.display_inventory()
recently= pharmacy.recently_updated()
recently=recently[-10:]
current_date = datetime.now().date() # Convert current_date to datetime.date object
users=pharmacy.get_users()
expired_medicines = [medicine for medicine in all_medicines if medicine.expiry < current_date]
out_of_stock_medicines = [medicine for medicine in all_medicines if medicine.quantity == 0]
recently_sold=pharmacy.get_transaction_details()
recently_sold = recently_sold[-10:]
return render_template('index.html', medicines=all_medicines, expired_medicines=expired_medicines , recently=recently , outstocks=out_of_stock_medicines ,users=users,sell=recently_sold)
@app.route('/remove_user', methods=['GET', 'POST'])
@login_required
def remove_user():
message=None
all_users = pharmacy.get_users()
if request.method == 'POST':
selected_user = request.form.getlist('user_checkbox')
for username in selected_user:
pharmacy.remove_user(username)
message=f"{username} Removed Successfully! "
return render_template('remove_user.html',users=all_users,message=message)
#add_medicine
@app.route('/add_medicine', methods=['GET', 'POST'])
@login_required
def add_medicine():
message = None
if request.method == 'POST':
name = request.form['name']
price = float(request.form['price'])
quantity = int(request.form['quantity'])
mrp = float(request.form['mrp'])
expiry = request.form['expiry']
try:
expiry = datetime.strptime(expiry, '%Y-%m-%d').date()
except ValueError:
return "Invalid Expiry Date Format. Please use yyyy-mm-dd."
pharmacy.add_medicine(name, price, mrp, quantity, expiry)
message = "Medicine added successfully!"
# return redirect(url_for('add_medicine'))
return render_template('add_medicine.html', message=message , medicines=pharmacy.recently_updated())
#find_medicine
@app.route('/find_medicine', methods=['GET', 'POST'])
@login_required
def find_medicine():
if request.method == 'POST':
name = request.form['name']
medicine = pharmacy.find_medicine(name)
return render_template('find_medicine.html', medicine=medicine)
return render_template('find_medicine.html', medicine=None)
#update_medicine_quantity
@app.route('/update_medicine_quantity', methods=['GET', 'POST'])
@login_required
def update_medicine_quantity_route():
recent_update=None
message=None
if request.method == 'POST':
name = request.form['name']
quantity = int(request.form['quantity'])
pharmacy.update_medicine_quantity(name, quantity)
recent_update=pharmacy.recently_updated()
message="Updated Successfully!"
# return redirect(url_for('display_inventory'))
return render_template('update_medicine_quantity.html' ,recently=recent_update,message=message)
@app.route('/remove_medicine', methods=['GET', 'POST'])
@login_required
def remove_medicine():
message = None
all_medicines = pharmacy.display_inventory()
if request.method == 'POST':
selected_medicines = request.form.getlist('medicine_checkbox')
for medicine_name in selected_medicines:
pharmacy.remove_medicine(medicine_name)
message="Medicine's Removed Successfully! "
return render_template('remove_medicine.html', medicines=all_medicines ,message=message)
@app.route('/remove_sales_history', methods=['GET', 'POST'])
@login_required
def remove_sales_history():
message1 = None
history = None # Add this line to initialize the history variable
if request.method == 'POST':
id = request.form['id']
# customer_name = request.form['customer_name']
pharmacy.remove_transaction_details(id)
# pharmacy.remove_customer_info(customer_name)
message1 = f"History for ID '{id}' removed successfully!"
# Fetch updated sales history after removal
# sales_history = pharmacy.get_sales()
x=pharmacy.get_transaction_details()
return render_template('remove_sales.html', message1=message1, medicines=x)
#SeLL medicine
@app.route('/sell_medicine', methods=['GET', 'POST'])
@login_required
def sell_medicine_route():
message = None
if request.method == 'POST':
medicine_names = request.form.getlist('medicine_name')
quantities = request.form.getlist('quantity')
customer_name = request.form['customer_name'] # Get customer name from the form
phone_no = request.form['phone_no'] # Get phone number from the form
issued_by = request.form['issued_by']
message="Medicine's sold Successfully! , Now Generate Invoice "
invoice = [] # List to store invoice data
# Process the data as needed
for name, quantity in zip(medicine_names, quantities):
if name and quantity:
medicine = pharmacy.find_medicine(name)
if medicine:
total_amount = medicine.mrp * int(quantity)
invoice.append({
'name': medicine.name,
'quantity_sold': int(quantity),
'price': medicine.mrp,
'total_amount': total_amount
})
# Perform the sell operation using pharmacy.sell_medicine()
pharmacy.sell_medicine(name, int(quantity))
pharmacy.add_transaction_deatils(customer_name,phone_no, issued_by,name, int(quantity),total_amount)
total_amount = sum(item['total_amount'] for item in invoice)
# Store the invoice data in a session variable
session['invoice'] = {
'invoice_items': invoice,
'total_amount': total_amount
}
return render_template('sell_medicine.html', medicines=pharmacy.display_inventory(), invoice=invoice, total_amount=total_amount ,message=message )
return render_template('sell_medicine.html', medicines=pharmacy.display_inventory())
#Invoice
@app.route('/invoice', methods=['GET', 'POST'])
@login_required
def invoice():
customers = pharmacy.get_customer_recent() # Get the list of customers
customers = [customers] if customers else []
invoice_data = session.get('invoice') # Retrieve the invoice data from the session
date=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return render_template('invoice.html', customers=customers, invoice_data=invoice_data , date=date)
#Display Inventory
@app.route('/display_inventory')
@login_required
def display_inventory():
return render_template('display_inventory.html', medicines=pharmacy.display_inventory())
#Generate Report
@app.route('/generate_report', methods=['GET', 'POST'])
@login_required
def generate_report():
if request.method == 'POST':
start_date_str = request.form['start_date']
end_date_str = request.form['end_date']
start_date = datetime.strptime(start_date_str, '%Y-%m-%d').date()
end_date = datetime.strptime(end_date_str, '%Y-%m-%d').date()
report_filename = pharmacy.generate_pdf_report(start_date, end_date)
return send_file(report_filename, as_attachment=True)
return render_template('generate_report.html')
##############################################################################################
if __name__ == '__main__':
app.run(debug=True)