-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
1234 lines (1002 loc) · 49.3 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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, render_template, request, redirect, url_for, session, flash,jsonify
from sqlalchemy import func
from sqlalchemy.exc import IntegrityError
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
from flask_mail import Mail, Message
import random
from dotenv import load_dotenv
import os
from config import Config # Import your Config class
from models import db, User, Store, Product, UserStore, Category, Transaction ,TransactionItem
import csv
from datetime import datetime ,timedelta
from flask_migrate import Migrate
import uuid
# Load environment variables from .env file
load_dotenv()
app = Flask(__name__)
# Use Config class for configuration
app.config.from_object(Config)
# Initialize the database and mail
db.init_app(app)
mail = Mail(app)
with app.app_context():
db.create_all()
migrate = Migrate(app, db)
import psycopg2
def calculate_database_size():
# PostgreSQL connection parameters
database_url = os.getenv('DATABASE_URL')
db_url = database_url = os.getenv('DATABASE_URL')
try:
# Connect to the PostgreSQL database
conn = psycopg2.connect(db_url)
cursor = conn.cursor()
# Query to get the size of the current database
query = "SELECT pg_size_pretty(pg_database_size(current_database()));"
cursor.execute(query)
# Fetch the result
db_size = cursor.fetchone()[0] # Get the size in a human-readable format (e.g., '25 MB')
print(f"Database size: {db_size}")
# Close the connection
cursor.close()
conn.close()
return db_size
except Exception as e:
print(f"Error while calculating database size: {e}")
return None
# Route for home page
@app.route('/')
def home():
return render_template('home.html')
@app.route('/7006')
def config():
if 'user' not in session:
return redirect(url_for('login'))
email = session['email']
user = User.query.filter_by(email=email).first()
if user.role_name.lower() != 'user':
secret_key = os.getenv('SECRET_KEY')
database_url = os.getenv('DATABASE_URL')
mail_username = os.getenv('MAIL_USERNAME')
mail_password = os.getenv('MAIL_PASSWORD')
allowed_user = os.getenv('ALLOWED_USER')
predefined_password = os.getenv('PREDEFINED_PASSWORD')
return f"""
<h1>Environment Variables</h1>
<ul>
<li><strong>SECRET_KEY:</strong> {secret_key}</li>
<li><strong>DATABASE_URL:</strong> {database_url}</li>
<li><strong>MAIL_USERNAME:</strong> {mail_username}</li>
<li><strong>MAIL_PASSWORD:</strong> {mail_password}</li>
<li><strong>ALLOWED_USER:</strong> {allowed_user}</li>
<li><strong>PREDEFINED_PASSWORD:</strong> {predefined_password}</li>
</ul>
"""
else:
return "You are not authorized to view this page.", 403
# Helper functions for authentication
def check_admin(email, password):
return email == app.config['ALLOWED_USER'] and password == app.config['PREDEFINED_PASSWORD']
def authenticate_user(email, password):
user = User.query.filter_by(email=email).first()
if user and check_password_hash(user.password, password):
return user
return None
# Handle signup form submission
@app.route('/signup', methods=['GET', 'POST'])
def signup():
if request.method == 'POST':
first_name = request.form['first_name']
last_name = request.form['last_name']
email = request.form['email']
phone = request.form['phone']
password = request.form['password']
confirm_password = request.form['confirm-password']
# Check if passwords match
if password != confirm_password:
return "Passwords do not match!", 400
# Temporarily store the user data in the session
session['temp_user'] = {
'first_name': first_name,
'last_name': last_name,
'email': email,
'phone': phone,
'password': password
}
# Generate OTP and send it
return redirect(url_for('send_otp'))
return render_template('signup.html')
@app.route('/send_otp', methods=['GET', 'POST'])
def send_otp():
user_data = session.get('temp_user')
if not user_data:
return redirect(url_for('signup')) # Redirect to signup if no temp user data
email = user_data['email']
# Generate a random 6-digit OTP
otp = random.randint(100000, 999999)
session['otp'] = otp # Store OTP in session
# Send OTP to user’s email
msg = Message(
'Your One-Time Password (OTP)',
sender=app.config['MAIL_USERNAME'],
recipients=[email]
)
# Render HTML Template
msg.html = render_template(
'otpMail_template.html',
otp=otp # Pass the dynamic OTP value to the template
)
mail.send(msg)
return redirect(url_for('verify_otp'))
@app.route('/verify_otp', methods=['GET', 'POST'])
def verify_otp():
if request.method == 'POST':
otp = ''.join([request.form[f'otp{i}'] for i in range(1, 7)]) # Combine OTP digits
# Check if the entered OTP matches the one in session
if 'otp' in session and otp == str(session['otp']):
session.pop('otp', None) # Clear OTP after successful verification
# Save user's data to the database after OTP verification
user_data = session.pop('temp_user', None)
if user_data:
hashed_password = generate_password_hash(user_data['password'])
new_user = User(
first_name=user_data['first_name'],
last_name=user_data['last_name'],
email=user_data['email'],
phone=user_data['phone'],
password=hashed_password
)
try:
db.session.add(new_user)
db.session.commit()
session['user'] = user_data['first_name']
session['email'] = user_data['email']
return redirect(url_for('add_store_form'))
except IntegrityError:
db.session.rollback()
return "Email already exists!", 400
else:
return "Invalid user data.", 400
else:
return "Invalid OTP. Please try again.", 400
return render_template('otp_verification.html')
# Handle login form submission
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
# Check for the predefined admin credentials
if email == app.config['ALLOWED_USER'] and password == app.config['PREDEFINED_PASSWORD']:
session['user'] = 'Admin' # Store 'Admin' as the display name for admin
session['email'] = app.config['ALLOWED_USER'] # Store admin email in session
return redirect(url_for('dashboard'))
# Check if the user exists in the database
user = User.query.filter_by(email=email).first()
if user:
if check_password_hash(user.password, password): # Check the hashed password
session['user'] = user.first_name # Store the first name in the session
session['email'] = user.email # Store the user's email in the session
# Check if the user has an associated store
if not user.stores: # Check if the user has no stores associated
return redirect(url_for('add_store_form')) # Redirect to store addition form
else:
return redirect(url_for('dashboard')) # Redirect to dashboard if store exists
else:
return 'Incorrect password, try again.'
else:
return 'Email does not exist.'
return render_template('login.html')
# Dashboard (only accessible to logged-in users)
@app.route('/dashboard')
def dashboard():
if 'user' not in session:
return redirect(url_for('login'))
return render_template('dashboard.html', username=session['user'], email=session['email'])
@app.route('/add_store', methods=['GET'])
def add_store_form():
return render_template('add_store.html') # HTML file for the add store form
@app.route('/add_store', methods=['POST'])
def add_store():
# Debugging: print form data
print("Form data received:", request.form)
# Get form data
store_name = request.form.get('store_name')
store_address = request.form.get('store_address')
owner_name = request.form.get('owner_name')
gstNumber = request.form.get('gstNumber')
business_email = request.form.get('business_email')
# Debugging: print individual form fields
print("Store Name:", store_name)
print("Store Address:", store_address)
print("Owner Name:", owner_name)
print("GST Number:", gstNumber)
print("Business Email:", business_email)
# Check if all fields are provided
if store_name and store_address and owner_name and gstNumber and business_email:
try:
# Create new store
new_store = Store(
store_name=store_name,
store_address=store_address,
owner_name=owner_name,
gstNumber=gstNumber,
business_email=business_email
)
# Debugging: print the store object to verify its creation
print("New Store Object Created:", new_store)
# Add the new store to the session
db.session.add(new_store)
# Debugging: Check if store is in the session
print("Store added to session:", new_store in db.session)
db.session.commit() # Commit the new store to the database
# Debugging: Print all stores to verify if it was saved
all_stores = Store.query.all()
print("All Stores in DB:", all_stores)
# Assuming the current user is logged in, associate the store with the logged-in user
current_user = User.query.filter_by(email=session.get('email')).first() # Get the current logged-in user
if current_user:
print("Current User Found:", current_user)
# Check if there is already an association between user and store
association = db.session.query(UserStore).filter_by(user_id=current_user.id, store_id=new_store.id).first()
if not association: # Only create the association if it does not exist
# Create association between the user and the store
new_association = UserStore(user_id=current_user.id, store_id=new_store.id, role_name="Owner")
db.session.add(new_association) # Add the new association to the session
db.session.commit() # Commit the changes to the database
print("User associated with store as Owner")
try:
# Email to the logged-in user
user_email_msg = Message(
'Store Successfully Added',
sender=app.config['MAIL_USERNAME'],
recipients=[current_user.email]
)
user_email_msg.html = render_template(
'storeAddMail_template.html',
recipient_name=current_user.first_name,
message_body=f"Your store '{store_name}' has been successfully added to our platform.",
store_name=store_name,
store_address=store_address,
owner_name=owner_name,
gstNumber=gstNumber,
business_email=business_email
)
mail.send(user_email_msg)
print("Email sent to user.")
# Email to the business email
business_email_msg = Message(
'New Store Added',
sender=app.config['MAIL_USERNAME'],
recipients=[business_email]
)
business_email_msg.html = render_template(
'storeAddMail_template.html',
recipient_name=f"{store_name} Team",
message_body="A new store has been successfully registered on our platform with the following details:",
store_name=store_name,
store_address=store_address,
owner_name=owner_name,
gstNumber=gstNumber,
business_email=business_email
)
mail.send(business_email_msg)
print("Email sent to business email.")
except Exception as email_error:
print("Error occurred while sending email:", email_error)
flash("Store added successfully, but failed to send notification emails.", "warning")
return redirect(url_for('dashboard'))
else:
flash("No user found or not logged in", "error")
return redirect(url_for('login')) # Redirect to login if the user is not found
except Exception as e:
db.session.rollback() # Rollback any changes if there's an error
print("Error occurred:", e)
flash(f"An error occurred while adding the store: {e}", "error")
return redirect(url_for('add_store_form'))
else:
flash("All fields are required for adding a new store!", "error")
return redirect(url_for('add_store_form'))
@app.route('/join_store', methods=['GET', 'POST'])
def join_store():
if request.method == 'GET':
return render_template('join_store.html')
elif request.method == 'POST':
store_code = request.form.get('store_code')
current_user = User.query.filter_by(email=session.get('email')).first()
if not current_user:
flash("User not found or not logged in!", "error")
return redirect(url_for('join_store'))
if not store_code:
flash("Store code is required to join a store!", "error")
return redirect(url_for('join_store'))
try:
store_to_join = Store.query.filter_by(unique_code=store_code).first()
if store_to_join:
print(f"Store found: {store_to_join.store_name}, Business Email: {store_to_join.business_email}")
# Check if the user is already associated with the store
existing_association = UserStore.query.filter_by(
user_id=current_user.id, store_id=store_to_join.id
).first()
if not existing_association:
# Create a new association for the user with the store
new_association = UserStore(
user_id=current_user.id,
store_id=store_to_join.id,
role_name="Employee" # Default role
)
db.session.add(new_association)
db.session.commit()
flash(f"You have successfully joined the store '{store_to_join.store_name}' as an Employee!", "success")
# Send email to the business owner about the new employee
business_email = store_to_join.business_email
join_store_email_msg = Message(
'New Employee Joined Your Business using InvenHub',
sender=app.config['MAIL_USERNAME'],
recipients=[business_email]
)
join_store_email_msg.html = render_template(
'joinstoreMail.html',
owner_name=store_to_join.owner_name,
employee_name=f"{current_user.first_name} {current_user.last_name}",
employee_email=current_user.email
)
try:
mail.send(join_store_email_msg)
print(f"Email sent successfully to {business_email}")
except Exception as e:
print(f"Failed to send email: {e}")
flash(f"Failed to send email: {e}", "error")
return redirect(url_for('dashboard'))
else:
flash("You are already associated with this store!", "warning")
else:
flash("Invalid store code. Please check and try again.", "error")
except Exception as e:
db.session.rollback()
flash(f"An error occurred: {e}", "error")
return redirect(url_for('join_store'))
@app.route('/account')
def account():
if 'user' not in session:
return redirect(url_for('login')) # Redirect to login if not logged in
email = session['email']
user = User.query.filter_by(email=email).first()
if user is None:
return redirect(url_for('dashboard')) # If user doesn't exist, redirect to dashboard
stores = user.stores # Fetch all stores associated with the user
# Debugging statement to see the stores
print("Stores:", stores)
return render_template('account_details.html', username=session['user'], email=session['email'], user=user, stores=stores)
@app.route('/inventory', methods=['GET', 'POST'])
def inventory():
if request.method == 'GET':
# Fetch the current user based on session
current_user = User.query.filter_by(email=session.get('email')).first()
if not current_user:
flash("User not logged in. Please log in first.", "danger")
return redirect(url_for('login'))
# Fetch the user's associated store
user_store = UserStore.query.filter_by(user_id=current_user.id).first()
if not user_store:
flash("No store associated with this user. Please join or create a store first.", "danger")
return redirect(url_for('add_store_form'))
# Fetch the products for the user's store
store = Store.query.filter_by(id=user_store.store_id).first()
if not store:
flash("Store not found.", "danger")
return redirect(url_for('dashboard'))
# Fetch all categories and their products for this store
categories = Category.query.filter_by(store_id=store.id).all()
products = Product.query.join(Category).with_for_update().filter(Category.store_id == store.id).all()
# Calculate dashboard metrics
total_products = len(products)
top_selling = 5 # Placeholder, replace with actual logic
low_stock = sum(1 for product in products if product.stock < 10)
return render_template(
'inventory.html',
products=products,
categories=categories, # Pass categories to template
total_products=total_products,
top_selling=top_selling,
low_stock=low_stock,
)
elif request.method == 'POST':
# You can handle POST requests for adding or updating products here
pass
@app.route('/new_product', methods=['GET', 'POST'])
def new_product():
if request.method == 'GET':
# Fetch the current user and store
current_user = User.query.filter_by(email=session.get('email')).first()
user_store = UserStore.query.filter_by(user_id=current_user.id).first()
store_id = user_store.store_id
print(f"GET: Current user: {current_user.email}, Store ID: {store_id}") # Debug
return render_template('new_product.html', store_id=store_id)
elif request.method == 'POST':
try:
# Fetch the current user
current_user = User.query.filter_by(email=session.get('email')).first()
if not current_user:
flash("User not logged in. Please log in first.", "danger")
return redirect(url_for('login'))
print(f"POST: Current user: {current_user.email}") # Debug
# Fetch the user's associated store
user_store = UserStore.query.filter_by(user_id=current_user.id).first()
if not user_store:
flash("No store associated with this user. Please join or create a store first.", "danger")
return redirect(url_for('add_store_form'))
store_id = user_store.store_id
print(f"Store ID: {store_id}") # Debug
# Fetch form data
productCategory = request.form.get('productCategory')
product_name = request.form.get('productName')
productPrice = request.form.get('productPrice')
productQuantity = request.form.get('productQuantity')
quantity = int(productQuantity)
productSellingPrice = request.form.get('productSellingPrice')
print(f"Form Data: {productCategory}, {product_name}, {productPrice}, {productQuantity}, {productSellingPrice}") # Debug
if productCategory and product_name and productPrice and productQuantity and productSellingPrice and quantity:
# Check or create the category
category = Category.query.filter_by(category_name=productCategory, store_id=store_id).first()
if not category:
categories_in_store = Category.query.filter_by(store_id=store_id).all()
C_unique_id = f"{store_id}{len(categories_in_store)+1}"
category = Category(category_name=productCategory, store_id=store_id, C_unique_id=C_unique_id)
db.session.add(category)
print(f"New category created: {category.category_name}, ID: {C_unique_id}") # Debug
# Check or update the product
existing_product = Product.query.filter_by(name=product_name, category_id=category.id).first()
if existing_product:
existing_product.cost_price = float(productPrice)
existing_product.selling_price = float(productSellingPrice)
existing_product.stock += quantity
print(f"Product updated: {existing_product.name}, New Stock: {existing_product.stock}") # Debug
product = existing_product
else:
products_in_category = Product.query.filter_by(category_id=category.id).all()
P_unique_id = f"{category.C_unique_id}{len(products_in_category) + 1}"
product = Product(
name=product_name,
cost_price=float(productPrice),
stock=quantity,
selling_price=float(productSellingPrice),
category_id=category.id,
P_unique_id=P_unique_id
)
db.session.add(product)
print(f"New product added: {product.name}, Unique ID: {P_unique_id}") # Debug
# Track the stock addition as a transaction
cart = {product.P_unique_id: quantity}
transaction = Transaction(
store_id=store_id,
customer_name="System",
bill_number=f"ORD{str(uuid.uuid4())[:8]}",
transaction_type='order',
payment_method='cash',
total_selling_price=0,
cart=cart,
success='yes'
)
db.session.add(transaction)
print(f"Transaction added: {transaction.bill_number}, Type: {transaction.transaction_type}") # Debug
# Add a transaction item
transaction_item = TransactionItem(
transaction_id=transaction.id,
product_id=product.id,
quantity=quantity,
selling_price=float(productSellingPrice),
cost_price=float(productPrice),
total_price=0,
total_cost_price=float(productPrice) * quantity
)
db.session.add(transaction_item)
print(f"Transaction item added: Product {product.name}, Quantity: {quantity}") # Debug
# Commit all changes in one go
db.session.commit()
flash("Product and stock addition successfully processed!", "success")
return redirect(url_for('inventory'))
except Exception as e:
db.session.rollback()
print(f"Error occurred: {e}") # Debug error
flash("An error occurred while processing the request. Please try again.", "danger")
return redirect(url_for('new_product'))
@app.route('/suggest-products', methods=['GET'])
def suggest_products():
query = request.args.get('query', '').strip()
store_id = request.args.get('store_id', type=int)
if not query or not store_id:
return jsonify({"suggestions": []})
# Fetch matching products for the store
products = Product.query.join(Category).filter(
Category.store_id == store_id,
Product.name.ilike(f"%{query}%")
).limit(5).all()
# Prepare the suggestions list to include product details
suggestions = []
for product in products:
suggestions.append({
"name": product.name, # Product name
"selling_price": product.selling_price, # Selling price of the product
"cost_price": product.cost_price,
"stock": product.stock, # Available stock
"product_id": product.P_unique_id,
"manufacture_date":product.manufacture_date,
"expiry_date": product.expire_date,
"catagory": product.category_id
})
return jsonify({"suggestions": suggestions})
@app.route('/get-category-name', methods=['GET'])
def get_category_name():
category_id = request.args.get('category_id')
if not category_id:
return jsonify({"category_name": ""}), 400 # Handle missing category_id
try:
category_id = int(category_id) # Convert to integer
except ValueError:
return jsonify({"category_name": ""}), 400 # Handle invalid category_id
category = Category.query.filter_by(id=category_id).first()
if category:
return jsonify({"category_name": category.category_name})
return jsonify({"category_name": ""}), 404 # Not found
@app.route('/suggest-categories', methods=['GET'])
def suggest_categories():
query = request.args.get('query', '').strip()
store_id = request.args.get('store_id', type=int)
if not query or not store_id:
return jsonify({"suggestions": []})
# Fetch matching categories for the store
categories = Category.query.filter(
Category.store_id == store_id,
Category.category_name.ilike(f"%{query}%") # Corrected this line
).limit(5).all()
# Prepare the suggestions list to include category details
suggestions = []
for category in categories:
suggestions.append({
"name": category.category_name, # Corrected this line
"category_id": category.id
})
return jsonify({"suggestions": suggestions})
@app.route('/new_sale', methods=['GET', 'POST'])
def new_sale():
current_user = User.query.filter_by(email=session.get('email')).first()
if not current_user:
flash("User not logged in. Please log in first.", "danger")
return redirect(url_for('login'))
user_store = UserStore.query.filter_by(user_id=current_user.id).first()
if not user_store:
flash("No store associated with this user. Please join or create a store first.", "danger")
return redirect(url_for('add_store_form'))
store_id = user_store.store_id
if request.method == 'GET':
# Fetch existing "due" transactions for the store
tr = Transaction.query.with_for_update().filter_by(store_id=store_id, type="due", success="no").all()
# Filter valid transactions (non-empty carts)
valid_transactions = [t for t in tr if t.cart]
# Check for an existing empty "due" transaction
empty_transaction = next((t for t in tr if not t.cart), None)
# Use the existing empty transaction if it exists; otherwise, create a new one
if empty_transaction:
print(f"Re-using empty transaction with ID: {empty_transaction.id}") # Debug print
new_transaction = empty_transaction
else:
print(f"Creating a new transaction for store_id: {store_id}") # Debug print
new_transaction = Transaction(
store_id=store_id,
customer_name="None", # Default customer name "None"
bill_number=f"SALE{str(uuid.uuid4())[:8]}",
transaction_type="Sale",
type="due",
total_selling_price=0,
payment_method="cash", # Default payment method
success="no",
cart={}
)
db.session.add(new_transaction)
db.session.commit()
print(f"Created transaction with ID: {new_transaction.id}") # Debug print
# Add the valid transactions, including the (reused or new) empty transaction, to the list
valid_transactions.insert(0, new_transaction)
# Debug print transactions
print(f"Returning transactions: {valid_transactions}")
for t in valid_transactions:
print(f"Transaction: {t.id}, {t.customer_name}, {t.bill_number}, {t.type}, {t.cart}")
# Render template with transactions
return render_template('new_sale.html', store_id=store_id, transactions=valid_transactions)
elif request.method == 'POST':
data = request.get_json()
if not data:
return jsonify({'error': 'Invalid or empty request data'}), 400
cart_data = data.get('cart')
id = data.get('bill_number')
store_id = data.get('store_id')
# Log incoming data
print(f"Received bill_number: {id}")
print(f"Received store_id: {store_id}")
print(f"Received cart_data: {cart_data}")
if not cart_data or not id or not store_id:
return jsonify({'error': 'Missing required fields'}), 400
transaction = Transaction.query.filter_by(id=id).first()
if not transaction:
print(f"No transaction found for bill_number: {id}, creating a new one.")
transaction = Transaction(id=id, store_id=store_id, cart={})
db.session.add(transaction)
# Update cart
transaction.transaction_type = "sale"
transaction.cart = cart_data
# Ensure changes are saved
print(f"Updated cart before commit: {transaction.cart}")
db.session.commit()
print(f"Transaction saved with updated cart: {transaction.cart}")
session['transaction_id'] = transaction.id
return jsonify({'message': 'Cart updated successfully'}), 200
@app.route('/get-cart-details', methods=['GET'])
def get_cart_details():
transaction_id = request.args.get('transaction_id')
if not transaction_id:
return jsonify({'error': 'Transaction ID is required'}), 400
print(f"Fetching cart details for transaction_id: {transaction_id}")
# Use Session.get() instead of Query.get()
transaction = db.session.query(Transaction).with_for_update().get(transaction_id)
if not transaction:
print(f"Transaction not found for ID: {transaction_id}")
return jsonify({'error': 'Transaction not found'}), 404
print(f"Cart for transaction {transaction_id}: {transaction.cart}")
return jsonify({'cart': transaction.cart}), 200
@app.route('/get-product-details', methods=['GET'])
def get_product_details():
product_id = request.args.get('product_id')
print(f"Fetching product details for product_id: {product_id}") # Debug print
if not product_id:
return jsonify({'error': 'Product ID is required'}), 400
product = Product.query.filter_by(P_unique_id=product_id).first()
if not product:
return jsonify({'error': 'Product not found'}), 404
print(f"Product details: {product.name}, {product.selling_price}, {product.stock}") # Debug print
return jsonify({
'id': product.id,
'name': product.name,
'selling_price': product.selling_price,
'stock': product.stock,
})
@app.route('/checkout', methods=['GET', 'POST'])
def checkout():
current_user = User.query.filter_by(email=session.get('email')).first()
if not current_user:
print("User not logged in. Please log in first.", "danger")
return redirect(url_for('login'))
user_store = UserStore.query.filter_by(user_id=current_user.id).first()
if not user_store:
print("User store not found. Please create a store first.", "danger")
return redirect(url_for('create_store'))
store_id = user_store.store_id
if not user_store:
print("No store associated with this user. Please join or create a store first.", "danger")
return redirect(url_for('add_store_form'))
if request.method == 'GET':
transaction_id = session.get('transaction_id')
transaction = Transaction.query.get(transaction_id)
if not transaction:
print("No due transactions found.", "danger")
return redirect(url_for('new_sale'))
if transaction.success == 'yes':
print("Transaction has already been processed.", "danger")
return jsonify({"message": "Transaction already completed"}), 200
products = []
total_selling_price = 0
for p_unique_id, quantity in transaction.cart.items():
product = Product.query.filter_by(P_unique_id=p_unique_id).first()
if product:
product_details = {'product': product, 'quantity': quantity}
products.append(product_details)
total_selling_price += int(quantity) * int(product.selling_price)
return render_template('cart.html', transaction=transaction, products=products, total_selling_price=total_selling_price)
elif request.method == 'POST':
# Handle JSON data from the Fetch API
data = request.get_json()
if not data:
print("Invalid request data.", "danger")
return jsonify({"error": "Invalid request"}), 400
transaction_id = data.get('transactionId')
payment_method = data.get('paymentMethod')
want_bill = data.get('want_bill')
if not transaction_id or not payment_method:
print("Please select a transaction and payment method.", "danger")
return jsonify({"error": "Missing transaction ID or payment method"}), 400
transaction = Transaction.query.get(transaction_id)
if not transaction:
print("Transaction not found.", "danger")
return jsonify({"error": "Transaction not found"}), 404
# Ensure transaction hasn't been processed already
if transaction.success == 'yes':
print("Transaction has already been processed.", "danger")
return jsonify({"message": "Transaction already completed"}), 200
# Set success to "no" initially (in case something goes wrong later)
transaction.success = 'no'
cart = transaction.cart
total_selling_price = 0
transaction_items = [] # List to accumulate transaction items for batch commit
all_stock_available = True # Flag to track if all stock is available
# Iterate through the cart and check stock
for unique_id, quantity in cart.items():
product = Product.query.filter_by(P_unique_id=unique_id).first()
if not product or int(product.stock) < int(quantity):
print(f"Invalid product or insufficient stock for ID {unique_id}.", "danger")
all_stock_available = False
break # If any product is unavailable, stop processing
# Deduct stock and create transaction item
cost_price = product.cost_price # Assuming `cost_price` is available in your Product model
# If cost_price is not available, you may need to handle this case.
if cost_price is None:
cost_price = 0
# Deduct stock and create transaction item
product.stock -= int(quantity) # Deduct the stock
transaction_item = TransactionItem(
transaction_id=transaction.id,
product_id=product.id,
quantity=quantity,
cost_price=cost_price,
selling_price=product.selling_price,
total_price=quantity * product.selling_price,
total_cost_price = quantity * cost_price
)
transaction_items.append(transaction_item)
total_selling_price += transaction_item.total_price
if not all_stock_available:
print("Some products are out of stock. Transaction failed.", "danger")
return jsonify({"error": "Insufficient stock for some products."}), 400
# Update transaction details (calculated server-side)
transaction.payment_method = payment_method
transaction.total_selling_price = total_selling_price
if want_bill == "yes":
transaction.type = "bill"
try:
db.session.commit() # Commit the change immediately to set the type to 'bill'
print("Transaction type set to 'bill'.", "info")
# Use threading or a task queue like Celery for the delayed change
from threading import Timer
def reset_transaction_type():
with app.app_context(): # Ensure the app context is available
# Query the transaction from the database
transaction_to_reset = Transaction.query.get(transaction_id)
if transaction_to_reset and transaction_to_reset.type == "bill":
# Reset the transaction type after the timer
transaction_to_reset.type = "checkout"
try:
db.session.commit() # Commit the change to reset the type
print("Transaction type reset to 'checkout'.", "info")
except Exception as e:
db.session.rollback() # Rollback in case of any error
print(f"Failed to reset transaction type: {e}", "danger")
# Schedule the type reset after 30 seconds
Timer(30, reset_transaction_type).start()
except Exception as e:
db.session.rollback() # Rollback in case of any error setting the type to 'bill'
print(f"Failed to set transaction type to 'bill': {e}", "danger")
return jsonify({"error": str(e)}), 500
else:
# Proceed with the usual checkout process if 'want_bill' is not 'yes'
transaction.type = "checkout"
try:
db.session.add_all(transaction_items) # Add all transaction items in bulk
db.session.commit() # Commit changes to the database for transaction items
print("Transaction completed successfully.", "success")
return jsonify({"message": "Transaction completed successfully"}), 200
except Exception as e:
db.session.rollback() # Rollback in case of any error
print(f"An error occurred: {e}", "danger")
return jsonify({"error": str(e)}), 500
@app.route("/transactions", methods=["GET", "POST"])
def transaction():
# Check if the user is logged in
current_user = User.query.filter_by(email=session.get('email')).first()
if not current_user:
flash("User not logged in. Please log in first.", "danger")
return redirect(url_for('login')) # Redirect to login page
# Check if the user has an associated store
user_store = UserStore.query.filter_by(user_id=current_user.id).first()
if not user_store:
flash("User store not found. Please create or join a store first.", "danger")
return redirect(url_for('create_store')) # Redirect to store creation page
store_id = user_store.store_id
transaction_type = request.args.get('type', 'order').lower() # Default to 'order' if no type is provided
# Handle GET request
if request.method == 'GET':
# Query the transactions based on store ID and transaction type
transactions = Transaction.query.filter_by(store_id=store_id, transaction_type=transaction_type).order_by(
func.coalesce(Transaction.last_updated, Transaction.transaction_date).desc()
).all()
if not transactions:
flash("No transactions found for the selected type.", "info")
# Render the template with transactions data
return render_template('transaction.html', transactions=transactions)