-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
2707 lines (2249 loc) · 99.1 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
import re
import secrets
from flask import Flask, render_template, request, jsonify, send_file, make_response
from pymongo import MongoClient, ASCENDING, DESCENDING
import os
from os.path import join, dirname
from dotenv import load_dotenv
import jwt
from datetime import datetime, timedelta
from werkzeug.utils import secure_filename
from bson import ObjectId
from flask_bcrypt import Bcrypt
from pagination import *
from exceptions import HttpException, handle_http_exception
from apiresponse import api_response
from utils import *
from middlewares import *
from flask_socketio import SocketIO, Namespace
import pandas as pd
from io import BytesIO
from flasgger import Swagger, swag_from
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
app = Flask(__name__)
# Register the error handler
app.errorhandler(HttpException)(handle_http_exception)
bcrypt = Bcrypt(app)
socketio = SocketIO(app)
# Swagger Configuration
app.config['SWAGGER'] = {
'title': 'Klinik Google',
'description': 'API documentation for klinik google, API ini menggunakan JWT untuk autentikasi dan otorisasi',
'version': '1.0.0',
}
Swagger(app)
MONGODB_CONNECTION_STRING = os.environ.get("MONGODB_CONNECTION_STRING")
if not MONGODB_CONNECTION_STRING:
raise ValueError(
"MONGODB_CONNECTION_STRING environment variable is not set")
DB_NAME = os.environ.get("DB_NAME")
if not DB_NAME:
raise ValueError("DB_NAME environment variable is not set")
client = MongoClient(MONGODB_CONNECTION_STRING)
db = client[DB_NAME]
TOKEN_KEY = os.environ.get("TOKEN_KEY")
if not TOKEN_KEY:
raise ValueError("TOKEN_KEY environment variable is not set")
SECRET_KEY = os.environ.get("SECRET_KEY")
if not SECRET_KEY:
raise ValueError("SECRET_KEY environment variable is not set")
class PendaftaranNamespace(Namespace):
"""
A namespace for handling pendaftaran events.
This class extends the `Namespace` class and provides methods for handling
client connection, disconnection, and new pendaftaran events.
Attributes:
None
Methods:
on_connect: Called when a client connects to the namespace.
on_disconnect: Called when a client disconnects from the namespace.
on_new_pendaftaran: Called when a new pendaftaran event is received.
"""
def on_connect(self):
print('Client connected')
def on_disconnect(self):
print('Client disconnected')
def on_new_pendaftaran(self, data):
self.emit('new_pendaftaran', data)
class AntrianNamespace(Namespace):
"""
A namespace class for handling antrian events.
This class extends the `Namespace` class from the `socketio` library.
It provides methods for handling client connections, disconnections,
and new antrian events.
Attributes:
None
Methods:
on_connect: Handles the client connection event.
on_disconnect: Handles the client disconnection event.
on_new_antrian: Handles the new antrian event.
"""
def on_connect(self):
print('Client connected')
def on_disconnect(self):
print('Client disconnected')
def on_new_antrian(self, data):
self.emit('new_antrian', data)
class JadwalNamespace(Namespace):
"""
A namespace class for handling Jadwal events.
This class extends the `Namespace` class and provides methods for handling
client connections, disconnections, and new Jadwal events.
Attributes:
None
Methods:
on_connect: Called when a client connects to the namespace.
on_disconnect: Called when a client disconnects from the namespace.
on_new_jadwal: Called when a new Jadwal event is received.
"""
def on_connect(self):
print('Client connected')
def on_disconnect(self):
print('Client disconnected')
def on_new_jadwal(self, data):
self.emit('new_jadwal', data)
# Register the namespace
socketio.on_namespace(PendaftaranNamespace('/pendaftaran'))
socketio.on_namespace(AntrianNamespace('/antrian'))
socketio.on_namespace(JadwalNamespace('/jadwal'))
#################### TEMPLATE ROUTES ####################
# Return Home Page
@app.route('/')
@validate_token_template(SECRET_KEY, TOKEN_KEY, db, allow_guest=True)
def home(decoded_token):
"""
Renders the home page.
Args:
decoded_token (dict): The decoded token containing user information.
Returns:
str: The rendered HTML page.
"""
msg = request.args.get('msg')
scripts = ['js/index.js']
css = ['css/index.css']
if decoded_token:
user_id = ObjectId(decoded_token.get("uid"))
user_info = db.users.find_one({"_id": user_id}, {
'_id': False, 'password': False})
return render_template('pages/index.html', user_info=user_info, active_page='home', scripts=scripts, css=css, msg=msg)
else:
return render_template('pages/index.html', active_page='home', scripts=scripts, css=css, msg=msg)
# Return Login Page
@app.route('/login')
def login():
"""
Renders the login page with optional message, JavaScript scripts, and CSS styles.
Args:
msg (str): Optional message to display on the login page.
Returns:
str: Rendered HTML template of the login page.
"""
msg = request.args.get('msg')
scripts = ['js/login.js']
css = ['css/login.css']
return render_template('pages/login.html', msg=msg, scripts=scripts, css=css)
# Return Register Page
@app.route("/register")
def register():
"""
Renders the register.html template with the necessary scripts and CSS files.
Returns:
The rendered register.html template with the scripts and CSS files.
"""
scripts = ['js/register.js']
css = ['css/register.css']
return render_template("pages/register.html", scripts=scripts, css=css)
# Return Pendaftaran Pasien Page (GET)
@app.route('/pendaftaran')
@validate_token_template(SECRET_KEY, TOKEN_KEY, db)
@authorized_roles_template(["pasien"])
def pendaftaran_get(decoded_token):
"""
Handle GET request for '/pendaftaran' route.
Args:
decoded_token (dict): Decoded token containing user information.
Returns:
Response: Rendered template 'pages/pendaftaran.html' with user_info and scripts.
"""
scripts = ['js/pendaftaran.js']
user_id = ObjectId(decoded_token.get("uid"))
user_info = db.users.find_one({"_id": user_id}, {
'_id': False, 'password': False})
return render_template('pages/pendaftaran.html', user_info=user_info, active_page='pendaftaran', scripts=scripts)
# Return Riwayat Pendaftaran Page
@app.route("/riwayat_pendaftaran")
@validate_token_template(SECRET_KEY, TOKEN_KEY, db)
@authorized_roles_template(["pasien"])
def riwayat_pendaftaran(decoded_token):
"""
This function handles the route '/riwayat_pendaftaran' and is accessible only to authorized 'pasien' role users.
Parameters:
decoded_token (dict): The decoded token containing user information.
Returns:
render_template: The rendered HTML template 'pages/riwayat_pendaftaran.html' with user_info and scripts as parameters.
"""
scripts = ['js/riwayat_pendaftaran.js']
user_id = ObjectId(decoded_token.get("uid"))
user_info = db.users.find_one({"_id": user_id}, {
'_id': False, 'password': False})
return render_template("pages/riwayat_pendaftaran.html", user_info=user_info, active_page='riwayat_pendaftaran', scripts=scripts)
# Return Riwayat Checkup Page
@app.route("/riwayat_checkup")
@validate_token_template(SECRET_KEY, TOKEN_KEY, db)
@authorized_roles_template(["pasien"])
def riwayat_checkup(decoded_token):
"""
This function handles the '/riwayat_checkup' route.
It requires a valid token with 'pasien' role to access.
It retrieves the user's information from the database based on the decoded token.
Then, it renders the 'riwayat_checkup.html' template with the user's information and necessary scripts.
"""
scripts = ['js/riwayat_checkup.js']
user_id = ObjectId(decoded_token.get("uid"))
user_info = db.users.find_one({"_id": user_id}, {
'_id': False, 'password': False})
return render_template("pages/riwayat_checkup.html", user_info=user_info, active_page='riwayat_checkup', scripts=scripts)
# Return Profile Page
@app.route("/profile")
@validate_token_template(SECRET_KEY, TOKEN_KEY, db)
def profile(decoded_token):
"""
Renders the profile page with user information.
Args:
decoded_token (dict): Decoded user token.
Returns:
render_template: Rendered profile page with user information.
"""
scripts = ['js/profile.js']
css = ['css/profile.css']
user_id = ObjectId(decoded_token.get("uid"))
user_info = db.users.find_one({"_id": user_id}, {
'_id': False, 'password': False})
if is_valid_date(user_info.get('tgl_lahir')):
user_info['tgl_lahir'] = datetime.strptime(
user_info.get('tgl_lahir'), '%d-%m-%Y').strftime('%Y-%m-%d')
return render_template('pages/profile.html', user_info=user_info, active_page='profile', scripts=scripts, css=css)
# Return Kelola Pendaftaran Page
@app.route("/kelola_pendaftaran")
@validate_token_template(SECRET_KEY, TOKEN_KEY, db)
@authorized_roles_template(["pegawai"])
def kelola_pendaftaran(decoded_token):
"""
Renders the 'kelola_pendaftaran.html' template and passes the user_info and scripts to it.
Args:
decoded_token (dict): The decoded token containing user information.
Returns:
render_template: The rendered template with user_info and scripts passed as parameters.
"""
scripts = ['js/kelola_pendaftaran.js']
user_id = ObjectId(decoded_token.get("uid"))
user_info = db.users.find_one({"_id": user_id}, {
'_id': False, 'password': False})
return render_template('pages/kelola_pendaftaran.html', user_info=user_info, active_page='kelola_pendaftaran', scripts=scripts)
# Return Dashboard Page
@app.route("/dashboard")
@validate_token_template(SECRET_KEY, TOKEN_KEY, db)
@authorized_roles_template(["pegawai"])
def dashboard(decoded_token):
"""
Renders the dashboard page with user information.
Parameters:
- decoded_token (dict): Decoded token containing user information.
Returns:
- rendered template: The rendered template of the dashboard page.
"""
scripts = ['js/dashboard.js']
user_id = ObjectId(decoded_token.get("uid"))
user_info = db.users.find_one({"_id": user_id}, {
'_id': False, 'password': False})
return render_template("pages/dashboard.html", user_info=user_info, active_page='dashboard', scripts=scripts)
# Return Rekam Medis Page
@app.route("/rekam_medis")
@validate_token_template(SECRET_KEY, TOKEN_KEY, db)
@authorized_roles_template(["pegawai"])
def get_rekam_medis(decoded_token):
"""
Retrieves the medical records for a user.
Parameters:
- decoded_token (dict): The decoded token containing user information.
Returns:
- render_template: The rendered HTML template for displaying the medical records page.
"""
scripts = ['js/rekam_medis.js']
user_id = ObjectId(decoded_token.get("uid"))
user_info = db.users.find_one({"_id": user_id}, {
'_id': False, 'password': False})
return render_template("pages/rekam_medis.html", user_info=user_info, active_page='rekam_medis', scripts=scripts)
# Return Kelola Jadwal Page
@app.route('/kelola_praktik')
@validate_token_template(SECRET_KEY, TOKEN_KEY, db)
@authorized_roles_template(["pegawai"])
def kelola_praktik(decoded_token):
"""
Renders the 'kelola_praktik' page with user information and necessary scripts.
Parameters:
- decoded_token (dict): Decoded token containing user information.
Returns:
- render_template: Rendered HTML template with user information and scripts.
"""
scripts = ['js/praktik.js']
user_id = ObjectId(decoded_token.get("uid"))
user_info = db.users.find_one({"_id": user_id}, {
'_id': False, 'password': False})
return render_template('pages/praktik.html', user_info=user_info, active_page='kelola_praktik', scripts=scripts)
#################### API ROUTES ####################
# Handle Register
@app.route("/api/register", methods=["POST"])
@swag_from('swagger_doc/register.yml')
def api_register():
"""
Handle user registration through the API.
This endpoint expects a POST request with a JSON payload containing user registration data.
The data is validated for completeness, uniqueness, and format before storing it in the database.
Parameters:
None
Returns:
tuple: A tuple containing JSON response and HTTP status code.
Raises:
HttpException: If any validation check fails, an HttpException with appropriate
status code and error message is raised.
"""
body = request.is_json
if not body:
raise HttpException(False, 415, "failed",
"Data harus dalam bentuk JSON")
data = request.get_json()
if not data:
raise HttpException(False, 400, "failed", "Data JSON tidak valid")
username = data.get('username')
name = data.get('name')
nik = data.get('nik')
tgl_lahir = data.get('tglLahir')
gender = data.get('gender')
agama = data.get('agama')
status = data.get('status')
alamat = data.get('alamat')
no_telp = data.get('noTelp')
password = data.get('password')
confirm_password = data.get('confirmPassword')
# Cek apakah semua input sudah diisi
if not all([username, name, nik, tgl_lahir, gender, agama, status, alamat, no_telp, password]):
raise HttpException(False, 400, "failed", "Semua input harus diisi")
# Cek apakah username sudah ada di database
existing_user = db.users.find_one({'username': username})
if existing_user:
raise HttpException(False, 400, "failed", "Username sudah digunakan")
# Cek apakah nik memiliki 16 digit angka
if not is_valid_nik(nik):
raise HttpException(False, 400, "failed",
"NIK harus terdiri dari 16 digit angka")
existing_nik = db.users.find_one({'nik': nik})
if existing_nik:
raise HttpException(False, 400, "failed", "NIK sudah digunakan")
# Cek apakah format tanggal lahir valid
if not is_valid_date(tgl_lahir):
raise HttpException(
False, 400, "failed", "Format tanggal lahir tidak valid, gunakan format dd-mm-yyyy")
# Cek apakah tanggal lahir valid
if not is_max_date_now(tgl_lahir):
raise HttpException(False, 400, "failed",
"Tanggal lahir tidak boleh lebih dari hari ini")
# Cek apakah jenis kelamin valid
if not is_valid_gender(gender):
raise HttpException(False, 400, "failed", "Jenis kelamin tidak valid")
# Cek apakah nomor telepon valid
if not is_valid_phone_number(no_telp):
raise HttpException(
False, 400, "failed", "Nomor telepon tidak valid, gunakan format nomor 10 - 13 digit")
# Cek apakah password sesuai
if len(password) < 8:
raise HttpException(False, 400, "failed",
"Password harus memiliki minimal 8 karakter")
if not any(char.isupper() for char in password):
raise HttpException(False, 400, "failed",
"Password harus memiliki minimal 1 huruf kapital")
if not any(char.isdigit() for char in password):
raise HttpException(False, 400, "failed",
"Password harus memiliki minimal 1 angka")
if not any(not char.isalnum() for char in password):
raise HttpException(
False, 400, "failed", "Password harus memiliki minimal 1 karakter spesial")
if password != confirm_password:
raise HttpException(False, 400, "failed",
"Password dan konfirmasi password tidak sesuai")
# Generate a unique salt for each user
salt = secrets.token_hex(16)
# Use a cost factor of 12, you can adjust it based on your security needs
hashed_password = bcrypt.generate_password_hash(
salt + password + salt, 10).decode('utf-8')
# Simpan data pengguna ke MongoDB
user_data = {
'profile_pic': 'profile_pics/profile_placeholder.png',
'username': username,
'name': name,
'nik': nik,
'tgl_lahir': tgl_lahir,
'gender': gender,
'agama': agama,
'status': status,
'alamat': alamat,
'no_telp': no_telp,
'password': hashed_password,
'role': 'pasien',
'salt': salt,
}
result = db.users.insert_one(user_data)
response = api_response(True, 201, "success", "Pendaftaran akun berhasil", {
'user_id': str(result.inserted_id), 'username': username})
return jsonify(response.__dict__), 201
# Handle Login
@app.route("/api/login", methods=["POST"])
@swag_from('swagger_doc/login.yml')
def sign_in():
"""
Endpoint for user authentication.
This endpoint handles user login through a POST request to '/api/login'.
The request should include a JSON body with 'username' and 'password' fields.
:raises HttpException 415: If the request data is not in JSON format.
:raises HttpException 400: If 'username' or 'password' is missing, or if the provided
credentials are incorrect.
:return: A JSON response with a success message and a JWT token upon successful login.
:rtype: Response
"""
body = request.is_json
if body:
raise HttpException(False, 415, "failed",
"Data harus dalam bentuk form data")
# Sign in
username_receive = request.form.get("username")
password_receive = request.form.get("password")
if not username_receive:
raise HttpException(False, 400, "failed",
"Username tidak boleh kosong")
if not password_receive:
raise HttpException(False, 400, "failed",
"Password tidak boleh kosong")
user = db.users.find_one({"username": username_receive})
if not user:
raise HttpException(False, 400, "failed", "Username / password salah")
# Use bcrypt to verify the password with the stored salt
check_password = bcrypt.check_password_hash(
user.get('password'), user.get('salt') + password_receive + user.get('salt'))
if not check_password:
raise HttpException(False, 400, "failed", "Username / password salah")
user_session = create_user_session(user["_id"], db)
payload = {
"uid": str(user["_id"]),
"sid": str(user_session["_id"]),
"role": user["role"],
"exp": datetime.utcnow() + timedelta(seconds=60 * 60 * 24),
}
token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
response = api_response(True, 200, "success",
"Login berhasil", {TOKEN_KEY: token})
response_data = make_response(jsonify(response.__dict__))
response_data.headers.add(
"Set-Cookie", f"{TOKEN_KEY}={token}; HttpOnly; Secure; Max-Age={60 * 60 * 24}; Path=/")
return response_data
# Handle Logout
@app.route("/api/logout", methods=["POST"])
@validate_token_api(SECRET_KEY, TOKEN_KEY, db)
@swag_from('swagger_doc/logout.yml')
def logout(decoded_token):
"""
Logs out a user by invalidating the session identified by the decoded token.
This endpoint is accessible via a POST request to "/api/logout" and requires a valid access token.
Args:
decoded_token (dict): The decoded JWT token containing user information.
Returns:
flask.Response: A JSON response indicating the success of the logout operation.
The response includes a message, status code, and relevant data.
"""
session_id = ObjectId(decoded_token["sid"])
logout_user_session(session_id, db)
response = api_response(True, 200, "success", "Logout berhasil")
response_data = make_response(jsonify(response.__dict__))
response_data.headers.add(
"Set-Cookie", f"{TOKEN_KEY}=; HttpOnly; Secure; Max-Age=0; Path=/")
return response_data
# API Pendaftaran Dashboard
@app.route('/api/pendaftaran')
@validate_token_api(SECRET_KEY, TOKEN_KEY, db)
@authorized_roles_api(["pegawai"])
@swag_from('swagger_doc/pendaftaran.yml')
def api_pendaftaran(decoded_token):
"""
Handle API requests for registration data.
Parameters:
- decoded_token (dict): Decoded token containing user information.
Returns:
- Flask Response: JSON response containing registration data or error message.
This function is a Flask route handling API requests for registration data. It expects
the following query parameters:
- 'name': Filter registrations by name.
- 'poli': Filter registrations by poli.
- 'tanggal': Filter registrations by tanggal.
- 'status_filter': Filter registrations by status.
The function supports DataTables pagination parameters:
- 'draw': Sequence number for the DataTables request.
- 'start': Starting index for paginated results.
- 'length': Number of records to fetch for paginated results.
Additionally, the function supports searching, sorting, and filtering based on the DataTables request.
The API response includes a JSON object with the following fields:
- 'success' (bool): Indicates whether the request was successful.
- 'code' (int): HTTP status code.
- 'message' (str): Description of the response.
- 'data' (list): List of registration data.
- 'pagination' (dict): Meta pagination information.
- 'datatables_pagination' (dict): DataTables pagination information.
The function is decorated with route, token validation, role authorization, and Swagger documentation.
"""
name = request.args.get('name')
poli = request.args.get('poli')
tanggal = request.args.get('tanggal')
status_filter = request.args.getlist('status_filter')
# Get parameters from DataTables request
draw = request.args.get('draw')
if draw:
draw = int(draw)
start = request.args.get('start')
if start:
start = int(start)
length = request.args.get('length')
if length:
length = int(length)
search_value = request.args.get('search[value]')
status = request.args.getlist('status')
order_column_index = int(request.args.get('order[0][column]', 0))
order_direction = request.args.get('order[0][dir]')
# Adjust the query for sorting
if status:
sort_column = ["antrian", "name", "poli", "tanggal",
"keluhan", "status"][order_column_index]
else:
sort_column = ["antrian", "name", "poli",
"tanggal", "status"][order_column_index]
# Get parameters for your own pagination
page = int(request.args.get('page', 1))
limit = int(request.args.get('limit', 10))
search = request.args.get('search')
order = request.args.get('order')
sort = request.args.get('sort', 'asc')
if name == 'name' and status:
list_nama = list(db.registrations.distinct(
'name', {'status': {'$in': status}}))
sorted_list_nama = sorted(list_nama, key=lambda x: x.lower())
response = api_response(True, 200, "success",
"Data berhasil diambil", sorted_list_nama)
return jsonify(response.__dict__)
if name == 'name' and not status:
list_nama = list(db.registrations.distinct('name'))
sorted_list_nama = sorted(list_nama, key=lambda x: x.lower())
response = api_response(True, 200, "success",
"Data berhasil diambil", sorted_list_nama)
return jsonify(response.__dict__)
if poli == 'poli' and status:
list_poli = list(db.registrations.distinct(
'poli', {'status': {'$in': status}}))
sorted_list_poli = sorted(list_poli, key=lambda x: x.lower())
response = api_response(True, 200, "success",
"Data berhasil diambil", sorted_list_poli)
return jsonify(response.__dict__)
if poli == 'poli' and not status:
list_poli = list(db.registrations.distinct('poli'))
sorted_list_poli = sorted(list_poli, key=lambda x: x.lower())
response = api_response(True, 200, "success",
"Data berhasil diambil", sorted_list_poli)
return jsonify(response.__dict__)
if tanggal == 'tanggal' and status:
list_tanggal = list(db.registrations.distinct(
'tanggal', {'status': {'$in': status}}))
sorted_list_tanggal = sorted(list_tanggal)
response = api_response(True, 200, "success",
"Data berhasil diambil", sorted_list_tanggal)
return jsonify(response.__dict__)
if tanggal == 'tanggal' and not status:
list_tanggal = list(db.registrations.distinct('tanggal'))
sorted_list_tanggal = sorted(list_tanggal)
response = api_response(True, 200, "success",
"Data berhasil diambil", sorted_list_tanggal)
return jsonify(response.__dict__)
# Define regex pattern for matching variations of "Approve"
approve_pattern = re.compile(
r'^a(p(p(r(o(v(e?)?)?)?)?)?)?$', re.IGNORECASE)
reject_pattern = re.compile(r'^r(e(j(e(c(t?)?)?)?)?)?$', re.IGNORECASE)
done_pattern = re.compile(r'^d(o(n(e?)?)?)?$', re.IGNORECASE)
# Decide whether to use DataTables pagination or your own pagination
if not draw:
start = page - 1
length = limit
search_value = search
sort_column = order
order_direction = sort
sort_direction = ASCENDING if order_direction == 'asc' else DESCENDING
collation = {'locale': 'en', 'strength': 2}
# MongoDB query with search
query = {}
if name:
query['name'] = name
if poli:
query['poli'] = poli
if tanggal:
query['tanggal'] = tanggal
if status_filter:
status = status_filter
if status:
query['status'] = {"$in": status}
if search_value:
query["$or"] = [
{"antrian": {"$regex": search_value, "$options": "i"}},
{"name": {"$regex": search_value, "$options": "i"}},
{"poli": {"$regex": search_value, "$options": "i"}},
{"tanggal": {"$regex": search_value, "$options": "i"}},
{"keluhan": {"$regex": search_value, "$options": "i"}},
]
# check if status is approve and search value match with approve pattern
if status and search_value and (approve_pattern.match(search_value) or reject_pattern.match(search_value)):
query["$or"] += [
{"status": "pending"},
]
# check if status is done and search value match with done pattern
if status and search_value and done_pattern.match(search_value):
query["$or"] += [
{"status": "approved"},
]
if not status and search_value:
query["$or"] += [
{"status": {"$regex": search_value, "$options": "i"}},
]
if sort_column:
data = list(db.registrations.find(query).sort(
sort_column, sort_direction).collation(collation).skip(start).limit(length))
else:
data = list(db.registrations.find(query).collation(
collation).skip(start).limit(length))
for d in data:
d['_id'] = str(d['_id'])
# Total records count (unfiltered)
total_records = db.registrations.count_documents({})
if draw and status:
total_records = db.registrations.count_documents({
"status": {"$in": status}
})
# Total records count after filtering
filtered_records = db.registrations.count_documents(query)
total_pages = (filtered_records + length -
1) // length # Calculate total pages
# Create the meta pagination object
pagination = Pagination(start+1, length, total_pages, filtered_records)
# Create datatables pagination object
datatables_pagination = DatatablesPagination(
total_records, filtered_records, draw, start, length)
# return jsonify(response.__dict__)
response = api_response(True, 200, "success", "Data fetched successfully",
data, pagination.__dict__, datatables_pagination.__dict__)
return jsonify(response.__dict__)
# Pendaftaran Pasien (POST)
@app.route('/api/pendaftaran', methods=['POST'])
@validate_token_api(SECRET_KEY, TOKEN_KEY, db)
@authorized_roles_api(["pasien"])
@swag_from('swagger_doc/pendaftaran_post.yml')
def pendaftaran_post(decoded_token):
"""
Handle the POST request for patient registration.
This endpoint allows authorized users with the role "pasien" to submit
a registration form for a medical appointment. The function validates the
incoming request, checks the user's information, and ensures that the
registration data meets the required criteria before storing it in MongoDB.
Args:
decoded_token (dict): Decoded user token containing user information.
Returns:
tuple: A tuple containing a JSON response and HTTP status code.
Raises:
HttpException: An exception with specific details in case of validation errors.
"""
body = request.is_json
if body:
raise HttpException(False, 415, "failed",
"Data harus dalam bentuk form data")
user_id = ObjectId(decoded_token.get("uid"))
# Ambil data pengguna dari koleksi users
user_data = db.users.find_one({"_id": user_id}, {
'_id': False, 'password': False})
if not user_data:
raise HttpException(False, 400, "failed",
"Data pengguna tidak ditemukan")
poli = request.form.get('poli')
# get all poli from collection jadwal in a list
poli_list = list(db.jadwal.distinct('poli'))
if not poli:
raise HttpException(False, 400, "failed", "Poli tidak boleh kosong")
if poli not in poli_list:
raise HttpException(
False, 400, "failed", f"Poli {poli} tidak tersedia, pilih dari {poli_list}")
tanggal = request.form.get('tanggal')
if not tanggal:
raise HttpException(False, 400, "failed", "Tanggal tidak boleh kosong")
if not is_valid_date(tanggal):
raise HttpException(
False, 400, "failed", "Format tanggal tidak valid, gunakan format dd-mm-yyyy")
if not is_min_date_now(tanggal):
raise HttpException(False, 400, "failed",
"Tanggal tidak boleh kurang dari hari ini")
keluhan = request.form.get('keluhan')
if not keluhan:
raise HttpException(False, 400, "failed", "Keluhan tidak boleh kosong")
has_pending_registration = bool(db.registrations.count_documents({
"status": {"$in": ["pending"]},
"username": user_data.get('username')
}) > 0)
if has_pending_registration:
raise HttpException(
False, 400, "failed", "Anda sudah memiliki pendaftaran yang sedang diproses")
has_approved_registration = bool(db.registrations.count_documents({
"status": {"$in": ["approved"]},
"username": user_data.get('username')
}) > 0)
if has_approved_registration:
raise HttpException(False, 400, "failed",
"Anda sudah memiliki pendaftaran yang disetujui")
# Masukkan data pendaftaran ke MongoDB
data_pendaftaran = {
'username': user_data.get('username'),
'name': user_data.get('name'),
'nik': user_data.get('nik'),
'tgl_lahir': user_data.get('tgl_lahir'),
'gender': user_data.get('gender'),
'agama': user_data.get('agama'),
'status_pernikahan': user_data.get('status'),
'alamat': user_data.get('alamat'),
'no_telp': user_data.get('no_telp'),
'poli': poli,
'tanggal': tanggal,
'keluhan': keluhan,
'status': 'pending'
}
result = db.registrations.insert_one(data_pendaftaran)
data_pendaftaran["_id"] = str(result.inserted_id)
socketio.emit('new_pendaftaran', data_pendaftaran,
namespace='/pendaftaran')
response = api_response(
True, 201, "success", "Formulir telah diproses. Silakan tunggu.", data_pendaftaran)
return jsonify(response.__dict__), 201
# Return Riwayat Pendaftaran Pasien
@app.route('/api/pendaftaran/me')
@validate_token_api(SECRET_KEY, TOKEN_KEY, db)
@authorized_roles_api(["pasien"])
@swag_from('swagger_doc/pendaftaran_me.yml')
def riwayat_pendaftaran_api(decoded_token):
"""
API endpoint to retrieve registration history for a user.
This endpoint requires authentication using a valid token and specific roles.
Parameters:
- decoded_token (dict): The decoded user token containing user information.
Returns:
- Flask Response: JSON response containing registration history data.
Raises:
- HttpException: If user data is not found or there is an issue with the request.
"""
user_id = ObjectId(decoded_token.get("uid"))
user_data = db.users.find_one({"_id": user_id}, {
'_id': False, 'password': False})
username = user_data.get('username')
# Get parameters from DataTables request
draw = request.args.get('draw')
if draw:
draw = int(draw)
start = request.args.get('start')
if start:
start = int(start)
length = request.args.get('length')
if length:
length = int(length)
search_value = request.args.get('search[value]')
order_column_index = int(request.args.get('order[0][column]', 0))
order_direction = request.args.get('order[0][dir]')
# Adjust the query for sorting
sort_column = ["_id", "name", "nik", "poli",
"tanggal", "status"][order_column_index]
if not user_data:
raise HttpException(False, 400, "failed",
"Data pengguna tidak ditemukan")
# Get parameters for your own pagination
page = int(request.args.get('page', 1))
limit = int(request.args.get('limit', 10))
search = request.args.get('search')
order = request.args.get('order')
sort = request.args.get('sort', 'asc')
# Decide whether to use DataTables pagination or your own pagination
if not draw:
start = page - 1
length = limit
search_value = search
sort_column = order
order_direction = sort
sort_direction = ASCENDING if order_direction == 'asc' else DESCENDING
collation = {'locale': 'en', 'strength': 2}
# MongoDB query with search
query = {'username': username}
if search_value:
query["$or"] = [
{"name": {"$regex": search_value, "$options": "i"}},
{"nik": {"$regex": search_value, "$options": "i"}},
{"poli": {"$regex": search_value, "$options": "i"}},
{"tanggal": {"$regex": search_value, "$options": "i"}},
{"status": {"$regex": search_value, "$options": "i"}},
]
if sort_column:
data = list(db.registrations.find(query).sort(
sort_column, sort_direction).collation(collation).skip(start).limit(length))
else:
data = list(db.registrations.find(query).collation(
collation).skip(start).limit(length))
for d in data:
d['_id'] = str(d['_id'])
# Total records count (unfiltered)
total_records = db.registrations.count_documents({'username': username})
# Total records count after filtering
filtered_records = db.registrations.count_documents(query)
total_pages = (filtered_records + length -
1) // length # Calculate total pages
# Create the meta pagination object
pagination = Pagination(start+1, length, total_pages, filtered_records)
# Create datatables pagination object
datatables_pagination = DatatablesPagination(
total_records, filtered_records, draw, start, length)
response = api_response(True, 200, "success", "Data berhasil diambil", data,
pagination.__dict__, datatables_pagination.__dict__)
return jsonify(response.__dict__)
@app.route('/api/pendaftaran/<id>/approve', methods=['POST'])
@validate_token_api(SECRET_KEY, TOKEN_KEY, db)