def get_user_brief_cope_results(user_id): start_date = request.args.get('start_date') end_date = request.args.get('end_date') if validate_datetime(start_date, 'date') is False or validate_datetime( end_date, 'date') is False: return jsonify(status=False, message='Format tanggal tidak valid'), 400 if ObjectId.is_valid(user_id) is True: user_id = ObjectId(user_id) brief_cope_results = list( mongo.db.brief_cope_results.find({ 'user_id': user_id, 'created_at': { '$gte': datetime.datetime.strptime(start_date, datetime_format('date')), '$lte': datetime.datetime.strptime(end_date, datetime_format('date')) } }).sort('created_at')) for result in brief_cope_results: result['_id'] = str(result['_id']) if ObjectId.is_valid(result['user_id']) is True: result['user_id'] = str(result['user_id']) result['created_at'] = {'date': str(result['created_at'].date())} return jsonify(status=True, brief_cope_results=brief_cope_results)
def resolve_get_users_growth_by_year(self, info, **kwargs): start_date= kwargs.get('start_date') end_date= kwargs.get('end_date') if lesser_comparison_datetime(start_date, end_date, 'date') is False: return [] if validate_datetime(start_date, 'date') is False or validate_datetime(end_date, 'date') is False: return [] start_date= datetime.datetime.strptime(start_date, datetime_format('date')) end_date= datetime.datetime.strptime(end_date, datetime_format('date')) users= list(mongo.db.users.find({ 'joined_at': { '$gte': start_date, '$lte': end_date }, 'is_admin': False })) users_growth_by_year= [] for date in list(get_months_between(start_date, end_date)): users_growth_by_year.append(UsersGrowthByYear( month_name= get_month_name(date.month-1), month_number= date.month, year= date.year, users= [] )) for growth in users_growth_by_year: for user in users: joined_at= user['joined_at'].date() if growth.month_number == joined_at.month and growth.year == joined_at.year: growth.users.append(user) return users_growth_by_year
def re_structure_habit_input(fields, operation= 'create'): if fields.reminder_time != '': fields['reminder_time']= datetime.datetime.strptime(fields.reminder_time, datetime_format('time')) structured= { '_id': get_sequence('habits'), 'name': fields['name'], 'description': fields['description'], 'created_at': '', 'type': fields['type'], 'day': fields['day'], 'goal': fields['goal'], 'goal_dates': { 'start': datetime.datetime.strptime(fields.goal_dates.start, datetime_format('date')), 'end': datetime.datetime.strptime(fields.goal_dates.end, datetime_format('date')) }, 'reminder_time': fields['reminder_time'], 'is_reminder': fields['is_reminder'], 'is_notified': False, 'label_color': fields['label_color'] } if operation == 'create': current_datetime= datetime.datetime.now() current_date= current_datetime.strftime(datetime_format('date')) current_time= current_datetime.strftime(datetime_format('time')) structured['created_at']= datetime.datetime.strptime(f"{current_date} {current_time}", datetime_format('datetime')) elif operation == 'update': del structured['_id'] del structured['created_at'] return structured
def resolve_get_moods_growth_by_year(self, info, **kwargs): start_date = kwargs.get('start_date') end_date = kwargs.get('end_date') if lesser_comparison_datetime(start_date, end_date, 'date') is False: return [] if validate_datetime(start_date, 'date') is False or validate_datetime( end_date, 'date') is False: return [] start_date = datetime.datetime.strptime(start_date, datetime_format('date')) end_date = datetime.datetime.strptime(end_date, datetime_format('date')) moods = list( mongo.db.moods.find( {'created_at': { '$gte': start_date, '$lte': end_date }})) moods_growth_by_year = [] for date in list(get_months_between(start_date, end_date)): moods_growth_by_year.append( MoodsGrowthByYear(month_name=get_month_name(date.month - 1), month_number=date.month, year=date.year, mood_count=0, mood_average=0)) for growth in moods_growth_by_year: for mood in moods: created_at = mood['created_at'].date() if growth.month_number == created_at.month and growth.year == created_at.year: growth.mood_count += 1 growth.mood_average += mood['emoticon']['value'] # for mood in moods: # month= mood['created_at'].date().month # moods_growth_by_year[month-1].mood_count+= 1 # moods_growth_by_year[month-1].mood_average+= mood['emoticon']['value'] for growth in moods_growth_by_year: if growth.mood_count > 0: growth.mood_average /= growth.mood_count return moods_growth_by_year
def resolve_get_app_feedbacks_growth_by_year(self, info, **kwargs): start_date = kwargs.get('start_date') end_date = kwargs.get('end_date') if lesser_comparison_datetime(start_date, end_date, 'date') is False: return [] if validate_datetime(start_date, 'date') is False or validate_datetime( end_date, 'date') is False: return [] start_date = datetime.datetime.strptime(start_date, datetime_format('date')) end_date = datetime.datetime.strptime(end_date, datetime_format('date')) feedbacks = list( mongo.db.app_feedbacks.find( {'created_at': { '$gte': start_date, '$lte': end_date }})) feedbacks_growth_by_year = [] for date in list(get_months_between(start_date, end_date)): feedbacks_growth_by_year.append( AppFeedbacksGrowthByYear(month_name=get_month_name(date.month - 1), month_number=date.month, year=date.year, feedbacks=[], average_rating=0)) for growth in feedbacks_growth_by_year: for feedback in feedbacks: created_at = feedback['created_at'].date() if growth.month_number == created_at.month and growth.year == created_at.year: growth.feedbacks.append(feedback) growth.average_rating += feedback['rating'] for growth in feedbacks_growth_by_year: if len(growth.feedbacks) > 0: growth.average_rating /= len(growth.feedbacks) return feedbacks_growth_by_year
def mutate(self, info, fields): #if fields is None or 'first_name' not in fields or 'last_name' not in fields or 'gender' not in fields or 'age' not in fields or 'email' not in fields or 'username' not in fields or 'password' not in fields or 'confirm_password' not in fields: # return CreateUser(response= ResponseMessage(text= 'Terjadi kesalahan pada server, data yang dikirimkan tidak lengkap.', status= False)) # #for key, value in fields.items(): # if value is None or value == '' or (key == 'age' and value == 0): # return CreateUser(response= ResponseMessage(text= 'Kolom registrasi tidak boleh ada yang kosong!', status= False)) # #if fields.password != fields.confirm_password: # return CreateUser(response= ResponseMessage(text= 'Konfirmasi kata sandi dengan kata sandi tidak cocok!', status= False)) # #del fields['confirm_password'] if validate_datetime(fields['date_of_birth'], 'date') is False: return CreateUser( created_user= None, response= ResponseMessage(text= 'Format tanggal lahir tidak sesusai', status= False) ) is_email_username_exist= mongo.db.users.find_one({ '$or': [ { 'email': fields.email }, { 'username': fields.username } ] }) if is_email_username_exist: return CreateUser( created_user= None, response= ResponseMessage(text= 'Alamat surel atau nama pengguna sudah ada yang menggunakan', status= False) ) fields['date_of_birth']= datetime.datetime.strptime(fields['date_of_birth'], datetime_format('date')) fields['password']= generate_password_hash(fields['password']) fields['joined_at']= datetime.datetime.now() fields['is_admin']= False fields['is_active']= True result= mongo.db.users.insert_one(dict(fields)) if result.inserted_id is None: #and init_user_activities.inserted_id is None: return CreateUser( created_user= None, response= ResponseMessage(text= 'Terjadi kesalahan pada server, registrasi akun gagal', status= False) ) created_user= mongo.db.users.find_one({ '_id': result.inserted_id }) return CreateUser( created_user= created_user, response= ResponseMessage(text= 'Registrasi akun baru berhasil!', status= True) )
def mutate(self, info, fields): #for key, value in fields.items(): # if value is None or value == '': # return UpdateUser(response= ResponseMessage(text= 'Kolom tidak boleh ada yang kosong!', status= False)) if validate_datetime(fields['date_of_birth'], 'date') is False: return UpdateProfile( updated_profile= None, response= ResponseMessage(text= 'Format tanggal lahir tidak sesuai', status= False) ) is_email_exist= mongo.db.users.find_one({ '$and': [ { '_id': { '$ne': ObjectId(get_jwt_identity()) } }, { 'email': fields['email'] } ] }) if is_email_exist: return UpdateProfile( updated_profile= None, response= ResponseMessage(text= 'Surel telah ada yang menggunakan, coba dengan surel lain', status= False) ) fields['date_of_birth']= datetime.datetime.strptime(fields['date_of_birth'], datetime_format('date')) result= mongo.db.users.find_one_and_update( { '_id': ObjectId(get_jwt_identity()) }, { '$set': dict(fields) } ) if result is None: return UpdateProfile( updated_profile= None, response= ResponseMessage(text= 'Terjadi kesalahan pada server, profil gagal diperbarui', status= False) ) updated_user= mongo.db.users.find_one({ '_id': ObjectId(get_jwt_identity()) }) updated_user['date_of_birth']= updated_user['date_of_birth'].date() return UpdateProfile( updated_profile= updated_user, response= ResponseMessage(text= 'Perubahan profil tersimpan', status= True) )
def save_brief_cope_result(): data = request.get_json() data['created_at'] = datetime.datetime.strptime( str(datetime.datetime.now().date()), datetime_format('date')) if ObjectId.is_valid(data['user_id']) is True: data['user_id'] = ObjectId(data['user_id']) else: data['user_id'] = str(data['user_id']) result = mongo.db.brief_cope_results.insert_one(data) if result.inserted_id is None: return jsonify( status=False, message= 'Terjadi kesalahan pada server, gagal menyimpna hasil evaluasi Brief-COPE' ), 500 return jsonify(status=True, message='Berhasil menyimpan hasil evaluasi Brief-COPE')
def mutate(self, info, _id, fields, img_upload): if ObjectId.is_valid(_id) is False: return UpdateUser( updated_user= None, response= ResponseMessage(text= 'Format Id tidak sesuai, pengguna gagal diperbarui', status= False) ) if validate_datetime(fields['date_of_birth'], 'date') is False: return UpdateUser( updated_user= None, response= ResponseMessage(text= 'Format tanggal tidak sesuai, pengguna gagal diperbarui', status= False) ) if 'date_of_birth' in fields: fields['date_of_birth']= datetime.datetime.strptime(fields['date_of_birth'], datetime_format('date')) if 'password' in fields: fields['password']= bcrypt.generate_password_hash(fields['password']) if img_upload.filename != 'default': file_name= formatted_file_name(img_upload.filename) fields['img_url']= f"{request.host_url}uploads/images/{file_name}" img_upload.save(os.path.join(f"{upload_path}/images", file_name)) if calculate_age(datetime.datetime.strptime(fields['date_of_birth'], datetime_format('date')).date()) < 12: return UpdateUser( updated_user= None, response= ResponseMessage(text= 'Umur pengguna belum mencukupi untuk menggunakan aplikasi ini, pengguna gagal diperbarui', status= False) ) result= mongo.db.users.find_one_and_update( { '_id': ObjectId(_id) }, { '$set': dict(fields) } ) if result is None: return UpdateUser( updated_user= None, response= ResponseMessage(text= 'Terjadi kesalahan pada server, pengguna gagal diperbarui', status= False) ) updated_user= mongo.db.users.find_one({ '_id': ObjectId(_id) }) updated_user['date_of_birth']= updated_user['date_of_birth'].date() updated_user['joined_at']= updated_user['joined_at'].date() if updated_user['img_url'] != default_img and is_uploaded_file_exist(updated_user['img_url'].split('/')[-1]) is False: result= mongo.db.users.update_one( { '_id': ObjectId(_id) }, { '$set': { 'img_url': default_img } } ) if result.modified_count == 0: return UpdateUser( updated_user= None, response= ResponseMessage(text= 'Terjadi kesalahan pada gambar profil pengguna, pengguna gagal diperbarui', status= False) ) updated_user['img_url']= default_img return UpdateUser( updated_user= updated_user, response= ResponseMessage(text= 'Berhasil membarui informasi pengguna', status= True) )
def run_brief_cope_result_seeder(): mongo.db.brief_cope_results.delete_many({}) brief_cope_results = [{ 'user_id': '1', 'coping_strategy': 'Problem-focused', 'problem_focused': { 'average': 2.75, 'categories': { 'active_coping': 3, 'use_of_informational_support': 2, 'positive_reframing': 3, 'planning': 3 } }, 'emotion_focused': { 'average': 2.58, 'coping_strategy': 'Problem-focused', 'categories': { 'emotional_support': 3, 'venting': 2, 'humour': 1.5, 'acceptance': 3, 'self_blame': 3, 'religion': 3 } }, 'avoidant': { 'average': 2.5, 'coping_strategy': 'Problem-focused', 'categories': { 'self_distraction': 3, 'substance_use': 1.5, 'denial': 2, 'behavioural_disengagement': 3.5 } }, 'created_at': datetime.strptime('2021-12-1', datetime_format('date')) }, { 'user_id': '1', 'coping_strategy': 'Problem-focused', 'problem_focused': { 'average': 2.75, 'categories': { 'active_coping': 3, 'use_of_informational_support': 2, 'positive_reframing': 3, 'planning': 3 } }, 'emotion_focused': { 'average': 2.58, 'categories': { 'emotional_support': 3, 'venting': 2, 'humour': 1.5, 'acceptance': 3, 'self_blame': 3, 'religion': 3 } }, 'avoidant': { 'average': 2.5, 'categories': { 'self_distraction': 3, 'substance_use': 1.5, 'denial': 2, 'behavioural_disengagement': 3.5 } }, 'created_at': datetime.strptime('2021-12-10', datetime_format('date')) }, { 'user_id': '1', 'coping_strategy': 'Problem-focused', 'problem_focused': { 'average': 2.75, 'categories': { 'active_coping': 3, 'use_of_informational_support': 2, 'positive_reframing': 3, 'planning': 3 } }, 'emotion_focused': { 'average': 2.58, 'categories': { 'emotional_support': 3, 'venting': 2, 'humour': 1.5, 'acceptance': 3, 'self_blame': 3, 'religion': 3 } }, 'avoidant': { 'average': 2.5, 'categories': { 'self_distraction': 3, 'substance_use': 1.5, 'denial': 2, 'behavioural_disengagement': 3.5 } }, 'created_at': datetime.strptime('2022-1-1', datetime_format('date')) }, { 'user_id': '1', 'coping_strategy': 'Problem-focused', 'problem_focused': { 'average': 2.75, 'categories': { 'active_coping': 3, 'use_of_informational_support': 2, 'positive_reframing': 3, 'planning': 3 } }, 'emotion_focused': { 'average': 2.58, 'categories': { 'emotional_support': 3, 'venting': 2, 'humour': 1.5, 'acceptance': 3, 'self_blame': 3, 'religion': 3 } }, 'avoidant': { 'average': 2.5, 'categories': { 'self_distraction': 3, 'substance_use': 1.5, 'denial': 2, 'behavioural_disengagement': 3.5 } }, 'created_at': datetime.strptime('2022-2-17', datetime_format('date')) }] try: result = mongo.db.brief_cope_results.insert_many(brief_cope_results) if len(result.inserted_ids) == 0: print('Seeding brief_cope_results collection failed...') return print('Seeding brief_cope_results collection succeed...') except Exception as ex: print('Seeding brief_cope_results collection failed...') print('error', ex)
def resolve_get_filtered_user_habits(self, info, filters): filter_conditions = [] if filters.name != '': filter_conditions.append( {'name': { '$regex': filters.name, '$options': 'i' }}) if filters.type != '': filter_conditions.append({'type': filters.type}) if filters.start_date != '' and filters.end_date == '' and validate_datetime( filters.start_date, 'date'): filter_conditions.append({ 'goal_dates.start': datetime.datetime.strptime(filters.start_date, datetime_format('date')) }) elif filters.start_date == '' and filters.end_date != '' and validate_datetime( filters.end_date, 'date'): filter_conditions.append({ 'goal_dates.end': datetime.datetime.strptime(filters.end_date, datetime_format('date')) }) elif ((filters.start_date != '' and filters.end_date != '') and validate_datetime(filters.start_date, 'date') and validate_datetime(filters.end_date, 'date')): #below works too # filter_conditions.append({ # 'goal_dates.start': { '$gte': datetime.datetime.strptime(filters.start_date, datetime_format('date')) }, # 'goal_dates.end': { '$lte': datetime.datetime.strptime(filters.end_date, datetime_format('date')) } # }) filter_conditions.append({ '$and': [{ 'goal_dates.start': { '$gte': datetime.datetime.strptime(filters.start_date, datetime_format('date')) } }, { 'goal_dates.end': { '$lte': datetime.datetime.strptime(filters.end_date, datetime_format('date')) } }] }) if filters.reminder_time != '': filter_conditions.append({'reminder_time': filters.reminder_time}) if filters.label_color != '': filter_conditions.append( {'label_color': f'#{filters.label_color}'}) user_habits = mongo.db.user_habits.find_one( {'user_id': ObjectId(get_jwt_identity())}) if UserHabits is None or not user_habits['habits']: return UserHabits(habits=[], response=ResponseMessage( text='Belum memiliki habit yang tersimpan', status=False)) habits = [] if len(filter_conditions) > 0: habits = list( mongo.db.habits.find({ '_id': { '$in': user_habits['habits'] }, '$and': filter_conditions }).sort('_id', 1)) for habit in habits: habit_track = mongo.db.habit_tracks.find_one( {'habit_id': habit['_id']}) habit = re_structure_habit_output(habit, habit_track) return UserHabits( _id=user_habits['_id'], user_id=ObjectId(get_jwt_identity()), habits=habits, response=ResponseMessage( text='Berhasil mengembalikan hasil pencarian habit pengguna', status=True))
def mutate(self, info, _id, fields, header_img_upload): if validate_datetime(fields.posted_at, 'date') is False: return UpdateArticle( updated_article=None, response=ResponseMessage( text='Format tanggal tidak valid, artikel gagal diperbarui', status=False)) is_article_title_exist = mongo.db.articles.find_one({ '_id': { '$ne': _id }, 'title': fields.title }) if is_article_title_exist: return UpdateArticle( updated_article=None, response=ResponseMessage( text='Judul sudah terpakai, artikel gagal diperbarui', status=False)) fields['posted_at'] = datetime.datetime.strptime( fields.posted_at, datetime_format('date')) if header_img_upload.filename != 'default': upload_result = cloudinary.uploader.upload(header_img_upload) fields['header_img'] = upload_result['secure_url'] # file_name= formatted_file_name(header_img_upload.filename) # header_img_upload.save(os.path.join(f"{upload_path}/images", file_name)) result = mongo.db.articles.find_one_and_update({'_id': _id}, {'$set': dict(fields)}) if result is None: return UpdateArticle( updated_article=None, response=ResponseMessage( text= 'Terjadi kesalahan pada server, artikel gagal diperbarui', status=False)) updated_article = mongo.db.articles.find_one({'_id': _id}) updated_article['posted_at'] = updated_article['posted_at'].date() # if updated_article['header_img'] != default_img and is_uploaded_file_exist(updated_article['header_img'].split('/')[-1]) is False: # result= mongo.db.articles.update_one( # { '_id': _id }, # { '$set': { 'header_img': default_img } } # ) # if result.modified_count == 0: # return UpdateArticle( # updated_article= None, # response= ResponseMessage(text= 'Terjadi kesalahan pada gambar artikel, artikel gagal diperbarui', status= False) # ) # updated_article['header_img']= default_img return UpdateArticle( updated_article=updated_article, response=ResponseMessage(text='Berhasil membarui artikel', status=True))
def mutate(self, info, fields, header_img_upload): if validate_datetime(fields.posted_at, 'date') is False: return CreateArticle( updated_article=None, response=ResponseMessage( text='Format tanggal tidak valid, artikel gagal terbuat', status=False)) is_article_title_exist = mongo.db.articles.find_one( {'title': fields.title}) if is_article_title_exist: return CreateArticle( updated_article=None, response=ResponseMessage( text='Judul sudah terpakai, artikel gagal terbuat', status=False)) fields = { '_id': get_sequence('articles'), 'title': fields['title'], 'short_summary': fields['short_summary'], 'author': fields['author'], 'posted_at': datetime.datetime.strptime(fields.posted_at, datetime_format('date')), 'reviewed_by': fields['reviewed_by'], 'header_img': default_img, 'content': fields['content'], 'url_name': fields['title'].lower().replace(', ', ' ').replace(' ', '-'), 'url': '' } if header_img_upload.filename != 'default': upload_result = cloudinary.uploader.upload(header_img_upload) fields['header_img'] = upload_result['secure_url'] # file_name= formatted_file_name(header_img_upload.filename) # header_img_upload.save(os.path.join(f"{upload_path}/images", file_name)) result = mongo.db.articles.insert_one(dict(fields)) if result.inserted_id is None: return CreateArticle( updated_article=None, response=ResponseMessage( text='Terjadi kesalahan pada server, artikel gagal terbuat', status=False)) created_article = list( mongo.db.articles.find({}).sort('_id', -1).limit(1))[0] created_article['posted_at'] = created_article['posted_at'].date() return CreateArticle(created_article=created_article, response=ResponseMessage( text='Berhasil menambahkan artikel baru', status=True))
def mutate(self, info, _id, fields): #start validation check if validate_datetime(fields.goal_dates.start, 'date') is False: return UpdateHabit( updated_habit=None, response=ResponseMessage( text= 'Format tanggal dimulai tidak sesuai, habit gagal diperbarui', status=False)) if validate_datetime(fields.goal_dates.end, 'date') is False: return UpdateHabit( updated_habit=None, response=ResponseMessage( text= 'Format tanggal selesai tidak sesuai, habit gagal diperbarui', status=False)) if lesser_comparison_datetime(fields.goal_dates.start, fields.goal_dates.end, 'date') is False: return UpdateHabit( updated_habit=None, response=ResponseMessage( text= 'Tanggal dimulai dan tanggal selesai tidak sesuai, habit gagal diperbarui', status=False)) if fields.reminder_time != '' and validate_datetime( fields.reminder_time, 'time') is False: return UpdateHabit( updated_habit=None, response=ResponseMessage( text= 'Format waktu pengingat tidak sesuai, habit gagal diperbarui', status=False)) is_habit_id_exist_in_user_habits = mongo.db.user_habits.find_one({ 'user_id': ObjectId(get_jwt_identity()), 'habits': _id }) if is_habit_id_exist_in_user_habits is None: return UpdateHabit( updated_habit=None, response=ResponseMessage( text= 'Habit tidak ditemukan pada user_habits collection, habit gagal diperbarui', status=False)) is_habit_id_exist_in_habits = mongo.db.habits.find_one({'_id': _id}) if is_habit_id_exist_in_habits is None: return UpdateHabit( updated_habit=None, response=ResponseMessage( text= 'Habit tidak ditemukan pada habits collection, habit gagal diperbarui', status=False)) #end validation check #start update habit result = mongo.db.habits.find_one_and_update( {'_id': _id}, {'$set': dict(re_structure_habit_input(fields, 'update'))}) if result is None: return UpdateHabit( updated_habit=None, response=ResponseMessage( text='Terjadi kendala pada server, habit gagal diperbarui', status=False)) updated_habit = mongo.db.habits.find_one({'_id': _id}) #end update habit #start update on habit streak logs is_streak_log_exist = mongo.db.habit_tracks.find_one({ 'habit_id': _id, 'streak_logs': { '$elemMatch': { 'start_date': datetime.datetime.strptime(fields.goal_dates.start, datetime_format('date')), #'end_date': datetime.datetime.strptime(fields.goal_dates.end, datetime_format('date')) } } }) #check if streak log exist in array streak_logs if is_streak_log_exist is None: result = mongo.db.habit_tracks.update_one({'habit_id': _id}, { '$push': { 'streak_logs': { 'start_date': datetime.datetime.strptime(fields.goal_dates.start, datetime_format('date')), 'end_date': datetime.datetime.strptime(fields.goal_dates.end, datetime_format('date')), 'current_goal': 0, 'target_goal': fields['goal'], 'last_marked_at': None, 'is_complete': False, 'marked_at': [] } } }) if result.modified_count == 0: return UpdateHabit( updated_habit=None, response=ResponseMessage( text= 'Tidak dapat menambah streak log pada habit_streak_logs, habit gagal diperbarui', status=False)) else: current_log = None total_completed = is_streak_log_exist['total_completed'] for log in is_streak_log_exist['streak_logs']: if log['start_date'] == datetime.datetime.strptime( fields.goal_dates.start, datetime_format('date')): current_log = log if current_log['current_goal'] == updated_habit[ 'goal'] and datetime.datetime.now().date( ) in current_log['marked_at']: total_completed += 1 current_log['is_complete'] = True result = mongo.db.habit_tracks.find_one_and_update( { 'habit_id': updated_habit['_id'], 'total_completed': total_completed, 'streak_logs': { '$elemMatch': { 'start_date': datetime.datetime.strptime(fields.goal_dates.start, datetime_format('date')) } } }, { '$set': { 'streak_logs.$.end_date': datetime.datetime.strptime(fields.goal_dates.end, datetime_format('date')), 'streak_logs.$.target_goal': updated_habit['goal'], 'streak_logs.$.is_complete': current_log['is_complete'] } }) if result is None: return UpdateHabit( updated_habit=None, response=ResponseMessage( text= 'Tidak dapat mengubah streak log pada habit_streak_logs, habit gagal diperbarui', status=False)) habit_track = mongo.db.habit_tracks.find_one({'habit_id': _id}) #end update on habit streak logs return UpdateHabit( updated_habit=re_structure_habit_output(updated_habit, habit_track), response=ResponseMessage(text='Berhasil membarui habit', status=True))
def resolve_get_filtered_user_mood(self, info, filters): filter_conditions = [] if filters.emoticon_name != '': filter_conditions.append({'emoticon.name': filters.emoticon_name}) if filters.parameters.internal is True: filter_conditions.append({ 'parameters.internal': { '$regex': filters.search_text, '$options': 'i' } }) if filters.parameters.external is True: filter_conditions.append({ 'parameters.external': { '$regex': filters.search_text, '$options': 'i' } }) if len(filters.activity_ids) > 0: filter_conditions.append( {'activities._id': { '$all': filters.activity_ids }}) if filters.note is True: filter_conditions.append( {'note': { '$regex': filters.search_text, '$options': 'i' }}) if ((filters.created_date.start != '' and filters.created_date.end != '') and (validate_datetime(filters.created_date.start, 'date') and validate_datetime(filters.created_date.end, 'date'))): filter_conditions.append({ '$and': [{ 'created_at': { '$gte': datetime.datetime.strptime( f'{filters.created_date.start} 23:59', datetime_format('datetime')) } }, { 'created_at': { '$lte': datetime.datetime.strptime( f'{filters.created_date.end} 23:59', datetime_format('datetime')) } }] }) user_moods = mongo.db.user_moods.find_one( {'user_id': ObjectId(get_jwt_identity())}) if user_moods is None or not user_moods['moods']: return UserMoods(moods=[], response=ResponseMessage( text='Belum memiliki mood yang tersimpan', status=False)) moods = [] if len(filter_conditions) > 0: moods = list( mongo.db.moods.find({ '_id': { '$in': user_moods['moods'] }, '$and': filter_conditions }).sort('created_at', -1)) for mood in moods: mood['created_at'] = { 'date': mood['created_at'].date(), 'time': str(mood['created_at'].time())[:-3] } return UserMoods( _id=user_moods['_id'], user_id=ObjectId(get_jwt_identity()), moods=list(moods), response=ResponseMessage( text='Berhasil mengembalikan hasil pencarian mood pengguna', status=True))
def mutate(self, info, fields): #start validation check if validate_datetime(fields.goal_dates.start, 'date') is False: return CreateHabit( created_habit=None, response=ResponseMessage( text= 'Format tanggal dimulai tidak sesuai, habit gagal diperbarui', status=False)) if validate_datetime(fields.goal_dates.end, 'date') is False: return CreateHabit( created_habit=None, response=ResponseMessage( text= 'Format tanggal selesai tidak sesuai, habit gagal diperbarui', status=False)) if lesser_comparison_datetime(fields.goal_dates.start, fields.goal_dates.end, 'date') is False: return CreateHabit( created_habit=None, response=ResponseMessage( text= 'Tanggal dimulai dan tanggal selesai tidak sesuai, habit gagal diperbarui', status=False)) if fields.reminder_time != '' and validate_datetime( fields.reminder_time, 'time') is False: return CreateHabit( created_habit=None, response=ResponseMessage( text= 'Format waktu pengingat tidak sesuai, habit gagal diperbarui', status=False)) #end validation check #start create habit and user habits insert_on_habits = mongo.db.habits.insert_one( dict(re_structure_habit_input(fields))) if insert_on_habits.inserted_id is None: return CreateHabit( created_habit=None, response=ResponseMessage( text= 'Tidak dapat menyimpan pada habits collection, habit gagal ditambahkan', status=False)) is_user_habits_exist = mongo.db.user_habits.find_one( {'user_id': ObjectId(get_jwt_identity())}) #check if user habits exist or not if is_user_habits_exist is None: create_user_habits = mongo.db.user_habits.insert_one({ '_id': get_sequence('user_habits'), 'user_id': ObjectId(get_jwt_identity()), 'habits': [insert_on_habits.inserted_id] }) if create_user_habits.inserted_id is None: return CreateHabit( created_habit=None, response=ResponseMessage( text= 'Tidak dapat membuat user_habits baru, habit gagal ditambahkan', status=False)) else: insert_on_user_habits = mongo.db.user_habits.update_one( {'user_id': ObjectId(get_jwt_identity())}, {'$push': { 'habits': insert_on_habits.inserted_id }}) if insert_on_user_habits.modified_count == 0: return CreateHabit( created_habit=None, response=ResponseMessage( text= 'Tidak dapat menyimpan pada user_habits collection, habit gagal ditambahkan', status=False)) created_habit = mongo.db.habits.find_one( {'_id': insert_on_habits.inserted_id}) #end create habit and user habits #start create habit track result = mongo.db.habit_tracks.insert_one({ 'habit_id': insert_on_habits.inserted_id, 'total_completed': 0, 'total_streaks': 0, 'streak_logs': [{ 'start_date': datetime.datetime.strptime(fields.goal_dates.start, datetime_format('date')), 'end_date': datetime.datetime.strptime(fields.goal_dates.end, datetime_format('date')), 'current_goal': 0, 'target_goal': created_habit['goal'], 'last_marked_at': None, 'is_complete': False, 'marked_at': [] }] }) if result.inserted_id is None: return CreateHabit( created_habit=None, response=ResponseMessage( text= 'Tidak dapat membuat habit track baru, habit gagal ditambahkan', status=False)) created_habit_track = mongo.db.habit_tracks.find_one( {'habit_id': insert_on_habits.inserted_id}) #end create habit streak logs return CreateHabit( created_habit=re_structure_habit_output(created_habit, created_habit_track), response=ResponseMessage(text='Berhasil menambahkan habit baru', status=True))
def mutate(self, info, _id, marked_at): #start validation check #validate date if validate_datetime(marked_at, 'date') is False: return MarkHabitGoal( marked_habit=None, response=ResponseMessage( text= 'Format tanggal tidak sesuai, habit goal gagal ditandai', status=False)) is_habit_id_exist = mongo.db.user_habits.find_one({ 'user_id': ObjectId(get_jwt_identity()), 'habits': _id }) #check habit id exist or not if is_habit_id_exist is None: return MarkHabitGoal( marked_habit=None, response=ResponseMessage( text='Habit tidak ditemukan, habit goal gagal ditandai', status=False)) habit = mongo.db.habits.find_one({'_id': _id}) #check date now still between on goal start and end date date_now = datetime.datetime.strptime(marked_at, datetime_format('date')).date() #if date_now >= habit['goal_dates']['start'].date() and date_now <= habit['goal_dates']['end'].date(): # days_left= (habit['goal_dates']['end'].date() - date_now).days #else: # return MarkHabitGoal( # marked_habit= None, # response= ResponseMessage(text= 'Tanggal tidak sesuai dengan rentang tanggal yang ditentukan, habit goal gagal ditandai', status= False) # ) if date_now < habit['goal_dates']['start'].date( ) or date_now > habit['goal_dates']['end'].date(): return MarkHabitGoal( marked_habit=None, response=ResponseMessage( text= 'Tanggal tidak sesuai dengan rentang tanggal yang ditentukan, habit goal gagal ditandai', status=False)) #end validation check #start mark habit is_already_marked = mongo.db.habit_tracks.find_one({ 'habit_id': _id, 'streak_logs': { '$elemMatch': { 'start_date': habit['goal_dates']['start'], 'last_marked_at': datetime.datetime.strptime(marked_at, datetime_format('date')) } } }) if is_already_marked: return MarkHabitGoal( marked_habit=None, response=ResponseMessage( text='Habit sudah ditandai pada tanggal tersebut', status=False)) else: current_track = mongo.db.habit_tracks.find_one({'habit_id': _id}) current_log = None for log in current_track['streak_logs']: if log['start_date'] == habit['goal_dates']['start']: current_log = log if current_log['current_goal'] + 1 == current_log['target_goal']: current_track['total_completed'] += 1 current_log['is_complete'] = True current_track['total_streaks'] += 1 current_log['current_goal'] += 1 result = mongo.db.habit_tracks.update_one( { 'habit_id': _id, 'streak_logs': { '$elemMatch': { 'start_date': habit['goal_dates']['start'] } } }, { '$set': { 'total_completed': current_track['total_completed'], 'total_streaks': current_track['total_streaks'], 'streak_logs.$.current_goal': current_log['current_goal'], 'streak_logs.$.last_marked_at': datetime.datetime.strptime(marked_at, datetime_format('date')), 'streak_logs.$.is_complete': current_log['is_complete'] }, '$push': { 'streak_logs.$.marked_at': datetime.datetime.strptime(marked_at, datetime_format('date')) } }) if result.modified_count == 0: return MarkHabitGoal( marked_habit=None, response=ResponseMessage( text= 'Tidak dapat menambah marked_at log baru pada habit_tracks, habit goal gagal ditandai', status=False)) habit_track = mongo.db.habit_tracks.find_one({'habit_id': _id}) #end mark habit return MarkHabitGoal( marked_habit=re_structure_habit_output(habit, habit_track), response=ResponseMessage( text=f"Berhasil menandai habit hari ini, tanggal {marked_at}", status=True))