-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathseeder.py
445 lines (358 loc) · 18 KB
/
seeder.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
from attr import has
from flask import Flask
from flask_pymongo import PyMongo
from pymongo import MongoClient
from faker import Faker
import os
import argparse
import random
from os.path import join, dirname
from dotenv import load_dotenv
from datetime import datetime, timedelta
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
app = Flask(__name__)
MONGODB_CONNECTION_STRING = os.environ.get("MONGODB_CONNECTION_STRING")
if not MONGODB_CONNECTION_STRING:
raise ValueError(
"MONGODB_CONNECTION_STRING environment variable is not set")
# Set the default database name
DB_NAME = os.environ.get("DB_NAME")
if not DB_NAME:
raise ValueError("DB_NAME environment variable is not set")
app.config['MONGO_URI'] = MONGODB_CONNECTION_STRING
app.config['MONGO_DBNAME'] = DB_NAME
mongo = PyMongo(app)
client = MongoClient(MONGODB_CONNECTION_STRING)
# How to use
# Seed all collections
# python3 seeder.py --user --jadwal --registration --approve-registrations --done-registrations --rekam-medis --list-checkup-user
# Recreate database
# python3 seeder.py --user --jadwal --registration --approve-registrations --done-registrations --rekam-medis --list-checkup-user --reload
# Seed registrations_pasien collection
# python3 seeder.py --registration --approve-registrations --done-registrations --rekam-medis --list-checkup-user
# Seed users collection
# python3 seeder.py --user
# Seed jadwal collection
# python3 seeder.py --jadwal
# Seed registrations_pasien collection
# python3 seeder.py --registration
# Seed rekam_medis collection
# python3 seeder.py --rekam-medis
# Seed list_checkup_user collection
# python3 seeder.py --list-checkup-user
fake = Faker('id_ID')
# Function to generate fake user data
def generate_fake_user(role):
db = mongo.cx[app.config['MONGO_DBNAME']]
while True:
username = fake.unique.user_name()
nik = str(fake.unique.random_number(16))
# Check if the generated username or nik already exists in the database
existing_user = db.users.find_one(
{'$or': [{'username': username}, {'nik': nik}]})
if existing_user is None and len(nik) == 16:
break
password = "$2b$10$xm2V57w6d8/Q4RzMYp9GDeiahaWW5HLmD1TxaS2TLurYXscUAATHS" # Password.12
salt = "6da84944bc8be809e39d6e63257cb840"
user_data = {
'profile_pic': 'profile_pics/profile_placeholder.png',
'username': username,
'name': fake.name(),
'nik': nik,
'tgl_lahir': fake.date_of_birth(minimum_age=18, maximum_age=60).strftime('%d-%m-%Y'),
'gender': fake.random_element(elements=('laki-laki', 'perempuan')),
'agama': fake.random_element(elements=('islam', 'kristen', 'hindu', 'budha', 'lainnya')),
'status': fake.random_element(elements=('menikah', 'single')),
'alamat': fake.address(),
'no_telp': '628' + str(fake.random_int(min=10**7, max=10**10)),
'password': password,
'role': role,
'salt': salt,
}
return user_data
# Function to seed the users collection with a specific number of users for each role
def seed_users(num_pasien=10, num_pegawai=2):
with app.app_context():
db = mongo.cx[app.config['MONGO_DBNAME']]
roles = {'pasien': num_pasien, 'pegawai': num_pegawai}
for role, count in roles.items():
for _ in range(count):
user_data = generate_fake_user(role)
db.users.insert_one(user_data)
print("Users seeded.")
# Function to seed the jadwal collection
def seed_jadwal(num_jadwal=3):
with app.app_context():
db = mongo.cx[app.config['MONGO_DBNAME']]
poli_choices = ['Umum', 'Gigi', 'Mata', 'Jantung', 'THT',
'Syaraf', 'Kesehatan Jiwa', 'Anak', 'Fisioterapi']
hari_choices = ['senin', 'selasa', 'rabu', 'kamis', 'jumat', 'sabtu', 'minggu']
for _ in range(num_jadwal): # Adjust the number of jadwal entries as needed
# Generate random time values
jam_buka = fake.time(pattern="%H:%M")
jam_tutup = fake.time(pattern="%H:%M")
# Ensure jam_buka is less than jam_tutup
while jam_buka >= jam_tutup:
jam_buka = fake.time(pattern="%H:%M")
jam_tutup = fake.time(pattern="%H:%M")
# Calculate the difference between jam_buka and jam_tutup
time_format = "%H:%M"
diff = datetime.strptime(
jam_tutup, time_format) - datetime.strptime(jam_buka, time_format)
# Ensure the difference is at least 2 hours and at most 4 hours
while diff < timedelta(hours=2) or diff > timedelta(hours=4):
jam_buka = fake.time(pattern="%H:%M")
jam_tutup = fake.time(pattern="%H:%M")
diff = datetime.strptime(
jam_tutup, time_format) - datetime.strptime(jam_buka, time_format)
jadwal_data = {
'nama': fake.name(),
'poli': fake.random_element(elements=poli_choices),
'hari': random.sample(hari_choices, k=random.randint(1, 5)),
'jam_buka': jam_buka,
'jam_tutup': jam_tutup
}
# Sort the 'hari' list according to the specified order
jadwal_data['hari'].sort(key=hari_choices.index)
db.jadwal.insert_one(jadwal_data)
print("Jadwal seeded.")
# Function to seed the registrations_pasien collection
def seed_registrations_pasien(num_registration=3):
with app.app_context():
db = mongo.cx[app.config['MONGO_DBNAME']]
status_choices = ['done', 'rejected', 'canceled', 'expired']
for user in db.users.find({'role': 'pasien'}):
has_pending_or_approved = db.registrations.find_one({'username': user['username'], 'status': {'$in': ['pending', 'approved']}})
if not has_pending_or_approved:
registration_data = {
'username': user['username'],
'name': user['name'],
'nik': user['nik'],
'tgl_lahir': user['tgl_lahir'],
'gender': user['gender'],
'agama': user['agama'],
'status_pernikahan': user['status'],
'alamat': user['alamat'],
'no_telp': user['no_telp'],
'tanggal': (datetime.now()).strftime('%d-%m-%Y'),
'keluhan': fake.sentence(),
'status': fake.random_element(elements=['approved', 'pending'])
}
# Choose poli randomly from jadwal collection
jadwal_poli = db.jadwal.aggregate([
{'$sample': {'size': 1}},
{'$project': {'_id': 0, 'poli': 1}}
]).next()
registration_data['poli'] = jadwal_poli['poli']
if registration_data['status'] in ['approved']:
# Calculate the antrian based on the number of registrations for the same date and poli
count_same_date_poli = db.registrations.count_documents({
'tanggal': registration_data['tanggal'],
'poli': registration_data['poli'],
'status': {'$in': ['approved', 'done']}
})
registration_data['antrian'] = f"{count_same_date_poli + 1:03d}"
db.registrations.insert_one(registration_data)
# Create more registrations for the same user
for _ in range(random.randint(1, num_registration)):
registration_data = {
'username': user['username'],
'name': user['name'],
'nik': user['nik'],
'tgl_lahir': user['tgl_lahir'],
'gender': user['gender'],
'agama': user['agama'],
'status_pernikahan': user['status'],
'alamat': user['alamat'],
'no_telp': user['no_telp'],
'tanggal': (datetime.now() - timedelta(days=random.randint(0, 30))).strftime('%d-%m-%Y'),
'keluhan': fake.sentence(),
'status': fake.random_element(elements=status_choices)
}
# Choose poli randomly from jadwal collection
jadwal_poli = db.jadwal.aggregate([
{'$sample': {'size': 1}},
{'$project': {'_id': 0, 'poli': 1}}
]).next()
registration_data['poli'] = jadwal_poli['poli']
if registration_data['status'] in ['approved', 'done']:
# Calculate the antrian based on the number of registrations for the same date and poli
count_same_date_poli = db.registrations.count_documents({
'tanggal': registration_data['tanggal'],
'poli': registration_data['poli'],
'status': {'$in': ['approved', 'done']}
})
registration_data['antrian'] = f"{count_same_date_poli + 1:03d}"
# Check if there are more "done" registrations than "approved" registrations on the same date
if registration_data['status'] == 'done':
approved_count = db.registrations.count_documents({
'username': user['username'],
'status': 'approved',
'tanggal': registration_data['tanggal']
})
done_count = db.registrations.count_documents({
'username': user['username'],
'status': 'done',
'tanggal': registration_data['tanggal']
})
if done_count >= approved_count:
continue # Skip this registration if the "done" count is greater or equal to "approved"
if registration_data['status'] == 'expired':
# Set expired registration to random date in the past
registration_data['tanggal'] = (datetime.now() - timedelta(days=random.randint(1, 30))).strftime('%d-%m-%Y')
# Calculate the antrian based on the number of registrations for the same date and poli
count_same_date_poli = db.registrations.count_documents({
'tanggal': registration_data['tanggal'],
'poli': registration_data['poli'],
'status': {'$in': ['approved', 'done']}
})
registration_data['antrian'] = f"{count_same_date_poli + 1:03d}"
db.registrations.insert_one(registration_data)
print("Registrations seeded.")
# Function to approve all pending registration
def approve_registrations():
with app.app_context():
db = mongo.cx[app.config['MONGO_DBNAME']]
# Iterate through the registrations_pasien collection
for registration in db.registrations.find({'status': 'pending'}):
# Calculate the antrian based on the number of registrations for the same date and poli
count_same_date_poli = db.registrations.count_documents({
'tanggal': registration['tanggal'],
'poli': registration['poli'],
'status': {'$in': ['approved', 'done']}
})
registration['antrian'] = f"{count_same_date_poli + 1:03d}"
db.registrations.update_one(
{'_id': registration['_id']}, {'$set': {'antrian': registration['antrian'], 'status': 'approved'}})
print("Registrations approved.")
# Function to done all approved registraiton
def done_registrations():
with app.app_context():
db = mongo.cx[app.config['MONGO_DBNAME']]
# Iterate through the registrations_pasien collection
for registration in db.registrations.find({'status': 'approved'}):
# Calculate the antrian based on the number of registrations for the same date and poli
count_same_date_poli = db.registrations.count_documents({
'tanggal': registration['tanggal'],
'poli': registration['poli'],
'status': {'$in': ['approved', 'done']}
})
registration['antrian'] = f"{count_same_date_poli + 1:03d}"
db.registrations.update_one(
{'_id': registration['_id']}, {'$set': {'antrian': registration['antrian'], 'status': 'done'}})
print("Registrations done.")
# Function to seed the rekam_medis collection
def seed_rekam_medis():
with app.app_context():
db = mongo.cx[app.config['MONGO_DBNAME']]
# Iterate through the registrations_pasien collection
for registration in db.registrations.find({'status': 'done'}):
# Check if rekam_medis already exists for this user
existing_rekam_medis = db.rekam_medis.find_one(
{'nik': registration['nik']})
if existing_rekam_medis:
continue # Skip if rekam_medis already exists for this user
# Calculate umur based on tgl_lahir
tgl_lahir = datetime.strptime(
registration['tgl_lahir'], '%d-%m-%Y')
umur = (datetime.now() - tgl_lahir).days // 365
# Generate nomor rekam medis
nomor_rekam_medis = generate_nomor_rekam_medis()
while db.rekam_medis.find_one({'no_kartu': nomor_rekam_medis}):
# Generate new nomor rekam medis if the generated nomor rekam medis already exists
nomor_rekam_medis = generate_nomor_rekam_medis()
# Create rekam_medis data
rekam_medis_data = {
'no_kartu': nomor_rekam_medis,
'username': registration['username'],
'nama': registration['name'],
'nik': registration['nik'],
'umur': str(umur),
'alamat': registration['alamat'],
'no_telp': registration['no_telp'],
}
# Insert rekam_medis data into the rekam_medis collection
db.rekam_medis.insert_one(rekam_medis_data)
print("Rekam medis seeded.")
# Function to generate nomor rekam medis
def generate_nomor_rekam_medis():
# Assuming 6-digit nomor rekam medis with the format XX-XX-XX
nomor_rekam_medis = '-'.join([str(random.randint(0, 99)).zfill(2)
for _ in range(3)])
return nomor_rekam_medis
# Function to seed the list_checkup_user collection
def seed_list_checkup_user():
with app.app_context():
db = mongo.cx[app.config['MONGO_DBNAME']]
# Iterate through the registrations_pasien collection with status 'done'
for registration in db.registrations.find({'status': 'done'}):
has_checkup = db.list_checkup_user.find_one(
{'nik': registration['nik'], 'tgl_periksa': registration['tanggal'], 'poli': registration['poli'], 'dokter': {'$exists': True}, 'hasil_anamnesa': {'$exists': True}, 'keluhan': registration['keluhan'], 'nama': registration['name']})
if has_checkup:
continue
# Get dokter name from jadwal
dokter_name = db.jadwal.aggregate([
{'$match': {'poli': registration['poli']}},
{'$sample': {'size': 1}},
{'$project': {'_id': 0, 'nama': 1}}
]).next()['nama']
# Create list_checkup_user data
checkup_data = {
'nik': registration['nik'],
'dokter': dokter_name,
'hasil_anamnesa': fake.text(),
'keluhan': registration['keluhan'],
'nama': registration['name'],
'poli': registration['poli'],
'tgl_periksa': registration['tanggal'],
}
# Insert list_checkup_user data into the list_checkup_user collection
db.list_checkup_user.insert_one(checkup_data)
print("List checkup user seeded.")
# Function to drop and recreate the database
def recreate_database():
with app.app_context():
db = mongo.cx[app.config['MONGO_DBNAME']]
db.users.delete_many({})
db.jadwal.delete_many({})
db.registrations.delete_many({})
db.rekam_medis.delete_many({})
db.list_checkup_user.delete_many({})
db.user_sessions.delete_many({})
print("Collections cleared.")
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Seed MongoDB database for Flask app.")
parser.add_argument('--user', action='store_true',
help='Seed users collection')
parser.add_argument('--jadwal', action='store_true',
help='Seed jadwal collection')
parser.add_argument('--registration', action='store_true',
help='Seed registrations_pasien collection')
parser.add_argument('--rekam-medis', action='store_true',
help='Seed rekam_medis collection'),
parser.add_argument('--list-checkup-user', action='store_true', help='Seed list_checkup_user collection'),
parser.add_argument('--approve-registrations', action='store_true',
help='Approve all pending registrations'),
parser.add_argument('--done-registrations', action='store_true',
help='Done all approved registrations'),
parser.add_argument('--reload', action='store_true',
help='Drop and recreate the database')
args = parser.parse_args()
if args.reload:
recreate_database()
if args.user:
seed_users(num_pasien=100, num_pegawai=1)
if args.jadwal:
seed_jadwal(num_jadwal=20)
if args.registration:
seed_registrations_pasien(num_registration=1)
if args.rekam_medis:
seed_rekam_medis()
if args.list_checkup_user:
seed_list_checkup_user()
if args.approve_registrations:
approve_registrations()
if args.done_registrations:
done_registrations()