-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2333 lines (1965 loc) · 83 KB
/
app.py
File metadata and controls
2333 lines (1965 loc) · 83 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
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_migrate import Migrate
from functools import wraps
from flask import Flask, jsonify, request, make_response, send_from_directory
import os
import sqlite3
from sqlalchemy import inspect, text, func
from models import db, User, Property, ListingHistory, Company
from auth_decorators import (
token_required,
payment_required,
admin_required,
privileged_required,
company_payment_required,
)
from datetime import datetime, timedelta
from flask_cors import CORS
from property_service import PropertyService
from payment_utils import (
update_payment_status,
check_payment_validity,
update_company_payment_status,
)
app = Flask(__name__, static_folder="client/build", static_url_path="")
app.config[
"SQLALCHEMY_DATABASE_URI"
] = "postgresql://postgres:SyncLabPASPAS@localhost:5432/real_estate_db"
app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {
"pool_size": 10,
"max_overflow": 20,
"pool_recycle": 1800,
}
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SECRET_KEY"] = os.environ.get(
"SECRET_KEY", "dev-secret-key-change-in-production"
)
CORS(app, supports_credentials=True, origins=["http://localhost:5173"])
# CORS(app, supports_credentials=True, origins=["http://34.44.116.8:5173"])
# Initialize the database with the app
db.init_app(app)
migrate = Migrate(app, db)
def initialize_database():
"""Initialize database and create default user if needed"""
with app.app_context():
# Check if tables exist
inspector = inspect(db.engine)
tables_exist = len(inspector.get_table_names()) > 0
# Create tables if they don't exist
if not tables_exist:
app.logger.info("Creating database tables...")
db.create_all()
# Check if default user exists, if not create it
try:
default_user = User.query.filter_by(id=1).first()
if not default_user:
app.logger.info("Creating default user")
default_user = User(
id=1,
email="gvantsakhubulia@gmail.com",
username="gvantsa",
phone="571155949",
name_ka="გვანცა",
name_en="Gvantsa",
name_ru="Гванца",
surname="Khubulia",
hardcoded_id="20764744",
position="CEO",
company_name="IDK JET",
payment=True,
privileged=True,
)
# Set the password
default_user.password = "Baqteria#1"
# Set payment dates
current_time = datetime.utcnow()
default_user.last_payment_date = current_time
default_user.payment_expiry_date = current_time + timedelta(
days=365
) # 1 year for admin
db.session.add(default_user)
db.session.commit()
app.logger.info("Created default user")
else:
app.logger.info("Default user already exists")
# Update user fields if needed
update_needed = False
if not default_user.username:
default_user.username = "gvantsa"
update_needed = True
if default_user.payment is None:
default_user.payment = True
update_needed = True
if default_user.privileged is None:
default_user.privileged = True
update_needed = True
if not default_user.surname:
default_user.surname = "Khubulia"
update_needed = True
if not default_user.payment_expiry_date:
default_user.last_payment_date = datetime.utcnow()
default_user.payment_expiry_date = datetime.utcnow() + timedelta(
days=365
)
update_needed = True
if update_needed:
db.session.commit()
app.logger.info("Updated default user with missing fields")
except Exception as e:
app.logger.error(f"Error handling default user: {e}")
app.logger.exception("Full traceback:")
@app.route("/api/auth/login", methods=["POST"])
def login():
"""Login with username or email and password"""
data = request.json
if not data or not data.get("username") or not data.get("password"):
return (
jsonify(
{"result": False, "errors": "Username/email and password required"}
),
400,
)
# Convert username/email to lowercase for case-insensitive comparison
username_or_email = data["username"].lower()
# Try to find user by username first (case-insensitive)
user = User.query.filter(func.lower(User.username) == username_or_email).first()
# If not found, try email (case-insensitive)
if not user:
user = User.query.filter(func.lower(User.email) == username_or_email).first()
# Check if user exists and password is correct
if user and user.verify_password(data["password"]):
# Generate a new token for the user
token = user.generate_auth_token()
db.session.commit()
response = make_response(
jsonify({
"result": True,
"data": {
"message": "Login successful"
}
}),
200
)
# Set token expiration
expiration_date = datetime.utcnow() + timedelta(days=1)
# Set access token cookie
response.set_cookie(
"access_token",
token,
expires=expiration_date,
httponly=False,
secure=False,
samesite=None,
)
# Set user ID cookie - not httponly so it can be accessed by JavaScript
response.set_cookie(
"user_id",
str(user.id),
expires=expiration_date,
httponly=False,
secure=False,
samesite=None,
)
return response
else:
return (
jsonify({"result": False, "errors": "Invalid username/email or password"}),
401,
)
@app.route("/api/auth/logout", methods=["POST"])
@token_required
def logout():
"""Logout current user by invalidating their token"""
user = request.current_user
user.access_token = None
user.token_expiry = None
db.session.commit()
response = make_response(
jsonify({"result": True, "data": {"message": "Logout successful"}})
)
# Delete both the access_token and user_id cookies
response.delete_cookie("access_token")
response.delete_cookie("user_id")
return response
@app.route("/api/auth/status", methods=["GET"])
@token_required
def auth_status():
"""Check if user is logged in"""
user = request.current_user
# Check payment validity
payment_valid, payment_message = check_payment_validity(user)
# Get company info if user belongs to a company
company_data = None
if user.company_id:
company = db.session.get(Company, user.company_id)
if company:
company_data = {"id": company.id, "name": company.name}
return jsonify(
{
"result": True,
"data": {
"authenticated": True,
"user_id": user.id,
"username": user.username,
"name": user.name_en,
"surname": user.surname,
"payment_status": user.payment,
"payment_valid": payment_valid,
"payment_expires": user.payment_expiry_date.isoformat()
if user.payment_expiry_date
else None,
"privileged": user.privileged,
"company": company_data,
},
}
)
# First, let's create a decorator to check if user is CEO
def ceo_required(f):
"""Decorator to require CEO privileges"""
@wraps(f)
def decorated_function(*args, **kwargs):
current_user = request.current_user
if not current_user.position or current_user.position.lower() != "ceo":
return jsonify({
"result": False,
"errors": "Access denied. CEO privileges required."
}), 403
if not current_user.company_id:
return jsonify({
"result": False,
"errors": "CEO must be associated with a company."
}), 400
return f(*args, **kwargs)
return decorated_function
# First, let's create a decorator to check if user is CEO
def ceo_required(f):
"""Decorator to require CEO privileges"""
@wraps(f)
def decorated_function(*args, **kwargs):
current_user = request.current_user
if not current_user.position or current_user.position.lower() != "ceo":
return jsonify({
"result": False,
"errors": "Access denied. CEO privileges required."
}), 403
if not current_user.company_id:
return jsonify({
"result": False,
"errors": "CEO must be associated with a company."
}), 400
return f(*args, **kwargs)
return decorated_function
# CEO - Create User within Company
@app.route("/api/ceo/user", methods=["POST"])
@token_required
@ceo_required
def ceo_create_user():
"""Create a new user within CEO's company"""
data = request.json
if not data:
return jsonify({"result": False, "errors": "Invalid user data"}), 400
current_user = request.current_user
# Validate required fields
required_fields = [
"email",
"username",
"password",
"phone",
"name_ka",
"name_en",
"name_ru",
"commission_percentage",
"surname",
"position"
]
missing_fields = [field for field in required_fields if field not in data]
if missing_fields:
return jsonify({
"result": False,
"errors": f"Missing required fields: {', '.join(missing_fields)}",
}), 400
# Validate commission percentage if provided
commission_percentage = data.get("commission_percentage", 10.00)
try:
commission_percentage = float(commission_percentage)
if commission_percentage < 0 or commission_percentage > 100:
return jsonify({
"result": False,
"errors": "Commission percentage must be between 0 and 100"
}), 400
except (ValueError, TypeError):
return jsonify({
"result": False,
"errors": "Commission percentage must be a valid number"
}), 400
try:
# Make email lowercase for consistency
data["email"] = data["email"].lower()
# Check if username or email already exists
if User.query.filter(func.lower(User.username) == data["username"].lower()).first():
return jsonify({"result": False, "errors": "Username already exists"}), 400
if User.query.filter(func.lower(User.email) == data["email"].lower()).first():
return jsonify({"result": False, "errors": "Email already exists"}), 400
# CEOs can only create users in their own company
# and cannot create other CEOs
if data.get("position", "").lower() == "ceo":
return jsonify({
"result": False,
"errors": "CEOs cannot create other CEO users"
}), 400
# Create user in CEO's company
user = User(
email=data["email"],
username=data["username"],
phone=data["phone"],
name_ka=data["name_ka"],
name_en=data["name_en"],
name_ru=data["name_ru"],
surname=data["surname"],
position=data["position"],
company_id=current_user.company_id, # Always assign to CEO's company
hardcoded_id=data.get("hardcoded_id"),
payment=False, # CEOs cannot set payment status
privileged=data.get("privileged", False),
commission_percentage=commission_percentage,
)
# Set password
user.password = data["password"]
# Initialize payment dates if payment is enabled (always False for CEO creation)
# Payment status can only be changed by admin
# Update company employee count
company = db.session.get(Company, current_user.company_id)
if company:
company.number_of_employees = (company.number_of_employees or 0) + 1
db.session.add(company)
db.session.add(user)
db.session.commit()
return jsonify({
"result": True,
"data": {
"id": user.id,
"commission_percentage": float(user.commission_percentage),
"company_id": user.company_id,
"message": "User created successfully in your company"
}
}), 201
except Exception as e:
db.session.rollback()
app.logger.error(f"Error creating user: {str(e)}")
return jsonify({"result": False, "errors": str(e)}), 500
# CEO - Update User within Company
@app.route("/api/ceo/user/<int:user_id>", methods=["PUT"])
@token_required
@ceo_required
def ceo_update_user(user_id):
"""Update a user within CEO's company"""
current_user = request.current_user
# Get the user to update
user = db.session.get(User, user_id)
if not user:
return jsonify({"result": False, "errors": "User not found"}), 404
# Check if user belongs to CEO's company
if user.company_id != current_user.company_id:
return jsonify({
"result": False,
"errors": "You can only update users within your company"
}), 403
# CEOs cannot update other CEOs
if user.position and user.position.lower() == "ceo" and user.id != current_user.id:
return jsonify({
"result": False,
"errors": "CEOs cannot update other CEO users"
}), 403
data = request.json
if not data:
return jsonify({"result": False, "errors": "Invalid user data"}), 400
try:
# Handle password change
if "password" in data:
user.password = data["password"]
# Handle commission percentage update
if "commission_percentage" in data:
try:
commission_percentage = float(data["commission_percentage"])
if commission_percentage < 0 or commission_percentage > 100:
return jsonify({
"result": False,
"errors": "Commission percentage must be between 0 and 100"
}), 400
user.commission_percentage = commission_percentage
except (ValueError, TypeError):
return jsonify({
"result": False,
"errors": "Commission percentage must be a valid number"
}), 400
# Update user fields if present in request data
if "email" in data:
data["email"] = data["email"].lower()
existing_user = User.query.filter(
func.lower(User.email) == data["email"]
).first()
if existing_user and existing_user.id != user_id:
return jsonify({
"result": False,
"errors": "Email already in use by another user",
}), 400
user.email = data["email"]
if "username" in data:
existing_user = User.query.filter(
func.lower(User.username) == data["username"].lower()
).first()
if existing_user and existing_user.id != user_id:
return jsonify({
"result": False,
"errors": "Username already in use by another user",
}), 400
user.username = data["username"]
# Update other fields
updatable_fields = ["phone", "name_ka", "name_en", "name_ru", "surname", "hardcoded_id"]
for field in updatable_fields:
if field in data:
setattr(user, field, data[field])
# Handle position update (but prevent creating other CEOs)
if "position" in data:
if data["position"].lower() == "ceo" and user.id != current_user.id:
return jsonify({
"result": False,
"errors": "Cannot assign CEO position to other users"
}), 400
user.position = data["position"]
# CEOs cannot change payment status - only admin can do this
# Payment and privileged status are admin-only privileges
db.session.commit()
return jsonify({
"result": True,
"data": {
"id": user.id,
"commission_percentage": float(user.commission_percentage),
"message": "User updated successfully"
},
})
except Exception as e:
db.session.rollback()
app.logger.error(f"Error updating user: {str(e)}")
return jsonify({"result": False, "errors": str(e)}), 500
# CEO - Delete User within Company
@app.route("/api/ceo/user/<int:user_id>", methods=["DELETE"])
@token_required
@ceo_required
def ceo_delete_user(user_id):
"""Delete a user within CEO's company and all their properties"""
current_user = request.current_user
# Get the user to delete
user = db.session.get(User, user_id)
if not user:
return jsonify({"result": False, "errors": "User not found"}), 404
# Check if user belongs to CEO's company
if user.company_id != current_user.company_id:
return jsonify({
"result": False,
"errors": "You can only delete users within your company"
}), 403
# CEOs cannot delete themselves or other CEOs
if user.id == current_user.id:
return jsonify({
"result": False,
"errors": "CEOs cannot delete themselves"
}), 403
if user.position and user.position.lower() == "ceo":
return jsonify({
"result": False,
"errors": "CEOs cannot delete other CEO users"
}), 403
try:
# Store user info for response
deleted_user_info = {
"id": user.id,
"username": user.username,
"email": user.email,
"name": f"{user.name_en} {user.surname}"
}
# Delete all user's properties first
properties = Property.query.filter_by(user_id=user_id).all()
deleted_properties = len(properties)
for prop in properties:
db.session.delete(prop)
# Delete listing history for this user
listing_histories = ListingHistory.query.filter_by(user_id=user_id).all()
deleted_histories = len(listing_histories)
for history in listing_histories:
db.session.delete(history)
# Update company employee count
company = db.session.get(Company, current_user.company_id)
if company and company.number_of_employees > 0:
company.number_of_employees -= 1
db.session.add(company)
# Delete the user
db.session.delete(user)
db.session.commit()
return jsonify({
"result": True,
"data": {
"deleted_user": deleted_user_info,
"deleted_properties": deleted_properties,
"deleted_histories": deleted_histories,
"message": f"User deleted successfully. {deleted_properties} properties and {deleted_histories} history records removed."
}
})
except Exception as e:
db.session.rollback()
app.logger.error(f"Error deleting user: {str(e)}")
return jsonify({"result": False, "errors": str(e)}), 500
# User API Routes
@app.route("/api/user/<int:user_id>", methods=["GET"])
@token_required
def get_user(user_id):
"""Get user profile with names in different languages"""
try:
# Check if the requested user is the logged in user or admin
current_user = request.current_user
if current_user.id != user_id and current_user.id != 1: # User 1 is admin
return jsonify({"result": False, "errors": "Unauthorized access"}), 403
user = db.session.get(User, user_id)
if user:
return jsonify({"result": True, "data": user.to_dict()})
else:
return jsonify({"result": False, "errors": "User not found"}), 404
except Exception as e:
app.logger.error(f"Error retrieving user: {str(e)}")
return jsonify({"result": False, "errors": "Server error"}), 500
# Replace the create_user function in your main Flask app
@app.route("/api/user", methods=["POST"])
@token_required
@admin_required
def create_user():
"""Create a new user profile (admin only)"""
data = request.json
if not data:
return jsonify({"result": False, "errors": "Invalid user data"}), 400
# Validate required fields
required_fields = [
"email",
"username",
"password",
"phone",
"name_ka",
"name_en",
"name_ru",
]
missing_fields = [field for field in required_fields if field not in data]
if missing_fields:
return (
jsonify(
{
"result": False,
"errors": f"Missing required fields: {', '.join(missing_fields)}",
}
),
400,
)
# Validate commission percentage if provided
commission_percentage = data.get("commission_percentage", 10.00)
try:
commission_percentage = float(commission_percentage)
if commission_percentage < 0 or commission_percentage > 100:
return jsonify({
"result": False,
"errors": "Commission percentage must be between 0 and 100"
}), 400
except (ValueError, TypeError):
return jsonify({
"result": False,
"errors": "Commission percentage must be a valid number"
}), 400
try:
# Make email lowercase for consistency
if "email" in data:
data["email"] = data["email"].lower()
# Check if username or email already exists
if User.query.filter(
func.lower(User.username) == data["username"].lower()
).first():
return jsonify({"result": False, "errors": "Username already exists"}), 400
if User.query.filter(func.lower(User.email) == data["email"].lower()).first():
return jsonify({"result": False, "errors": "Email already exists"}), 400
# Handle company assignment
company_id = data.get("company_id")
# If company name is provided but no company_id, try to find or create the company
if not company_id and data.get("company_name"):
# First, check if a company with this name already exists
company = Company.query.filter(func.lower(Company.name) == data["company_name"].lower()).first()
if company:
# Use existing company
company_id = company.id
else:
# Create new company with the provided name
new_company = Company(
name=data["company_name"],
number_of_employees=1 # Start with 1 employee
)
db.session.add(new_company)
db.session.flush() # Get ID without committing yet
company_id = new_company.id
# If company_id is provided, verify it exists
elif company_id:
company = db.session.get(Company, company_id)
if not company:
return jsonify({"result": False, "errors": "Company not found"}), 400
# If company found and it has employees, increase employee count
if company:
company.number_of_employees = (company.number_of_employees or 0) + 1
db.session.add(company)
# Create user
user = User(
email=data["email"],
username=data["username"],
phone=data["phone"],
name_ka=data["name_ka"],
name_en=data["name_en"],
name_ru=data["name_ru"],
surname=data.get("surname"),
position=data.get("position"),
company_id=company_id,
hardcoded_id=data.get("hardcoded_id"),
payment=data.get("payment", False),
privileged=data.get("privileged", False),
commission_percentage=commission_percentage, # Add commission percentage
)
# Set password
user.password = data["password"]
# Initialize payment dates if payment is enabled
if data.get("payment", False):
current_time = datetime.utcnow()
user.last_payment_date = current_time
user.payment_expiry_date = current_time + timedelta(days=30)
# If this user should be a CEO and company exists
if data.get("position", "").lower() == "ceo" and company_id:
company = db.session.get(Company, company_id)
if company:
company.ceo_id = user.id
db.session.add(company)
db.session.add(user)
db.session.commit()
# Build response with additional info
response_data = {
"id": user.id,
"commission_percentage": float(user.commission_percentage),
"message": "User created successfully"
}
# Add company info to response if applicable
if company_id:
company = db.session.get(Company, company_id)
if company:
response_data["company"] = {
"id": company.id,
"name": company.name
}
return jsonify({"result": True, "data": response_data}), 201
except Exception as e:
db.session.rollback()
app.logger.error(f"Error creating user: {str(e)}")
return jsonify({"result": False, "errors": str(e)}), 500
# Replace the update_user function in your main Flask app
@app.route("/api/user/<int:user_id>", methods=["PUT"])
@token_required
def update_user(user_id):
"""Update an existing user profile"""
# Check if the user is updating their own profile or is an admin
current_user = request.current_user
if current_user.id != user_id and current_user.id != 1:
return (
jsonify({"result": False, "errors": "Unauthorized to update this user"}),
403,
)
user = db.session.get(User, user_id)
if not user:
return jsonify({"result": False, "errors": "User not found"}), 404
data = request.json
if not data:
return jsonify({"result": False, "errors": "Invalid user data"}), 400
try:
# Handle password change with old password verification
if "password" in data:
# Admin can change password without old password
if current_user.id != 1: # Not admin
# Require old password
if "old_password" not in data:
return (
jsonify({"result": False, "errors": "Old password is required to change password"}),
400,
)
# Verify old password
if not user.verify_password(data["old_password"]):
return (
jsonify({"result": False, "errors": "Incorrect old password"}),
401,
)
# Set the new password
user.password = data["password"]
# Handle commission percentage update
if "commission_percentage" in data:
# Only admin or the user themselves can update commission percentage
if current_user.id != 1 and current_user.id != user_id:
return jsonify({
"result": False,
"errors": "Unauthorized to update commission percentage"
}), 403
try:
commission_percentage = float(data["commission_percentage"])
if commission_percentage < 0 or commission_percentage > 100:
return jsonify({
"result": False,
"errors": "Commission percentage must be between 0 and 100"
}), 400
user.commission_percentage = commission_percentage
except (ValueError, TypeError):
return jsonify({
"result": False,
"errors": "Commission percentage must be a valid number"
}), 400
# Update user fields if present in request data
if "email" in data:
# Make email lowercase
data["email"] = data["email"].lower()
# Check if email already exists for another user
existing_user = User.query.filter(
func.lower(User.email) == data["email"]
).first()
if existing_user and existing_user.id != user_id:
return (
jsonify(
{
"result": False,
"errors": "Email already in use by another user",
}
),
400,
)
user.email = data["email"]
if "username" in data:
# Check if username already exists for another user
existing_user = User.query.filter(
func.lower(User.username) == data["username"].lower()
).first()
if existing_user and existing_user.id != user_id:
return (
jsonify(
{
"result": False,
"errors": "Username already in use by another user",
}
),
400,
)
user.username = data["username"]
if "phone" in data:
user.phone = data["phone"]
if "name_ka" in data:
user.name_ka = data["name_ka"]
if "name_en" in data:
user.name_en = data["name_en"]
if "name_ru" in data:
user.name_ru = data["name_ru"]
if "surname" in data:
user.surname = data["surname"]
if "company_name" in data:
user.company_name = data["company_name"]
if "position" in data:
user.position = data["position"]
if "company_id" in data and (
current_user.id == 1 or current_user.position == "CEO"
):
company_id = data["company_id"]
if company_id:
company = db.session.get(Company, company_id)
if not company:
return (
jsonify({"result": False, "errors": "Company not found"}),
400,
)
user.company_id = company_id
# Only allow admin to update these fields
if current_user.id == 1:
if "hardcoded_id" in data:
user.hardcoded_id = data["hardcoded_id"]
if "payment" in data:
payment_status = bool(data["payment"])
user.payment = payment_status
# Update payment dates if setting payment to True
if payment_status:
current_time = datetime.utcnow()
user.last_payment_date = current_time
user.payment_expiry_date = current_time + timedelta(days=30)
if "privileged" in data:
user.privileged = bool(data["privileged"])
db.session.commit()
return jsonify(
{
"result": True,
"data": {
"id": user.id,
"commission_percentage": float(user.commission_percentage),
"message": "User updated successfully"
},
}
)
except Exception as e:
db.session.rollback()
app.logger.error(f"Error updating user: {str(e)}")
return jsonify({"result": False, "errors": str(e)}), 500
# Add this new endpoint to your main Flask app
@app.route("/api/reports/ceo-monthly", methods=["GET"])
@token_required
def get_ceo_monthly_report():
"""Get monthly report for CEO showing employee statistics"""
current_user = request.current_user
# Check if user is a CEO
if not current_user.position or current_user.position.lower() != "ceo":
return jsonify({
"result": False,
"errors": "Access denied. Only CEOs can access this report."
}), 403
# Check if user has a company
if not current_user.company_id:
return jsonify({
"result": False,
"errors": "CEO must be associated with a company."
}), 400
try:
# Get optional month and year parameters
month = request.args.get("month")
year = request.args.get("year")
# Default to current month/year if not provided
if not month or not year:
current_date = datetime.utcnow()
month = month or current_date.month
year = year or current_date.year
# Convert to integers and validate
try:
month = int(month)
year = int(year)
if month < 1 or month > 12:
raise ValueError("Invalid month")
if year < 2000 or year > 2100:
raise ValueError("Invalid year")
except ValueError as e:
return jsonify({
"result": False,
"errors": f"Invalid month or year parameter: {str(e)}"