-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
2655 lines (2197 loc) · 111 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 models import User, Inventory, Importation, Customer, GalleryImage, Sale,Invoice,Receipt,Report,Notification
from config import app, api, db, bcrypt,limiter
from flask_restful import Resource
from flask import request, jsonify, make_response
from flask_bcrypt import check_password_hash, generate_password_hash
from schemas import InvoiceSchema, InventorySchema, UserSchema, CustomerSchema, SaleSchema, ReceiptSchema
from flask_jwt_extended import create_access_token, get_jwt_identity, jwt_required
from sqlalchemy import or_
import cloudinary
import cloudinary.uploader
import cloudinary.api
from datetime import datetime
from collections import defaultdict
import smtplib
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from io import BytesIO
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
cloudinary.config(
cloud_name='dups4sotm',
api_key='141549863151677',
api_secret='ml0oq6T67FZeXf6AFJqhhPsDfAs'
)
def send_email_with_pdf(email, subject, body, attachment=None, attachment_name=None):
smtp_server = 'smtp.gmail.com'
smtp_port = 587
sender_email = 'irungud220@gmail.com'
sender_password = 'qbpq uvgp rrqh bjky'
# Create a multipart message
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = email
msg['Subject'] = subject
# Attach the body text
msg.attach(MIMEText(body, 'plain'))
# Attach the PDF file
if attachment and attachment_name:
part = MIMEApplication(attachment, Name=attachment_name)
part['Content-Disposition'] = f'attachment; filename="{attachment_name}"'
msg.attach(part)
# Send the email
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, email, msg.as_string())
def send_email(email,subject,body):
smtp_server = 'smtp.gmail.com'
smtp_port = 587
sender_email = 'irungud220@gmail.com'
sender_password = 'qbpq uvgp rrqh bjky'
subject=subject
body=body
message = f'Subject: {subject}\n\n{body}'
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email,email,message)
def generate_pdf( invoice, customer, inventory):
buffer = BytesIO()
c = canvas.Canvas(buffer, pagesize=letter)
width, height = letter
# Logo and Business Info
logo_path = "./images/autocar.jpg" # Adjust the path to your logo
c.drawImage(logo_path, 40, height - 80, width=50, height=50)
c.setFont("Helvetica-Bold", 12)
c.drawString(100, height - 40, "Business Name")
c.setFont("Helvetica", 10)
c.drawString(100, height - 55, "Office Address")
c.drawString(100, height - 70, "By-pass, Kiambu road,")
c.drawString(100, height - 85, "Kiambu county, Kenya")
c.drawString(100, height - 100, "(+254) 123 456 7890")
# Invoice Info
c.setFont("Helvetica-Bold", 16)
c.setFillColorRGB(0, 0, 1) # Blue color
c.drawString(width - 200, height - 40, "INVOICE")
c.setFont("Helvetica", 10)
c.setFillColorRGB(0, 0, 0) # Reset to black
c.drawString(width - 200, height - 55, f"Date: {invoice.date_of_purchase.strftime('%Y-%m-%d') if isinstance(invoice.date_of_purchase, datetime) else invoice.date_of_purchase}")
c.drawString(width - 200, height - 70, f"To: {customer.first_name} {customer.last_name}")
c.drawString(width - 200, height - 85, f"Address: {customer.address}")
c.drawString(width - 200, height - 100, f"Email: {customer.email}")
# Table Headers
table_top = height - 130
c.setFont("Helvetica-Bold", 10)
c.drawString(50, table_top, "Car Description")
c.drawString(200, table_top, "Total cost")
c.drawString(300, table_top, "Amount paid")
c.drawString(400, table_top, "Balance")
c.drawString(500, table_top, "Total")
# Table Content
table_top -= 20
c.setFont("Helvetica", 10)
c.drawString(50, table_top, f"{inventory.make} {inventory.model} {inventory.year}")
c.drawString(200, table_top, f"{invoice.currency} {invoice.total_amount}")
c.drawString(300, table_top, f"{invoice.currency} {invoice.amount_paid:.2f}")
c.drawString(400, table_top, f"{invoice.currency} {invoice.balance}")
c.drawString(500, table_top, f"{invoice.currency} {invoice.amount_paid:.2f}")
# Tax and Thanks Note
table_top -= 40
c.setFont("Helvetica", 10)
c.drawString(400, table_top, f"Tax (15%): {invoice.currency} {invoice.tax:.2f}")
# Footer
footer_top = 80
c.setFillColorRGB(0.9, 0.9, 1) # Light blue background
c.rect(30, footer_top - 30, width - 60, 40, fill=True, stroke=False)
c.setFillColorRGB(0, 0, 0) # Reset to black
c.setFont("Helvetica", 10)
c.drawString(50, footer_top, "Thank you for your business")
c.drawString(50, footer_top - 15, "Questions? Email us at support@businessname.com")
c.showPage()
c.save()
buffer.seek(0)
return buffer.getvalue()
class CheckSession(Resource):
@jwt_required()
def get(self):
user_id = get_jwt_identity()
user = User.query.filter_by(id=user_id).first()
if not user:
return {"message": "user not found"}
user_data = {
"user_id": user.id,
"first_name": user.first_name,
"last_name": user.last_name,
"user_email": user.email,
"contact": user.contact,
"role": user.role,
"image": user.image,
"status":user.status
}
return make_response(jsonify(user_data), 200)
class Login(Resource):
decorators = [limiter.limit("3 per minute")]
def post(self):
email = request.json.get("email")
password = request.json.get("password")
if not email or not password:
return make_response(jsonify({"msg": "Bad Email or password"}), 401)
user = User.query.filter_by(email=email).first()
if not user:
return make_response(jsonify({"msg": "Wrong credentials"}), 401)
if check_password_hash(user._password_hash, password):
access_token = create_access_token(identity=user.id)
# remember to uncomment this code
send_email(email=email,subject='Login Successful', body='You have been logged in your account successfully')
user.status="active"
db.session.commit()
return make_response(jsonify(access_token=access_token), 200)
return make_response(jsonify({"message": "Wrong password"}), 406)
class SignupUser(Resource):
decorators = [limiter.limit("5 per minute")]
@jwt_required()
def post(self):
user_id = get_jwt_identity()
check_user_role = User.query.filter_by(id=user_id).first()
if check_user_role.role not in ['admin', 'super admin'] and check_user_role.status == 'active':
return make_response(jsonify({'message': 'Unauthorized'}), 401)
data = request.form
first_name = data.get('first_name')
last_name = data.get('last_name')
image_file = request.files.get('image')
contact = data.get('contact')
email = data.get('email')
status = "inactive"
role = data.get('role') if check_user_role.role == 'super admin' else 'seller'
password = '8Dn@3pQo'
# print(image_file)
if not all([first_name, last_name, email, contact, role]) or not image_file:
return make_response(jsonify({'errors': ['Missing required data']}), 406)
if User.query.filter_by(email=email).first() or User.query.filter_by(contact=contact).first():
return make_response(jsonify({'message': 'User already exists'}), 400)
if image_file.filename == '':
return {'error': 'No image selected for upload'}, 400
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg', 'gif', 'webp'}
if not allowed_file(image_file.filename):
return {'error': 'Invalid file type. Only images are allowed'}, 400
# Upload image to Cloudinary
try:
image_upload_result = cloudinary.uploader.upload(image_file)
except Exception as e:
return {'error': f'Error uploading image: {str(e)}'}, 500
new_user = User(
first_name=first_name,
last_name=last_name,
image=image_upload_result['secure_url'],
email=email,
contact=contact,
status=status,
role=role,
_password_hash=bcrypt.generate_password_hash(password).decode('utf-8')
)
db.session.add(new_user)
db.session.commit()
# Send email here (assuming you have a function defined for this)
send_email(
email=email,
subject='You have been signed up',
body=f'You have been signed up to our car dealership management system. Use this password to login into your account PASSWORD: {password} EMAIL: {email}'
)
notification=Notification(
user_id=user_id,
message=f'{first_name} {last_name} added to the system successfully',
notification_type='Sign up'
)
db.session.add(notification)
db.session.commit()
return make_response(jsonify({'message': 'Sign up successful'}), 200)
class UpdatePassword(Resource):
decorators = [limiter.limit("5 per minute")]
def post(self):
data = request.json
user_email = data.get('email')
former_password = data.get('former_password')
new_password = data.get('new_password')
if not user_email or not former_password or not new_password:
return make_response(jsonify({'message': 'Email, former password, and new password are required.'}), 400)
user = User.query.filter_by(email=user_email).first()
if user is None:
return make_response(jsonify({'message': 'User not found'}), 404)
if not check_password_hash(user.password_hash, former_password):
return make_response(jsonify({'message': 'Incorrect former password'}), 401)
# Update the password hash with the new one
user.password_hash = generate_password_hash(
new_password).decode('utf-8')
db.session.commit()
send_email(email=user_email, subject='Password Updates', body='Password updated successfully')
return make_response(jsonify({'message': 'Password updated successfully'}), 200)
# in this class we are getting all the users and serializering each user using list comprehension
class AllUsers(Resource):
# decorators = [limiter.limit("5 per minute")]
@jwt_required()
def get(self):
user_id = get_jwt_identity()
check_user_role = User.query.filter_by(id=user_id).first()
user = [] # Define user as an empty list by default
if check_user_role.role == "admin" and check_user_role.status == "active":
user = [{
'id': n.id,
'first_name': n.first_name,
'last_name': n.last_name,
'email': n.email,
'contact': n.contact,
'status': n.status
} for n in User.query.filter_by(role='seller').all()]
elif check_user_role.role == "super admin" and check_user_role.status == "active":
user = [{
'id': n.id,
'first_name': n.first_name,
'last_name': n.last_name,
'email': n.email,
'role': n.role,
'contact': n.contact,
'status': n.status
} for n in User.query.all()]
return make_response(jsonify(user), 200)
# in this function we are getting a specific user by their id
class OneUser(Resource):
decorators = [limiter.limit("10 per minute")]
@jwt_required()
def get(self, id):
user_id = get_jwt_identity()
check_user_role = User.query.filter_by(id=user_id).first()
if check_user_role.role == "admin" and check_user_role.status == "active" :
user = User.query.filter_by(id=id, role='seller').first()
elif check_user_role.role == "super admin" and check_user_role.status == "active":
user = User.query.filter_by(id=id).first()
elif check_user_role.role == "seller" and check_user_role.status == "active":
user = User.query.filter_by(id=user_id, role='seller').first()
else:
return make_response(jsonify({"message": "Un Authorized User"}), 401)
# if user:
# user = User.query.filter_by(id=id, role='seller').first()
if not user:
return {"message": "No user found"}
sales = Sale.query.filter_by(seller_id=user.id).all()
number_of_sales = len(sales)
total_commission = sum(sale.commision for sale in sales)
user_data = {
'id': user.id,
'first_name': user.first_name,
'last_name': user.last_name,
'image': user.image,
'email': user.email,
'role': user.role,
'contact': user.contact,
"sales":
[{
"id": sale.id,
"commision": sale.commision,
"status": sale.status,
"history": sale.history,
"discount": sale.discount,
"sale_date": sale.sale_date,
'status':sale.status,
"promotions": sale.promotions,
} for sale in sales], # Using enumerate to count sales starting from 1
"number_of_sales":number_of_sales,
"total_commission": total_commission
}
response = make_response(jsonify(user_data), 200)
return response
decorators = [limiter.limit("5 per minute")]
@jwt_required()
def put(self, id):
user_id = get_jwt_identity()
check_user_role = User.query.filter_by(id=user_id).first()
# Get the JSON data from the request
data = request.form
# Querying the user by their id
if check_user_role.role == 'super admin' and check_user_role.status == "active":
user = User.query.filter_by(id=id).first()
elif check_user_role.role == 'admin' and check_user_role.status == "active":
user = User.query.filter_by(id=id, role='seller').first()
else:
return make_response(jsonify({"message": "Unauthorized User"}), 401)
# If no user is found, return an error response
if not user:
return make_response(jsonify({"message": "No user to update"}), 401)
if check_user_role.role == "super admin":
# Update user attributes if they are provided in the JSON data
if 'first_name' in data:
user.first_name = data.get('first_name')
if 'last_name' in data:
user.last_name = data.get('last_name')
if 'image' in data:
image = request.files.get('image')
if image.filename == '':
return {'error': 'No image selected for upload'}, 400
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg', 'gif'}
if not allowed_file(image.filename):
return {'error': 'Invalid file type. Only images are allowed'}, 400
# Upload image to Cloudinary
try:
image_upload_result = cloudinary.uploader.upload(image)
user.image = image_upload_result['secure_url']
except Exception as e:
return {'error': f'Error uploading image: {str(e)}'}, 500
if 'email' in data:
user.email = data.get('email')
if 'contact' in data:
user.contact = data.get('contact')
if 'role' in data:
user.role = data.get('role')
# Commit the changes to the database
db.session.commit()
# Return a success response
return make_response(jsonify({'message': 'User updated successfully'}), 200)
if check_user_role.role == "admin" and check_user_role.status == "active" or check_user_role.role == "seller" and check_user_role.status == "active":
# Update user attributes if they are provided in the JSON data
if 'first_name' in data:
user.first_name = data.get('first_name')
if 'last_name' in data:
user.last_name = data.get('last_name')
if 'image' in data:
image = request.files.get('image')
if image.filename == '':
return {'error': 'No image selected for upload'}, 400
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg', 'gif'}
if not allowed_file(image.filename):
return {'error': 'Invalid file type. Only images are allowed'}, 400
# Upload image to Cloudinary
try:
image_upload_result = cloudinary.uploader.upload(image)
user.image = image_upload_result['secure_url']
except Exception as e:
return {'error': f'Error uploading image: {str(e)}'}, 500
if 'email' in data:
user.email = data.get('email')
if check_user_role.role == "admin":
if 'role' in data:
user.role = data.get('role')
if 'contact' in data:
user.contact = data.get('contact')
# Commit the changes to the database
db.session.commit()
# Return a success response
return make_response(jsonify({'message': 'User updated successfully'}), 200)
else:
return make_response(jsonify({'message': 'Unauthorized'}), 401)
class INVENTORY(Resource):
# decorators = [limiter.limit("5 per minute")]
@jwt_required()
def post(self):
user_id = get_jwt_identity()
check_user_role = User.query.filter_by(id=user_id).first()
# Ensure the user has the correct role to create inventory
if check_user_role.role != 'super admin': # or whatever role is required
return make_response(jsonify({'message': 'User has no access rights to create a Car'}), 401)
data = request.form
image = request.files.get('image')
# import_document = request.files.get('import_document')
gallery = request.files.getlist('gallery_images')
if image is None or image.filename == '':
return {'error': 'No image selected for upload'}, 400
if not all(g.filename for g in gallery):
return {'error': 'One or more gallery images are not selected for upload'}, 400
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg', 'gif', 'webp'}
if not allowed_file(image.filename) or not all(allowed_file(g.filename) for g in gallery) :
return {'error': 'One or more files have unsupported file types'}, 400
try:
image_upload_result = cloudinary.uploader.upload(image)
gallery_upload_results = [cloudinary.uploader.upload(g) for g in gallery]
# import_document_result = cloudinary.uploader.upload(import_document)
except Exception as e:
return {'error': f'Error uploading files: {str(e)}'}, 500
try:
price = float(data.get('price'))
purchase_cost = float(data.get('purchase_cost'))
profit = price - purchase_cost
# Create the inventory item
new_inventory_item = Inventory(
make=data.get('make'),
image=image_upload_result['secure_url'],
price=price,
currency=data.get('currency'),
model=data.get('model'),
year=data.get('year'),
VIN=data.get('VIN'),
color=data.get('color'),
mileage=data.get('mileage'),
body_style=data.get('body_style'),
transmission=data.get('transmission'),
fuel_type=data.get('fuel_type'),
engine_size=data.get('engine_size'),
drive_type=data.get('drive_type'),
trim_level=data.get('trim_level'),
condition=data.get('condition'),
availability=data.get('availability'),
cylinder=data.get('cylinder'),
doors=data.get('doors'),
features=data.get('features'),
stock_number=data.get('stock_number'),
purchase_cost=purchase_cost,
profit=profit,
user_id=user_id
)
db.session.add(new_inventory_item)
db.session.commit()
db.session.refresh(new_inventory_item)
# Create gallery images
for result in gallery_upload_results:
gallery_image = GalleryImage(
url=result['secure_url'], inventory_id=new_inventory_item.id)
db.session.add(gallery_image)
# Create importation record
transport = float(data.get('transport_fee'))
duty = float(data.get('import_duty'))
new_importation = Importation(
country_of_origin=data.get('country_of_origin'),
transport_fee=transport,
currency=data.get('currency'),
import_duty=duty,
# import_document=import_document_result['secure_url'],
car_id=new_inventory_item.id,
expense=transport + duty
)
db.session.add(new_importation)
db.session.commit()
notification=Notification(
user_id=user_id,
message=f'Car Details added to the system successfully',
notification_type='Inventory adittion'
)
db.session.add(notification)
db.session.commit()
return make_response(jsonify({'message': 'Inventory and importation created successfully'}), 201)
except Exception as e:
db.session.rollback()
return {'error': f'Error creating inventory: {str(e)}'}, 500
# @jwt_required()
# decorators = [limiter.limit("5 per minute")]
def get(self):
items = Inventory.query.all()
response_data = [{
'id': item.id,
'make': item.make,
'image': item.image,
'price': item.price,
'currency': item.currency,
'model': item.model,
'year': item.year,
'VIN': item.VIN,
'color': item.color,
'mileage': item.mileage,
'body_style': item.body_style,
'transmission': item.transmission,
'fuel_type': item.fuel_type,
'engine_size': item.engine_size,
'drive_type': item.drive_type,
'trim_level': item.trim_level,
'gallery': [gallery.url for gallery in item.gallery],
'condition': item.condition,
'availability': item.availability,
'cylinder': item.cylinder,
'doors': item.doors,
'features': item.features,
'stock_number': item.stock_number,
'purchase_cost': item.purchase_cost,
'profit': item.profit
} for item in items]
return jsonify(response_data)
# continue the README from here
class inventory_update(Resource):
decorators = [limiter.limit("5 per minute")]
@jwt_required()
def put(self, id):
user_id = get_jwt_identity()
check_user_role = User.query.filter_by(id=user_id).first()
inventory_item = Inventory.query.filter_by(id=id).first()
if not inventory_item:
return {'message': 'Inventory item not found'}, 404
if check_user_role.role == 'admin' and check_user_role.status == "active" or check_user_role.role == 'super admin' and check_user_role.status == "active":
data = request.form
# Handle gallery images
gallery_images = request.files.getlist('gallery')
for image in gallery_images:
try:
image_upload_result = cloudinary.uploader.upload(image)
gallery_image = GalleryImage(
url=image_upload_result['secure_url'], inventory_id=id)
db.session.add(gallery_image)
except Exception as e:
return {'error': f'Error uploading gallery image: {str(e)}'}, 500
for key, value in data.items():
if hasattr(inventory_item, key):
setattr(inventory_item, key, value)
db.session.commit()
return {'message': 'Inventory item updated successfully'}, 200
else:
return {'message': 'User has no access rights to update Inventory'}, 422
@jwt_required()
def delete(self, id):
user_id = get_jwt_identity()
check_user_role = User.query.filter_by(id=user_id).first()
if check_user_role.role == 'super admin' and check_user_role.status == "active" or check_user_role.role == 'admin' and check_user_role.status == "active":
gallery = GalleryImage.query.filter_by(inventory_id=id).all()
for image in gallery:
db.session.delete(image)
inventory_item = Inventory.query.filter_by(id=id).first()
if inventory_item:
# db.session.delete(inventory_item)
db.session.commit()
return {'message': 'Inventory item deleted successfully'}, 200
else:
return {'message': 'User has no access rights to delete'}, 422
return {'message': "Inventory item not found"}, 404
class Importations(Resource):
@jwt_required()
def get(self):
user_id = get_jwt_identity()
check_user_role = User.query.filter_by(id=user_id).first()
if check_user_role.role == 'super admin' and check_user_role.status == "active" or check_user_role.role == 'admin' and check_user_role.status == "active" or check_user_role.role == 'seller' and check_user_role.status == "active":
importations = Importation.query.all()
importations_data = []
for importation in importations:
importations_data.append({
'id': importation.id,
'country_of_origin': importation.country_of_origin,
'transport_fee': importation.transport_fee,
'currency': importation.currency,
'import_duty': importation.import_duty,
'import_date': importation.import_date,
'import_document': importation.import_document,
'car': [
{
"id": car.id,
"make": car.make,
"model": car.model,
"image": car.image,
"year": car.year,
"currency": car.currency,
"purchase_cost": car.purchase_cost
} for car in Inventory.query.filter_by(id=importation.car_id).all()
]
})
return make_response(jsonify(importations_data), 200)
else:
return make_response(jsonify({"message": "Unauthorized User"}), 401)
@jwt_required()
def post(self):
user_id = get_jwt_identity()
check_user_role = User.query.filter_by(id=user_id).first()
if check_user_role.role == 'super admin' and check_user_role.status == "active" or check_user_role.role == 'admin' and check_user_role.status == "active":
# Get form data and uploaded file
data = request.form
import_document = request.files.get('import_document')
# Check if all required fields are present
required_fields = ['country_of_origin', 'transport_fee', 'currency', 'import_duty', 'import_date', 'car_id']
missing_fields = [field for field in required_fields if field not in data]
if missing_fields:
return make_response(jsonify({"error": f"Missing required fields: {', '.join(missing_fields)}"}), 400)
if import_document is None or import_document.filename == '':
return {'error': 'No document selected for upload'}, 400
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'doc', 'docx', 'txt'}
if not allowed_file(import_document.filename):
return {'error': 'Invalid file type. Only images are allowed'}, 400
# Upload document to Cloudinary
try:
document_upload_result = cloudinary.uploader.upload(import_document)
except Exception as e:
return {'error': f'Error uploading document: {str(e)}'}, 500
# Create new Importation object
new_importation = Importation(
country_of_origin=data['country_of_origin'],
transport_fee=data['transport_fee'],
currency=data['currency'],
import_duty=data['import_duty'],
import_date=data['import_date'],
import_document=document_upload_result['secure_url'],
car_id=data['car_id']
)
# Add and commit to database
db.session.add(new_importation)
db.session.commit()
return make_response(jsonify({'message': 'Importation created successfully'}), 201)
else:
return make_response(jsonify({"message": "Unauthorized User"}), 404)
class UpdateImportation(Resource):
@jwt_required()
def put(self, importation_id):
user_id = get_jwt_identity()
check_user_role = User.query.filter_by(id=user_id).first()
if check_user_role.role == 'super admin' and check_user_role.status == "active" or check_user_role.role == 'admin' and check_user_role.status == "active":
data = request.form
importation = Importation.query.get(importation_id)
doc = request.files.get(
'import_document', importation.import_document)
if doc.filename == '':
return {'error': 'No image selected for upload'}, 400
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'doc', 'docx', 'txt'}
if not allowed_file(doc.filename):
return {'error': 'Invalid file type. Only images are allowed'}, 400
# Upload image to Cloudinary
try:
image_upload_result = cloudinary.uploader.upload(doc)
importation.import_document = image_upload_result['secure_url']
except Exception as e:
return {'error': f'Error uploading document: {str(e)}'}, 500
if not importation:
return make_response(jsonify({'message': 'Importation not found'}), 404)
importation.country_of_origin = data.get(
'country_of_origin', importation.country_of_origin)
importation.transport_fee = data.get(
'transport_fee', importation.transport_fee)
importation.currency = data.get('currency', importation.currency)
importation.import_duty = data.get(
'import_duty', importation.import_duty)
importation.import_date = data.get(
'import_date', importation.import_date)
# importation.import_document = image_upload_result
importation.car_id = data.get('car_id', importation.car_id)
db.session.commit()
return make_response(jsonify({'message': 'Importation updated successfully'}), 200)
else:
return make_response(jsonify({"message": "Unauthorized User"}), 404)
@jwt_required()
def delete(self, importation_id):
user_id = get_jwt_identity()
check_user_role = User.query.filter_by(id=user_id).first()
if check_user_role.role == 'super admin' and check_user_role.status == "active" or check_user_role.role == 'admin' and check_user_role.status == "active":
importation = Importation.query.get(importation_id)
if not importation:
return make_response(jsonify({'message': 'Importation not found'}), 404)
db.session.delete(importation)
db.session.commit()
return make_response(jsonify({'message': 'Importation deleted successfully'}), 200)
else:
return make_response(jsonify({"message": "Unauthorized User"}), 404)
class DetailCustomer(Resource):
decorators = [limiter.limit("5 per minute")]
@jwt_required()
def get(self):
# Get the current user's ID from the JWT token
user_id = get_jwt_identity()
check_user_role = User.query.filter_by(id=user_id).first()
# Retrieve only the customers associated with the current seller (user)
if check_user_role.role == 'seller' and check_user_role.status == "active" :
customers = Customer.query.filter_by(seller_id=user_id).all()
# Check if customers exist
if not customers:
return make_response(jsonify({'message': 'No customers found for this seller'}), 404)
# Serialize customer data
serialized_customers = [{
"id":customer.id,
"first_name": customer.first_name,
'last_name': customer.last_name,
'email': customer.email,
'address': customer.address,
'phone_number': customer.phone_number,
'image_file': customer.image
} for customer in customers]
return make_response(jsonify(serialized_customers), 200)
class Customers(Resource):
decorators = [limiter.limit("5 per minute")]
@jwt_required()
def get(self):
# Get the current user's ID from the JWT token
user_id = get_jwt_identity()
check_user_role = User.query.filter_by(id=user_id).first()
# Retrieve only the customers associated with the current seller (user)
if check_user_role.role == 'seller' and check_user_role.status == "active" :
# Retrieve only the customers associated with the current seller (user)
customers = Customer.query.filter_by(seller_id=user_id).all()
# Check if customers exist
if not customers:
return make_response(jsonify({'message': 'No customers found for this seller'}), 404)
# Serialize customer data
serialized_customers = [{
"id":customer.id,
"first_name": customer.first_name,
'last_name': customer.last_name,
'email': customer.email,
'address': customer.address,
'phone_number': customer.phone_number,
'image_file': customer.image
} for customer in customers]
return make_response(jsonify(serialized_customers), 200)
elif check_user_role.role == 'super admin' and check_user_role.status == "active" or check_user_role.role == 'admin' and check_user_role.status == "active" :
# Retrieve only the customers associated with the current seller (user)
customers = Customer.query.all()
# Check if customers exist
if not customers:
return make_response(jsonify({'message': 'No customers found for this seller'}), 404)
# Serialize customer data
serialized_customers = [{
"id":customer.id,
"first_name": customer.first_name,
'last_name': customer.last_name,
'email': customer.email,
'address': customer.address,
'phone_number': customer.phone_number,
'image_file': customer.image
} for customer in customers]
return make_response(jsonify(serialized_customers), 200)
else:
return make_response(jsonify({'message':"User unauthorized"}), 422)
decorators = [limiter.limit("5 per minute")]
@jwt_required() # Require JWT authentication
def post(self):
user_id = get_jwt_identity()
check_user_role = User.query.filter_by(id=user_id).first()
# Retrieve only the customers associated with the current seller (user)
if check_user_role.role == 'seller' and check_user_role.status == "active" :
data = request.form
first_name = data.get('first_name')
last_name = data.get('last_name')
email = data.get('email')
address = data.get('address')
phone_number = data.get('contact')
image_file = request.files.get('image')
if not all([first_name, last_name, email, address, phone_number, image_file]):
return {'error': '422 Unprocessable Entity', 'message': 'Missing customer details'}, 422
# Get the current user's ID from the JWT token
current_user_id = get_jwt_identity()
# Retrieve the user object from the database
user = User.query.filter_by(id=current_user_id).first()
# Check if the user exists and has the role "seller"
if not user or user.role != "seller":
return {'error': '403 Forbidden', 'message': 'User is not authorized to add customer details'}, 403
# Check if file uploaded and is an image
if image_file.filename == '':
return {'error': 'No image selected for upload'}, 400
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg', 'gif' ,'webp'}
if not allowed_file(image_file.filename):
return {'error': 'Invalid file type. Only images are allowed'}, 400
# Upload image to Cloudinary
try:
image_upload_result = cloudinary.uploader.upload(image_file)
except Exception as e:
return {'error': f'Error uploading image: {str(e)}'}, 500
# Create a new customer object
new_customer = Customer(
first_name=first_name,
last_name=last_name,
email=email,
address=address,
phone_number=phone_number,
# Store Cloudinary URL
image=image_upload_result['secure_url'],
created_at=datetime.now(),
seller_id=user_id # Assign the current user ID as the seller ID
)
# in the inventory the stock number should be generated in the backend
db.session.add(new_customer)
db.session.commit()
notification=Notification(
user_id=user_id,
message=f'{first_name} {last_name} added to the system successfully',
notification_type='Customer Adittion'
)
db.session.add(notification)
db.session.commit()
send_email(email=email,subject="Customer Registration",body="Your Information has been recorded Successful and Safe.Thank You and wlcome again")
return {'message': 'Customer details added successfully'}, 201
class UpdateDetails(Resource):
decorators = [limiter.limit("5 per minute")]
@jwt_required()
def put(self, customer_id):
# Get the current user's identity
current_user_id = get_jwt_identity()