def insert_to_cassandra(self, data, time_now): VacLogDB.insert_data( data['package_id'], data['package_type_id'], data['name'], custom_functions.obj_to_date(data['manufacturing_date'], False), custom_functions.obj_to_date(data['expiry_date'], False), data['manufacturer_info']) from_station_data = eval(data['from_station']) to_station_data = eval(data['to_station']) VacSubLogDB.insert_data( uuid.UUID(data['uuid']), data['package_id'], data['name'], custom_functions.obj_to_date(data['manufacturing_date'], False), custom_functions.obj_to_date(data['expiry_date'], False), data['manufacturer_info'], uuid.UUID(data['previous_uuid']) if data['previous_uuid'] else None, (int(data['dose_count']) - int(data["adjustments"]['doses'])), int(data["adjustments"]['doses']), str(data["adjustments"]['remarks']), data['status'], time_now, str(data['comments']), int(from_station_data['station_id']), from_station_data, int(to_station_data['station_id']), to_station_data) VacTransferLogDB.insert_data(uuid.uuid4(), uuid.UUID(data['uuid']), int(from_station_data['station_id']), from_station_data, int(to_station_data['station_id']), to_station_data, str(data['comments']), str(data["adjustments"]['remarks']), data['user_id'], data['status'], time_now)
def male_female_count(): try: args = request.json log = {} log['request'] = args station_id = args['station_id'] from_str = custom_functions.obj_to_date( args['date_from']).split(" ")[0] to_str = custom_functions.obj_to_date(args['date_to'], extra_day=1).split(" ")[0] select_query = "SELECT beneficiary_id,vaccine_dose_id FROM kba.immunisation_log WHERE \ station_id='{}' AND current_date >= '{}' AND current_date <= '{}' allow filtering;" vaccine_doses = session.query(VaccineDose).all() vd_obj = {} for vd in vaccine_doses: vd_obj[vd.id] = vd.name sub_logs = cassandra_client.session.execute( select_query.format(station_id, from_str, to_str)) result = {} for sub_log in sub_logs: r = session.query(Child).filter( Child.rch_id == sub_log.beneficiary_id).first() if r: if not vd_obj[sub_log.vaccine_dose_id] in result: result[vd_obj[sub_log.vaccine_dose_id]] = {} result[vd_obj[sub_log.vaccine_dose_id]]['male'] = 0 result[vd_obj[sub_log.vaccine_dose_id]]['female'] = 0 result[vd_obj[sub_log.vaccine_dose_id]]['total'] = 0 result[vd_obj[sub_log.vaccine_dose_id]][ 'dose_name'] = vd_obj[sub_log.vaccine_dose_id] result[vd_obj[sub_log.vaccine_dose_id]]['total'] = result[ vd_obj[sub_log.vaccine_dose_id]]['total'] + 1 if r.gender.lower() == 'm': result[vd_obj[sub_log.vaccine_dose_id]]['male'] = result[ vd_obj[sub_log.vaccine_dose_id]]['male'] + 1 elif r.gender.lower() == 'f': result[vd_obj[sub_log.vaccine_dose_id]]['female'] = result[ vd_obj[sub_log.vaccine_dose_id]]['female'] + 1 result_list = list(result.values()) sorted(result_list, key=lambda i: i['dose_name']) if result_list: record = {'status_code': 200, 'data': result_list} else: record = { 'status_code': 404, "status_msg": "No data found.", 'data': result_list } except Exception as e: session.rollback() error_email.send_email({'error': str(e), 'url': request.url}) record = {'status_code': 500, "status_msg": str(e)} log['response'] = record ml_male_female_count.insert_one(log) return jsonify(record)
def beneficiary_report(): try: args = request.json log = {} log['request'] = args station_id = args['station_id'] from_str = custom_functions.obj_to_date( args['date_from']).split(" ")[0] to_str = custom_functions.obj_to_date(args['date_to'], extra_day=1).split(" ")[0] select_query = "SELECT beneficiary_id,vaccine_dose_id FROM kba.immunisation_log WHERE \ station_id='{}' AND current_date >= '{}' AND current_date <= '{}' allow filtering;" vaccine_doses = session.query(VaccineDose).all() vd_obj = {} for vd in vaccine_doses: vd_obj[vd.id] = vd.name sub_logs = cassandra_client.session.execute( select_query.format(station_id, from_str, to_str)) obj = {} for sub_log in sub_logs: r = session.query(Child).filter( Child.rch_id == sub_log.beneficiary_id).first() rch_user = session.query(RCHUser).filter( RCHUser.id == r.rch_user_id).first() if r and rch_user: if not sub_log.beneficiary_id in obj: obj[sub_log.beneficiary_id] = {} obj[sub_log.beneficiary_id]['child_name'] = r.name obj[sub_log.beneficiary_id]['mother_name'] = rch_user.name obj[sub_log. beneficiary_id]['dob'] = custom_functions.date_to_string( r.date_of_birth) obj[sub_log.beneficiary_id]['address'] = rch_user.address obj[sub_log.beneficiary_id]['gender'] = r.gender.upper() obj[sub_log.beneficiary_id]['vaccine'] = vd_obj[ sub_log.vaccine_dose_id] if (not ( 'vaccine' in obj[sub_log.beneficiary_id])) else obj[ sub_log.beneficiary_id]['vaccine'] + ", " + vd_obj[ sub_log.vaccine_dose_id] result_list = list(obj.values()) if result_list: record = {'status_code': 200, 'data': result_list} else: record = { 'status_code': 404, "status_msg": "No data found.", 'data': result_list } except Exception as e: session.rollback() error_email.send_email({'error': str(e), 'url': request.url}) record = {'status_code': 500, "status_msg": str(e)} log['response'] = record ml_beneficiary_report.insert_one(log) return jsonify(record)
def detailed_immunization_register(): try: args = request.json log = {} log['request'] = args station_ids = args['station'] csv = args['csv'] == "y" from_str = custom_functions.obj_to_date( args['date_from']).split(" ")[0] to_str = custom_functions.obj_to_date(args['date_to'], extra_day=1).split(" ")[0] data = {} for station_id in station_ids: sub_select_query = "SELECT beneficiary_id,vaccine_details,beneficiary_details FROM kba.immunisation_log WHERE \ station_id='{}' AND current_date >= '{}' AND current_date <= '{}' allow filtering;" sub_logs = cassandra_client.session.execute( sub_select_query.format(station_id, from_str, to_str)) for sub_log in sub_logs: if sub_log.beneficiary_id in data: data[sub_log.beneficiary_id]['vaccines_given'].append( sub_log.vaccine_details['vaccine_dose_name']) else: if check_filter(args, sub_log): data[sub_log.beneficiary_id] = {} data[sub_log.beneficiary_id][ 'child_name'] = sub_log.beneficiary_details[ 'child_name'] data[sub_log.beneficiary_id][ 'father_name'] = sub_log.beneficiary_details[ 'father_name'] data[sub_log.beneficiary_id][ 'mother_name'] = sub_log.beneficiary_details[ 'mother_name'] data[sub_log.beneficiary_id][ 'address'] = sub_log.beneficiary_details['address'] data[sub_log.beneficiary_id][ 'sex'] = sub_log.beneficiary_details['sex'] if not csv: dat = custom_functions.date_to_string(sub_log.beneficiary_details['date_of_birth'],False) if 'date_of_birth' in sub_log.beneficiary_details else {} else: try: format = custom_functions.date_to_string( sub_log. beneficiary_details['date_of_birth'], False ) if 'date_of_birth' in sub_log.beneficiary_details else { 'dd': "0", 'mm': "0", 'yyyy': "0000" } dat = str(format['dd']) + "/" + str( format['mm']) + "/" + str(format['yyyy']) except: dat = "" data[sub_log.beneficiary_id]['date_of_birth'] = dat data[sub_log.beneficiary_id]['vaccines_given'] = [ sub_log.vaccine_details['vaccine_dose_name'] ] detailed_data = data.values() if csv: file_name = generate_csv(list(detailed_data)) record = { 'status_code': 200, 'status_msg': "Posted successfully", "file_name": file_name } else: list_data = list(detailed_data) if list_data: record = {'status_code': 200, 'data': list_data} else: record = { 'status_code': 404, "status_msg": "No data found.", 'data': list_data } except Exception as e: error_email.send_email({'error': str(e), 'url': request.url}) record = {'status_code': 500, "status_msg": str(e)} log['response'] = record ml_detailed_immunization_register.insert_one(log) return jsonify(record)
def show(): try: args = request.json log = {} log['request'] = args return_data = [] if False: ## TO DO LATER. from_obj = args['date'] from_time = custom_functions.obj_to_date(from_obj) args['date']['HH'] = 23 args['date']['MM'] = 59 to_obj = args['date'] to_time = custom_functions.obj_to_date(to_obj) sub_select_query = "SELECT id,name,dose_count,package_id,manufacturing_date,manufacturer_info,date_time FROM kba.vaccine_sub_log WHERE status='received' \ AND date_time >= '{}' AND date_time <= '{}' \ AND station_id={} allow filtering;" else: sub_select_query = "SELECT * FROM kba.vaccine_sub_log WHERE \ current_station_id={} allow filtering;" for station_id in args['station_id']: station_obj = {} station_obj["station_id"] = station_id station_obj["vaccines"] = {} sub_logs = cassandra_client.session.execute( sub_select_query.format(station_id)) for sub_log in sub_logs: vaccine_name = sub_log.name if vaccine_name in station_obj["vaccines"]: if sub_log.status == "send": station_obj["vaccines"][vaccine_name][ 'transit_count'] = station_obj["vaccines"][ vaccine_name][ 'transit_count'] + sub_log.dose_count else: station_obj["vaccines"][vaccine_name][ 'received_count'] = station_obj["vaccines"][ vaccine_name][ 'received_count'] + sub_log.dose_count count_obj = {} count_obj['count'] = sub_log.dose_count count_obj['vaccine_sub_id'] = str(sub_log.id) count_obj['package_id'] = sub_log.package_id count_obj['previous_station'] = dict( sub_log.previous_station) count_obj[ 'status'] = "In-Transit" if sub_log.status == "send" else "Received" count_obj[ 'date_checked_in'] = custom_functions.date_to_string( sub_log.date_time) count_obj[ 'manufacturing_date'] = custom_functions.date_to_string( sub_log.manufacturing_date) count_obj['expiry_date'] = custom_functions.date_to_string( sub_log.expiry_date) count_obj['manufacturer_info'] = sub_log.manufacturer_info station_obj["vaccines"][vaccine_name]['batches'].append( count_obj) else: station_obj["vaccines"][vaccine_name] = {} if sub_log.status == "send": station_obj["vaccines"][vaccine_name][ 'transit_count'] = sub_log.dose_count station_obj["vaccines"][vaccine_name][ 'received_count'] = 0 else: station_obj["vaccines"][vaccine_name][ 'transit_count'] = 0 station_obj["vaccines"][vaccine_name][ 'received_count'] = sub_log.dose_count station_obj["vaccines"][vaccine_name]['batches'] = [] count_obj = {} count_obj['count'] = sub_log.dose_count count_obj['vaccine_sub_id'] = str(sub_log.id) count_obj['package_id'] = sub_log.package_id count_obj[ 'status'] = "In-Transit" if sub_log.status == "send" else "Received" count_obj['previous_station'] = dict( sub_log.previous_station) count_obj[ 'date_checked_in'] = custom_functions.date_to_string( sub_log.date_time) count_obj[ 'manufacturing_date'] = custom_functions.date_to_string( sub_log.manufacturing_date) count_obj['expiry_date'] = custom_functions.date_to_string( sub_log.expiry_date) count_obj['manufacturer_info'] = sub_log.manufacturer_info if (station_obj["vaccines"][vaccine_name]['transit_count'] + station_obj["vaccines"][vaccine_name] ['received_count']) > 0: station_obj["vaccines"][vaccine_name][ 'batches'].append(count_obj) return_data.append(station_obj) if return_data: record = { 'status_code': 200, 'status_msg': "Posted successfully", "data": return_data } else: record = { 'status_code': 404, 'status_msg': "No records found", "data": [] } except Exception as e: error_email.send_email({'error': str(e), 'url': request.url}) record = {'status_code': 500, "status_msg": str(e)} log['response'] = record ml_station_vaccine_analytics.insert_one(log) return jsonify(record)
def station_vaccination_analytics(): args = request.json log = {} log['request'] = args csv = args['csv'] == "y" from_str = custom_functions.obj_to_date(args['date_from']).split(" ")[0] to_str = custom_functions.obj_to_date(args['date_to'], extra_day=1).split(" ")[0] station_ids = args['station'] vaccine_name = args['vaccine_name'] if 'vaccine_name' in args else None batch_id = args['batch_id'] if 'batch_id' in args else None return_obj = {} main_obj = [] csv_query = "AND name='{}' " if vaccine_name else "" csv_query = csv_query + ("AND package_id='{}' " if batch_id else "") sub_select_query = "SELECT package_id,name,date_rec,beneficiary_no,vaccine_no,station_other FROM kba.batch_immunisation_log WHERE \ station_id='{}' AND date_rec >= '{}' AND date_rec <= '{}' " + csv_query + "allow filtering;" try: for station in station_ids: if vaccine_name: sub_logs = cassandra_client.session.execute( sub_select_query.format(str(station), from_str, to_str, vaccine_name, batch_id)) else: sub_logs = cassandra_client.session.execute( sub_select_query.format(str(station), from_str, to_str, batch_id)) for sub_log in sub_logs: datestr = str(sub_log.date_rec) if sub_log.package_id in return_obj: if datestr in return_obj[sub_log.package_id]: obj = {} obj['batch_id'] = sub_log.package_id obj['vaccine_name'] = sub_log.name if csv: dat = custom_functions.date_to_string( datestr, False) else: try: format = custom_functions.date_to_string( datestr, False) dat = str(format['dd']) + "/" + str( format['mm']) + "/" + str(format['yyyy']) except: dat = "" obj['date_of_administration'] = dat obj['no_of_doses_administered'] = sub_log.vaccine_no obj['no_of_beneficiaries_administered'] = sub_log.beneficiary_no main_obj.append(obj) else: return_obj[sub_log.package_id][datestr] = [] obj = {} obj['batch_id'] = sub_log.package_id obj['vaccine_name'] = sub_log.name if csv: dat = custom_functions.date_to_string( datestr, False) else: try: format = custom_functions.date_to_string( datestr, False) dat = str(format['dd']) + "/" + str( format['mm']) + "/" + str(format['yyyy']) except: dat = "" obj['date_of_administration'] = dat obj['no_of_doses_administered'] = sub_log.vaccine_no obj['no_of_beneficiaries_administered'] = sub_log.beneficiary_no main_obj.append(obj) else: return_obj[sub_log.package_id] = {} return_obj[sub_log.package_id][datestr] = [] obj = {} obj['batch_id'] = sub_log.package_id obj['vaccine_name'] = sub_log.name if not csv: dat = custom_functions.date_to_string(datestr, False) else: try: format = custom_functions.date_to_string( datestr, False) dat = str(format['dd']) + "/" + str( format['mm']) + "/" + str(format['yyyy']) except: dat = "" obj['date_of_administration'] = dat obj['no_of_doses_administered'] = sub_log.vaccine_no obj['no_of_beneficiaries_administered'] = sub_log.beneficiary_no main_obj.append(obj) if main_obj: if csv: file_name = generate_csv(main_obj) record = { 'status_code': 200, 'status_msg': "Posted successfully", "file_name": file_name } else: record = { 'status_code': 200, 'status_msg': "Posted successfully", "data": main_obj } else: record = { 'status_code': 404, 'status_msg': "No records found", "data": [] } except Exception as e: error_email.send_email({'error': str(e), 'url': request.url}) record = {'status_code': 500, "status_msg": str(e)} log['response'] = record ml_station_vaccination_analytics.insert_one(log) return jsonify(record)
def creation(): args = request.json log = {} log['request'] = args if not "phone_no" in args: log['response'] = {"status_code":400, "status_msg": "Bad Request. Phone Number not found."} ml_register_rch_user.insert_one(log) return jsonify({"status_code":400, "status_msg": "Bad Request. Phone Number not found."}) if args["phone_no"] == "": log['response'] = {"status_code": 400, "status_msg": "Bad Request. Phone Number not valid."} ml_register_rch_user.insert_one(log) return jsonify({"status_code":400, "status_msg": "Bad Request. Phone Number not valid."}) try: if "record_unique_id" in args: r = session.query(RCHUser).filter(RCHUser.phone_no_1 == args["phone_no"]) rch_rec_phone = r.count() rch_rec =r.first() if rch_rec_phone > 0 and args['record_unique_id'] != rch_rec.uid: log['response'] ={"status_code":400, "record_unique_id":rch_rec.uid, "status_msg": "Phone number is already taken for another user."} ml_register_rch_user.insert_one(log) return jsonify(log['response']) rch_rec = session.query(RCHUser).filter(RCHUser.uid == args["record_unique_id"]).first() woman_dob = obj_to_date(args["woman_dob"],False) husband_dob = obj_to_date(args["husband_dob"],False) preg_rec = session.query(PregnancyDetail).filter(PregnancyDetail.rch_user_id == rch_rec.id).all() record_pregnancy_ids = [] for p in preg_rec: record_pregnancy_ids.append(p.pregnancy_id) rch_rec.name = args["woman_name"] rch_rec.dob = woman_dob, rch_rec.address = args["address"] rch_rec.phone_no_1 = str(args["phone_no"]) rch_rec.phone_no_2 = args["phone_no_1"] rch_rec.age = args["woman_age"] rch_rec.husband_name = args["husband_name"] rch_rec.husband_dob = husband_dob, rch_rec.husband_age = args["husband_age"] rch_rec.family_reg_no = args["family_registration_number"] rch_rec.mother_education = args["mother_education"] rch_rec.unique_id = args["unique_id"] rch_rec.aadhar_id = args["aadhar_id"] rch_rec.income = args["income"] rch_rec.caste = args["caste"] rch_rec.ec_no = args["ec_no"] rch_rec.apl_bpl = args["apl_bpl"] rch_rec.bank_account_number = args["bank_account_number"] rch_rec.ifsc_code = args["ifsc_code"] rch_rec.category = args["category"] session.commit() record = {'status_code': 200, "woman_name":rch_rec.name,"record_unique_id":rch_rec.uid ,"record_pregnancy_ids":record_pregnancy_ids,"status_msg": "Details have been successfully edited."} else: rec = session.query(User).filter(User.username == str(args["phone_no"])).first() role = session.query(Role).filter(Role.role_name == "rch_user").first() uid = get_random_id() if rec: user = rec else: passwd = create_hash(args["unique_id"]) user=User( username=str(args["phone_no"]), password=passwd, unique_id=uid ) session.add(user) session.commit() user_role = UserRole(role_id=role.id,user_id=user.id) session.add(user_role) session.commit() rch_rec = session.query(RCHUser).filter(RCHUser.user_id == user.id).first() if rch_rec: preg_recs = session.query(PregnancyDetail).filter(PregnancyDetail.rch_user_id == rch_rec.id).all() preg_dates = {} for preg_rec in preg_recs: children = session.query(Child).filter(Child.pregnancy_detail_id == preg_rec.id).all() child_arr = [] for child in children: child_arr.append(child.date_of_birth) child_arr.sort() preg_dates[preg_rec.pregnancy_id] = date_to_string(child_arr[-1]) return jsonify({"status_code":401,"record_unique_id":rch_rec.uid, "pregnancy_dates":preg_dates, "status_msg": "RCH User already exists"}) else: woman_dob = obj_to_date(args["woman_dob"], False) husband_dob = obj_to_date(args["husband_dob"], False) rch_user=RCHUser( user_id = user.id, name = args["woman_name"], dob = woman_dob, address = args["address"], phone_no_1 = str(args["phone_no"]), phone_no_2 = args["phone_no_1"], age = args["woman_age"], husband_name = args["husband_name"], husband_dob = husband_dob, husband_age = args["husband_age"], family_reg_no = args["family_registration_number"], mother_education = args["mother_education"], unique_id = args["unique_id"], aadhar_id = args["aadhar_id"], income = args["income"], uid= uid, caste = args["caste"], ec_no = args["ec_no"], apl_bpl = args["apl_bpl"], bank_account_number = args["bank_account_number"], ifsc_code = args["ifsc_code"], category = args["category"] ) session.add(rch_user) session.commit() record = {'status_code': 200, "woman_name":rch_user.name, "record_unique_id":rch_user.uid ,"status_msg": "Details have been successfully created."} except Exception as e: session.rollback() error_email.send_email({'error':str(e),'url':request.url}) record = {'status_code': 500, "status_msg": str(e)} log['response'] = record ml_register_rch_user.insert_one(log) return jsonify(record)
def create_service_provider(): args = request.json log = {} log['request'] = args if not "record_pregnancy_id" in args: log['response'] = {"status_code":400, "status_msg": "Bad Request. RCH ID not found."} ml_register_service_provider.insert_one(log) return jsonify({"status_code":400, "status_msg": "Bad Request. RCH ID not found."}) if args["record_pregnancy_id"] == "": log['response'] = {"status_code": 400, "status_msg": "Bad Request. RCH ID not valid."} ml_register_service_provider.insert_one(log) return jsonify({"status_code":400, "status_msg": "Bad Request. RCH ID not valid."}) try: if ("record_pregnancy_id" in args) and ("record_service_id" in args): date_of_first_registration =obj_to_date(args["date_of_first_registration"], False) serv_rec = session.query(ServiceProvider).filter(ServiceProvider.id == args["record_service_id"]).first() if serv_rec: serv_rec.health_centre = args["health_centre"] serv_rec.sub_centre = args["sub_centre"] serv_rec.asha = args["asha"] serv_rec.asha_phone = args["asha_phone"] serv_rec.jphn = args["jphn"] serv_rec.jphn_phone = args["jphn_phone"] serv_rec.hospital_for_delivery = args["hospital_for_delivery"] serv_rec.hospital_address = args["hospital_address"] serv_rec.birth_companion = args["birth_companion"] serv_rec.transportation_arrangement = args["transportation_arrangement"] serv_rec.registered_for_pmmvy = False#args["registered_for_pmmvy"] serv_rec.first_financial_aid = False#args["first_financial_aid"] serv_rec.second_financial_aid = False#args["second_financial_aid"] serv_rec.third_financial_aid = False#args["third_financial_aid"] serv_rec.anganwadi_worker = args["anganwadi_worker"] serv_rec.anganwadi_registration_number = args["anganwadi_registration_number"] serv_rec.anganwadi_centre = args["anganwadi_centre"] serv_rec.anganwadi_phone = args["anganwadi_phone"] serv_rec.icds = args["icds"] serv_rec.sub_centre_registration_number = args["sub_centre_registration_number"] serv_rec.date_of_first_registration = date_of_first_registration serv_rec.nearest_station_id = int(args["nearest_station"]["station_id"] if "station_id" in args["nearest_station"] else 0) session.commit() record = {'status_code': 200, "record_service_id":serv_rec.id ,"status_msg": "Successfully updated."} else: jsonify({"status_code":404, "status_msg": "Record Service Provider Not Found."}) else: preg_detail = session.query(PregnancyDetail).filter(PregnancyDetail.pregnancy_id == args["record_pregnancy_id"]).first() if preg_detail: date_of_first_registration =obj_to_date(args["date_of_first_registration"], False) serv_rec = ServiceProvider( pregnancy_detail_id = preg_detail.id, health_centre = args["health_centre"], sub_centre = args["sub_centre"], asha = args["asha"], asha_phone = args["asha_phone"], jphn = args["jphn"], jphn_phone = args["jphn_phone"], hospital_for_delivery = args["hospital_for_delivery"], hospital_address = args["hospital_address"], birth_companion = args["birth_companion"], transportation_arrangement = args["transportation_arrangement"], registered_for_pmmvy = False,#args["registered_for_pmmvy"], first_financial_aid = False,#args["first_financial_aid"], second_financial_aid = False,#args["second_financial_aid"], third_financial_aid = False,#args["third_financial_aid"], anganwadi_worker = args["anganwadi_worker"], anganwadi_registration_number = args["anganwadi_registration_number"], anganwadi_centre = args["anganwadi_centre"], anganwadi_phone = args["anganwadi_phone"], icds = args["icds"], sub_centre_registration_number = args["sub_centre_registration_number"], date_of_first_registration = date_of_first_registration, nearest_station_id = int(args["nearest_station"]["station_id"] if "station_id" in args["nearest_station"] else 0) ) session.add(serv_rec) session.commit() record = {'status_code': 200, "record_service_id":serv_rec.id ,"status_msg": "Successfully created."} except Exception as e: session.rollback() error_email.send_email({'error':str(e),'url':request.url}) record = {'status_code': 500, "status_msg": str(e)} log['response'] = record ml_register_service_provider.insert_one(log) return jsonify(record)
def create_pregnancy(): args = request.json log = {} log['request'] = args if not "record_unique_id" in args: log['response'] = {"status_code":400, "status_msg": "Bad Request. Unique ID not found."} ml_register_pregnancy.insert_one(log) return jsonify({"status_code":400, "status_msg": "Bad Request. Unique ID not found."}) if args["record_unique_id"] == "": log['response'] = {"status_code": 400, "status_msg": "Bad Request. Unique ID not valid."} ml_register_pregnancy.insert_one(log) return jsonify({"status_code":400, "status_msg": "Bad Request. Unique ID is not valid."}) try: if "record_pregnancy_id" in args: preg_rec = session.query(PregnancyDetail).filter(PregnancyDetail.pregnancy_id == args["record_pregnancy_id"]).first() rec = session.query(RCHUser).filter(RCHUser.uid == args["record_unique_id"]).first() menstruation_date = obj_to_date(args["menstruation_date"], False) expected_delivery_date = obj_to_date(args["expected_delivery_date"], False) last_delivery_date = obj_to_date(args["last_delivery_date"], False) serv_rec = session.query(ServiceProvider).filter(ServiceProvider.pregnancy_detail_id == preg_rec.id).first() tt1_date = obj_to_date(args["tt1_date"], False) tt2_date = obj_to_date(args["tt2_date"], False) usg1_date = obj_to_date(args["usg1_date"], False) usg2_date = obj_to_date(args["usg2_date"], False) usg3_date = obj_to_date(args["usg3_date"], False) preg_rec.rch_user_id = rec.id, preg_rec.phone_no=args["phone_no"] preg_rec.drivers_number=args["drivers_number"] preg_rec.menstruation_date=menstruation_date, preg_rec.expected_delivery_date=expected_delivery_date, preg_rec.blood_group=args["blood_group"] preg_rec.last_delivery_date=last_delivery_date, preg_rec.rsby_reg_number=args["rsby_reg_number"] preg_rec.jsy_reg_number=args["jsy_reg_number"] preg_rec.gravida=int(args["gravida"]), preg_rec.para=int(args["para"]), preg_rec.no_of_live_children=int(args["no_of_live_children"]), preg_rec.no_of_abortions=int(args["no_of_abortions"]), preg_rec.tt1_date=tt1_date, preg_rec.tt2_date=tt2_date, preg_rec.usg1_date=usg1_date, preg_rec.usg2_date=usg2_date, preg_rec.usg3_date=usg3_date, preg_rec.important_findings=args["important_findings"] preg_rec.complication_details=args["complication_details"] preg_rec.heart_complications=args["heart_complications"] preg_rec.advice=args["advice"] preg_rec.referrals=args["referrals"] preg_rec.contraceptive_methods_used=args["contraceptive_methods_used"] preg_rec.rh_category=args["rh_category"] preg_rec.previous_delivery=args["previous_delivery"] child_rch_data = [] for child_record in args["child_data"]: if child_record['rch_id']: child_rec = session.query(Child).filter(Child.rch_id == child_record['rch_id'],Child.deleted==False).first() dob = obj_to_date(child_record['dob'], False) child_rec.name = child_record['name'] child_rec.gender = child_record['gender'] child_rec.deleted = True if child_record['deleted'] == "true" else False child_rec.date_of_birth = dob update_beneficiary_immunisation_tracking(child_rec.rch_id,dob) child_rch_data.append(child_rec.rch_id) session.commit() else: dob = obj_to_date(child_record['dob'], False) if child_record['dob'] else datetime.now() child_rec = Child( name=child_record['name'] if child_record['name'] else "Baby" + rec.name, gender=child_record['gender'], pregnancy_detail_id=preg_rec.id, rch_user_id=rec.id, date_of_birth=dob , rch_id = child_record['dup_rch_id'] if 'dup_rch_id' in child_record else "", deleted = True if child_record['deleted'] == "true" else False ) session.add(child_rec) session.commit() create_beneficiary_immunisation_tracking(child_rec.rch_id,dob) child_rch_data.append(child_rec.rch_id) add_to_cassandra(child_rec.rch_id, '3') producer.ProduceBeneficiaryData('Add_Beneficiary', '3', child_rec.rch_id) record = {'status_code': 200, 'woman_name':rec.name , "record_pregnancy_id": preg_rec.pregnancy_id, "record_service_id":serv_rec.id if serv_rec else None , "record_rch_ids": child_rch_data, "status_msg": "Pregnancy edited successfully."} else: rec = session.query(RCHUser).filter(RCHUser.uid == args["record_unique_id"]).first() if rec: menstruation_date = obj_to_date(args["menstruation_date"], False) expected_delivery_date = obj_to_date(args["expected_delivery_date"], False) last_delivery_date = obj_to_date(args["last_delivery_date"], False) tt1_date = obj_to_date(args["tt1_date"], False) tt2_date = obj_to_date(args["tt2_date"], False) usg1_date = obj_to_date(args["usg1_date"], False) usg2_date = obj_to_date(args["usg2_date"], False) usg3_date = obj_to_date(args["usg3_date"], False) preg_rec=PregnancyDetail( rch_user_id = rec.id, phone_no=args["phone_no"], drivers_number=args["drivers_number"], menstruation_date=menstruation_date, expected_delivery_date=expected_delivery_date, blood_group=args["blood_group"], last_delivery_date=last_delivery_date, rsby_reg_number=args["rsby_reg_number"], jsy_reg_number=args["jsy_reg_number"], gravida=int(args["gravida"]), para=int(args["para"]), no_of_live_children=int(args["no_of_live_children"]), no_of_abortions=int(args["no_of_abortions"]), tt1_date=tt1_date, tt2_date=tt2_date, usg1_date=usg1_date, usg2_date=usg2_date, usg3_date=usg3_date, important_findings=args["important_findings"], complication_details=args["complication_details"], heart_complications=args["heart_complications"], advice=args["advice"], referrals=args["referrals"], contraceptive_methods_used=args["contraceptive_methods_used"], rh_category=args["rh_category"], previous_delivery=args["previous_delivery"], pregnancy_id=args["pregnancy_id"] if "pregnancy_id" in args else "" ) session.add(preg_rec) session.commit() child_rch_data = [] if args["child_data"]: for child_record in args["child_data"]: dob = obj_to_date(child_record['dob'], False) if child_record['dob'] else datetime.now() child_rec = Child( name=child_record['name'] if child_record['name'] else "Baby" + rec.name, gender=child_record['gender'], pregnancy_detail_id=preg_rec.id, rch_user_id=rec.id, deleted = True if child_record['deleted'] == "true" else False, rch_id = child_record['dup_rch_id'] if 'dup_rch_id' in child_record else "", date_of_birth=dob ) session.add(child_rec) session.commit() create_beneficiary_immunisation_tracking(child_rec.rch_id,dob) child_rch_data.append(child_rec.rch_id) add_to_cassandra(child_rec.rch_id, '3'); producer.ProduceBeneficiaryData('Add_Beneficiary', '3', child_rec.rch_id) else: child_rec = Child( name= "Baby" + rec.name, gender= "m", pregnancy_detail_id= preg_rec.id, rch_user_id= rec.id, rch_id = "", date_of_birth= datetime.now() ) session.add(child_rec) session.commit() create_beneficiary_immunisation_tracking(child_rec.rch_id,datetime.now()) child_rch_data.append(child_rec.rch_id) add_to_cassandra(child_rec.rch_id, '3'); producer.ProduceBeneficiaryData('Add_Beneficiary', '3', child_rec.rch_id) record = {'status_code': 200,'woman_name':rec.name ,"record_pregnancy_id": preg_rec.pregnancy_id,"record_rch_ids":child_rch_data ,"status_msg": "Pregnancy created Successfully."} except Exception as e: session.rollback() error_email.send_email({'error':str(e),'url':request.url}) record = {'status_code': 500, "status_msg": str(e)} log['response'] = record ml_register_pregnancy.insert_one(log) return jsonify(record)
def post(self): """ Documentation Params: Specified below. Returns: JSON dict Sample Request: requests.post(url='http://192.168.1.22:5000/api/immunization', params={"beneficiary_id":"8992KOKOK","batch_id":"34232DDW","batch_type_id":"qqq","beneficiary_type_id":"898HBBJ","station_id":"werwer1113","medicine_id":"2","vile_image":"base encoded string"}) """ parser = reqparse.RequestParser() parser.add_argument('Age', type=dict, required=True, help="vaccination_dict") parser.add_argument('edited', type=dict, required=True, help="discarded_dict") parser.add_argument('BeneficiaryId', type=str, required=True, help="benefeciary id") parser.add_argument('nextDate', type=dict, required=True, help="next date") parser.add_argument('BeneficiaryIdType', type=str, required=True, help="beneficiary type not defined") parser.add_argument('station_other', type=dict, required=True) parser.add_argument('GeoLocation', type=dict,required=True, help="geo location not detailed") parser.add_argument('currentDate', type=dict) ''' parser.add_argument('comment', type=str,required=False) ''' args = parser.parse_args() fields = "(id,vaccine_id, vaccine_dose_id, current_date, next_date, beneficiary_id, beneficiary_details,vaccine_details,beneficiary_type, age, station_id, station_other, geo_location)" try: log = {} log['request'] = args age_object = {} age_vaccine_data = args["Age"] ages = age_vaccine_data.keys() child_rec = session.query(Child).filter(Child.rch_id == args["BeneficiaryId"]).first() rch_user = session.query(RCHUser).filter(RCHUser.id == child_rec.rch_user_id).first() if bool(args["currentDate"]): current_time = custom_functions.obj_to_date(args["currentDate"],False) else: current_time = datetime.now() if bool(args["nextDate"]): nd = custom_functions.obj_to_date(args["nextDate"]['date'],False) else: nd = None if not bool(args['station_other']): args['station_other'] = call_et() if args["edited"].keys(): self.discard_taken_vaccination(args["edited"],args['BeneficiaryId'],args["station_other"]) if child_rec: cassandra_client.set_table("immunisation_log",fields) for age in ages: age_object[age] = {} vaccines = age_vaccine_data[age] vaccines_keys = vaccines.keys() for vaccine_name in vaccines_keys: vaccine_object = vaccines[vaccine_name] if bool(vaccine_object): vaccine_id = vaccine_object["vaccine_package_id"] if "vaccine_package_id" in vaccine_object else None vd = session.query(VaccineDose).filter(VaccineDose.name == vaccine_name).first() vacc_exists = session.query(Vaccination) \ .filter(Vaccination.beneficiary_id==args["BeneficiaryId"]) \ .filter(Vaccination.vaccine_batch_id==vaccine_id)\ .filter(Vaccination.vaccine_dose_id==vd.id).first() if vacc_exists: continue if bool(args["currentDate"]) and not vaccine_id: vaccine_id = "ExternalPackageID" vaccine_current_date = str(current_time) vaccine_next_date = vaccine_object["next_date"] if "next_date" in vaccine_object else "" age_object[age][vaccine_name] ={} mv = session.query(MissedVaccination) \ .filter(MissedVaccination.beneficiary_id == args["BeneficiaryId"]) \ .filter(MissedVaccination.vaccine_dose_id == vd.id) \ .filter(MissedVaccination.age == age) if vaccine_id: beneficiary_details = {} beneficiary_details['child_name'] = child_rec.name beneficiary_details['mother_name'] = rch_user.name beneficiary_details['date_of_birth'] = child_rec.date_of_birth.strftime("%Y-%m-%d %H:%M:%S") beneficiary_details['father_name'] = rch_user.husband_name beneficiary_details['address'] = rch_user.address beneficiary_details['sex'] = child_rec.gender vaccine_details = {} vac = vd.vaccine vaccine_details['vaccine_id'] = str(vac.id) vaccine_details['vaccine_name'] = vac.name vaccine_details['vaccine_dose_id'] = str(vd.id) vaccine_details['vaccine_dose_name'] = vd.name age_object[age][vaccine_name]['vaccine_id'] = vac.id age_object[age][vaccine_name]['vaccine_name'] = vac.name age_object[age][vaccine_name]['vaccine_dose_id'] = vd.id age_object[age][vaccine_name]['vaccine_dose_name'] = vd.name age_object[age][vaccine_name]['package_id'] = vaccine_id age_object[age][vaccine_name]['vaccination_date'] = current_time.strftime("%Y-%m-%d") cassandra_client.insert_data(uuid.uuid4(), str(vaccine_id), vd.id, vaccine_current_date, \ vaccine_next_date, args["BeneficiaryId"],beneficiary_details,\ vaccine_details, args["BeneficiaryIdType"], age, str(args["station_other"]['station_id']), \ eval(json.dumps(args["station_other"])),args["GeoLocation"]) mvd = mv.filter(MissedVaccination.active == True).first() if mvd: mvd.active = False session.add(mvd) session.commit() v = Vaccination( beneficiary_id=args["BeneficiaryId"], beneficiary_id_type =args["BeneficiaryIdType"], age =age, vaccine_batch_id = vaccine_id, current_date=current_time, next_date= nd, station_id = int(args["station_other"]['station_id']), vaccine_dose_id = vd.id) session.add(v) session.commit() else: v = session.query(Vaccination) \ .filter(Vaccination.beneficiary_id==args["BeneficiaryId"]) \ .filter(Vaccination.age ==age) \ .filter(Vaccination.vaccine_dose_id == vd.id) if not v.first(): mv = MissedVaccination( beneficiary_id=args["BeneficiaryId"], beneficiary_id_type =args["BeneficiaryIdType"], age=age, reason = vaccine_object["reason"] if "reason" in vaccine_object and vaccine_object['reason'] else "Automated Reason", current_date=current_time, next_date= nd, station_id = int(args["station_other"]['station_id']), vaccine_dose_id = vd.id) nxt = custom_functions.obj_to_date(vaccine_object["next_vaccine_date"],False) age_object[age][vaccine_name]['expected_date'] = nxt.strftime("%Y-%m-%d") session.add(mv) session.commit() if "vaccine_batch_id" in vaccine_object and vaccine_object['vaccine_batch_id']:#.replace('{"','{').replace(', "',',').replace('":',':') beneficiary_dict = {"beneficiary_id":args["BeneficiaryId"],"vaccine_dose_id":vd.id,"age":age,"time_rec":current_time.strftime("%H:%M:%S")} vaccine_dict = {"vaccine_id":str(vaccine_object["vaccine_batch_id"]),"time_rec":current_time.strftime("%H:%M:%S")} batch_imm_log = "UPDATE kba.batch_immunisation_log SET name='{}', \ beneficiary_no={}, vaccine_no={}, station_other={}, \ beneficiary_list=beneficiary_list+[{}], vaccine_list=vaccine_list+[{}] \ WHERE package_id='{}' AND date_rec='{}' AND station_id='{}';" vaccine_sub_log_rec = cassandra_client.session.execute("SELECT beneficiary_no,vaccine_no FROM kba.batch_immunisation_log WHERE package_id='{}' AND date_rec='{}' AND station_id='{}';"\ .format(vaccine_id, current_time.strftime("%Y-%m-%d"), args["station_other"]['station_id'])) if vaccine_sub_log_rec: beneficiary_no = vaccine_sub_log_rec[0].beneficiary_no + 1 vaccine_no = vaccine_sub_log_rec[0].vaccine_no + 1 else: beneficiary_no = 1 vaccine_no = 1 beneficiary_obj_replica = json.dumps(beneficiary_dict).replace('{"','{').replace(', "',',').replace('":',':').replace('"',"'") vaccine_obj_replica = json.dumps(vaccine_dict).replace('{"','{').replace(', "',',').replace('":',':').replace('"',"'") vaccine_sub_log_rec = cassandra_client.session.execute('SELECT * FROM kba.vaccine_sub_log WHERE id='+str(vaccine_object["vaccine_batch_id"])+';') new_count = vaccine_sub_log_rec[0].dose_count - 1 cassandra_client.session.execute('UPDATE kba.vaccine_sub_log SET dose_count ='+str(new_count)+' WHERE id='+str(vaccine_object["vaccine_batch_id"])+';') cassandra_client.session.execute(batch_imm_log.format(vd.vaccine.name,str(beneficiary_no),str(vaccine_no),\ eval(json.dumps(args["station_other"])), beneficiary_obj_replica, vaccine_obj_replica\ ,vaccine_id, current_time.strftime("%Y-%m-%d"), args["station_other"]['station_id'])) self.update_beneficiary_immunisation_tracking(child_rec.rch_id, age_object,args["nextDate"]) record = {'status_code': 200,'status_msg': "API is successfully posted."} else: record = {'status_code': 404,'status_msg': "Child Record Not found."} except Exception as e: error_email.send_email({'error':str(e),'url':'/immunization/post'}) record = {'status_code': 500, "status_msg": str(e)} log['response'] = record ml_immunisation_post.insert_one(log) return record