def delete_fb_tasks(sender, instance, **kwargs): """ Remove entry from '/prescriptions', '/schedules', 'waiting_patient' and 'archived' Google Realtime Database (Firebase) endpoints when a Prescription is deleted Concierge screens: 'Prescrição', 'Elegibilidade', 'Aguardando Paciente', 'Arquivados' respectively :param sender: :param instance: :param kwargs: :return: """ try: import pyrebase firebase = pyrebase.initialize_app(settings.FB_CONFIG) db = firebase.database() for root in ['prescriptions', 'schedules', 'waiting_patient', 'archived']: if root == 'prescriptions': grouped_key = grouped_exams_by_lab_date_keygen(instance) db.child(root).child(grouped_key).child(instance.pk).remove() clear_empty_firebase_node(grouped_key, root, db) else:db.child(root).child(instance.pk).remove() except Exception as e: traceback.print_tb(e.__traceback__) log.error("Unable to delete prescription from firebase MedicalPrescription: %s" % instance.pk)
def delete_fb_scheduled_exams_tasks(sender, instance, **kwargs): """ Remove entry from '/preregister', '/canceled', 'waiting_patient' and 'archived' Google Realtime Database (Firebase) endpoints when a ScheduledExam is deleted Concierge screens: 'Abertura de Ficha', 'Cancelados', 'Aguardando Paciente' and 'Arquivados' respectively :param sender: :param instance: :param kwargs: :return: """ try: import pyrebase firebase = pyrebase.initialize_app(settings.FB_CONFIG) db = firebase.database() grouped_key = grouped_exams_by_lab_date_keygen(instance) db.child('preregister').child(grouped_key).remove() clear_empty_firebase_node(grouped_key, 'preregister', db) db.child('canceled').child(instance.pk).remove() db.child('waiting_patient').child(instance.prescription.pk).child('exams').child(instance.pk).remove() db.child('archived').child(instance.prescription.pk).child('exams').child(instance.pk).remove() except Exception as e: traceback.print_tb(e.__traceback__) log.error("Unable to delete exams from firebase ScheduledExam: %s" % instance.pk)
def remove_nested_nodes_from_expired_prescription_piece(prescription_piece): """ Removes all nested nodes when a prescription piece expires :param prescription_piece: :return: """ # Update exams status and remove firebase nodes: exams_to_expire = prescription_piece.scheduled_exams.all().exclude(status__in=ScheduledExam.ATTENDED_SCHEDULED_EXAMS) if not exams_to_expire: return exams_to_expire.update(status=ScheduledExam.EXAM_EXPIRED) import pyrebase firebase = pyrebase.initialize_app(settings.FB_CONFIG) db = firebase.database() group = grouped_exams_by_lab_date_keygen(exams_to_expire[0]) db.child('preregister').child(group).remove() for i in exams_to_expire: create_week_scheduling(i)
def handle(self, *args, **options): try: import pyrebase firebase = pyrebase.initialize_app(settings.FB_CONFIG) db = firebase.database() scheduled_exams = ScheduledExam.objects.filter( status=ScheduledExam.EXAM_TIME_SCHEDULED) for instance in scheduled_exams: exam_scheduled_time = instance.scheduled_time group_key = grouped_exams_by_lab_date_keygen(instance) existing_data = db.child('preregister').child( group_key).get().val() if existing_data and exam_scheduled_time: exam_scheduled_timestamp = int( exam_scheduled_time.timestamp()) current_scheduled_time = db.child('preregister').child( group_key).child('scheduledTime').get().val() if not current_scheduled_time or exam_scheduled_timestamp < current_scheduled_time: db.child('preregister').child(group_key).child( 'scheduledTime').set(exam_scheduled_timestamp) except Exception as e: print( "Unable to sync with firebase from signals ('preregister'): {0}" .format(e))
def group(self, request, groupid, *args, **kwargs): """ Return all the exams in a group :param request: :param args: :param kwargs: :return: """ try: d, user, lab = grouped_exams_by_lab_date_keygen(groupid, 'decode') except: return Response( { "detail": "No group found", "status_code": status.HTTP_404_NOT_FOUND }, status=status.HTTP_404_NOT_FOUND) try: queryset = domain_models.MedicalPrescription.objects.filter( scheduledexam__scheduled_time__date=d, patient_id=user, scheduledexam__laboratory_id=lab)[0] serializer = PreregisterPrescriptionSerializer(queryset) return Response(serializer.data) except Exception as exc: return Response( { "detail": str(exc), "status_code": status.HTTP_400_BAD_REQUEST }, status=status.HTTP_400_BAD_REQUEST)
def sync_prescription_to_firebase_after_async_upload(instance, **kwargs): """ Sync Prescription data to Google Realtime Database (Firebase) on endpoints 'prescriptions' only after the images async uploading process is done. This is called by the async celery task domain.tasks.create_images Concierge screens: 'Prescrição' :param instance: :param kwargs: :return: """ if settings.APP_ENVIRONMENT in (settings.CI, ): return try: import pyrebase firebase = pyrebase.initialize_app(settings.FB_CONFIG) db = firebase.database() insurance_company_name = "Não definido" if instance.insurance_company: insurance_company_name = instance.insurance_company.name selfie = None if bool(instance.patient.selfie_uploadcare) or bool(instance.patient.selfie): try: selfie = instance.patient.selfie_uploadcare.url except (AttributeError, ValueError): selfie = instance.patient.selfie.url fb_data = { "avatar": selfie, "insurancePlan": insurance_company_name, "key": instance.pk, "name": instance.patient.full_name, "prefferedLabs": [str(lab) for lab in instance.patient.preferred_laboratories.all()], "createdAt": int(instance.created.timestamp()), } group_key = grouped_exams_by_lab_date_keygen(instance) if instance.status == MedicalPrescription.PATIENT_REQUESTED: db.child('prescriptions').child(group_key).child(instance.pk).set(fb_data) except Exception as e: traceback.print_tb(e.__traceback__) print(e) log.error("Unable to sync with firebase from signals %s - %s" % (instance.pk, instance.status))
def group(self, request, groupid, *args, **kwargs): """ Return all the exams in a group :param request: :param args: :param kwargs: :return: """ try: d, user, lab = grouped_exams_by_lab_date_keygen(groupid, 'decode') except: return Response( { "detail": "No group found", "status_code": status.HTTP_404_NOT_FOUND }, status=status.HTTP_404_NOT_FOUND) try: exams = domain_models.ScheduledExam.objects.filter( scheduled_time__date=d, prescription__patient_id=user, laboratory_id=lab, status=domain_models.ScheduledExam.EXAM_TIME_SCHEDULED ).order_by('scheduled_time') serializer = GroupStatusScheduledExamSerializer(exams, many=True) return Response(serializer.data) except Exception as exc: return Response( { "detail": str(exc), "status_code": status.HTTP_400_BAD_REQUEST }, status=status.HTTP_400_BAD_REQUEST)
def sync_scheduled_exams_to_firebase(sender, instance, created, **kwargs): """ Sync Scheduled Exams data to Google Realtime Database (Firebase) on endpoints 'preregister' and 'canceled' Concierge screens: 'Abertura de Ficha' and 'Cancelados', respectively :param sender: :param instance: :param created: :param kwargs: :return: """ try: if not created and instance.status == instance._ScheduledExam__original_status: log.warning('Missed {} {} '.format(created, instance.status)) return import pyrebase firebase = pyrebase.initialize_app(settings.FB_CONFIG) db = firebase.database() insurance_company_name = "Não definido" if instance.prescription.insurance_company: insurance_company_name = instance.prescription.insurance_company.name selfie = None if bool(instance.prescription.patient.selfie_uploadcare) or bool(instance.prescription.patient.selfie): try: selfie = instance.prescription.patient.selfie_uploadcare.url except (AttributeError, ValueError): selfie = instance.prescription.patient.selfie.url group_key = grouped_exams_by_lab_date_keygen(instance) fb_root = 'preregister' current_scheduled_time = db.child(fb_root).child(group_key).child('scheduledTime').get().val() fb_data = { "avatar": selfie, "insurancePlan": insurance_company_name, "key": group_key, "name": instance.prescription.patient.full_name, "prefferedLabs": [str(lab) for lab in instance.prescription.patient.preferred_laboratories.all()], "patientId": instance.prescription.patient.user.id, "prescriptionId": instance.prescription.id, "examsIds": [], "scheduledTime": current_scheduled_time if current_scheduled_time else None } current_data = db.child(fb_root).child(group_key).get().val() if not current_data: current_data = {} new_ids = current_data.get('examIds', []) log.warning(group_key) if instance.status == ScheduledExam.EXAM_TIME_SCHEDULED: fb_root = 'preregister' exam_scheduled_time = int(instance.scheduled_time.timestamp()) if instance.scheduled_time else None lab_name = instance.laboratory.description if instance.laboratory else settings.NOT_FOUND fb_data.update({"labName": lab_name}) if not current_scheduled_time or exam_scheduled_time < current_scheduled_time: fb_data.update({ "scheduledTime": exam_scheduled_time }) if not current_data: db.child(fb_root).child(group_key).set(fb_data) new_ids.append(instance.pk) db.child(fb_root).child(group_key).set(fb_data) db.child(fb_root).child(group_key).child('examIds').set(new_ids) elif instance.status == ScheduledExam.PATIENT_CANCELED: fb_data = { "avatar": selfie, "insurancePlan": insurance_company_name, "key": instance.pk, "name": instance.prescription.patient.full_name, "prefferedLabs": [str(lab) for lab in instance.prescription.patient.preferred_laboratories.all()], "patientId": instance.prescription.patient.user.id, "prescriptionId": instance.prescription.id, } # In "Cancelados" tab, only show exams that are scheduled by phone if not instance.exam.is_scheduled_by_phone: # new_ids.remove(instance.pk) remove_exam_from_firebase_node(db, new_ids, group_key, instance) log.warn('Current canceled exam is not scheduled by phone, aborting fb insertion %s - %s' % (instance.pk, instance.status)) return db.child('canceled').child(instance.pk).remove() # new_ids.remove(instance.pk) remove_exam_from_firebase_node(db, new_ids, group_key, instance) db.child('canceled').child(instance.pk).set(fb_data) return elif instance.status == ScheduledExam.EXAM_EXPIRED: remove_exam_from_firebase_node(db, new_ids, group_key, instance) return else: log.warning('Unable to define the right root for firebase tasks %s - %s' % (instance.pk, instance.status)) db.child('canceled').child(instance.pk).remove() db.child('preregister').child(group_key).remove() return except Exception as e: traceback.print_tb(e.__traceback__) log.error("Unable to sync with firebase from signals %s - %s" % (instance.pk, instance.status))
def sync_prescription_to_firebase(sender, instance, created, **kwargs): """ Sync Prescription data to Google Realtime Database (Firebase) on endpoints 'prescriptions' and 'schedules', Concierge screens: 'Prescrição' and 'Elegibilidade', respectively :param sender: :param instance: :param created: :param kwargs: :return: """ try: # if not created and instance.status == instance._MedicalPrescription__original_status: # return import pyrebase firebase = pyrebase.initialize_app(settings.FB_CONFIG) db = firebase.database() insurance_company_name = "Não definido" grouped_exams = grouped_exams_by_lab_date_keygen(instance) if instance.insurance_company: insurance_company_name = instance.insurance_company.name selfie = None if bool(instance.patient.selfie_uploadcare) or bool(instance.patient.selfie): try: selfie = instance.patient.selfie_uploadcare.url except (AttributeError, ValueError): selfie = instance.patient.selfie.url fb_data = { "avatar": selfie, "insurancePlan": insurance_company_name, "key": instance.pk, "name": instance.patient.full_name, "prefferedLabs": [str(lab) for lab in instance.patient.preferred_laboratories.all()], "createdAt": int(instance.created.timestamp()), } if instance.status in ( MedicalPrescription.UNREADABLE_PICTURES, MedicalPrescription.PICTURES_ID_SELFIE_DONT_MATCH, MedicalPrescription.PACKAGE_REJECTED, MedicalPrescription.PATIENT_CANCELED_BY_CALL, MedicalPrescription.INVALID_HEALDH_CARD_PICTURE, MedicalPrescription.INVALID_ID_PICTURE, MedicalPrescription.NOT_A_PRESCRIPTION, MedicalPrescription.PROCEDURES_NOT_COVERED, MedicalPrescription.PICTURES_HEALTHCARD_ID_DONT_MATCH ): db.child('prescriptions').child(instance.pk).remove() elif instance.status in (MedicalPrescription.EXAMS_IDENTIFIED, MedicalPrescription.NOT_REGISTERED_EXAMS_FOUND): scheduled_exams = ScheduledExam.objects.filter( prescription_piece__prescription__pk=instance.pk, status=ScheduledExam.EXAM_IDENTIFIED).all() expiration_date = int(instance.expiration_date.timestamp()) if instance.expiration_date else None db.child('prescriptions').child(instance.pk).remove() if scheduled_exams.exists(): fb_data.update({ "willExpire": True if expiration_date else False, "expirationDate": expiration_date, "exams": [scheduled_exam.exam.description for scheduled_exam in scheduled_exams] }) db.child('schedules').child(instance.pk).set(fb_data) elif instance.status == MedicalPrescription.EXAMS_ANALYZED: db.child('schedules').child(instance.pk).remove() elif instance.status == MedicalPrescription.REQUEST_EXPIRED: remove_nested_nodes_from_expired_prescription(instance, db) except Exception as e: traceback.print_tb(e.__traceback__) print(e) log.error("Unable to sync with firebase from signals %s - %s" % (instance.pk, instance.status))
def handle(self, *args, **options): try: import pyrebase firebase = pyrebase.initialize_app(settings.FB_CONFIG) db = firebase.database() scheduled_exams = ScheduledExam.objects.filter( status=ScheduledExam.EXAM_TIME_SCHEDULED) insurance_company_name = "Não definido" for instance in scheduled_exams: if instance.prescription.insurance_company: insurance_company_name = instance.prescription.insurance_company.name selfie = None if bool(instance.prescription.patient.selfie_uploadcare ) or bool(instance.prescription.patient.selfie): try: selfie = instance.prescription.patient.selfie_uploadcare.url except (AttributeError, ValueError): selfie = instance.prescription.patient.selfie.url group_key = grouped_exams_by_lab_date_keygen(instance) fb_root = 'preregister' # current_data = db.child(fb_root).child(group_key).get().val() if not current_data: current_data = {} new_ids = current_data.get('examIds', []) fb_data = { "avatar": selfie, "insurancePlan": insurance_company_name, "key": group_key, "name": instance.prescription.patient.full_name, "prefferedLabs": [ str(lab) for lab in instance.prescription.patient. preferred_laboratories.all() ], "patientId": instance.prescription.patient.user.id, "prescriptionId": instance.prescription.id, 'examsIds': [] } exam_scheduled_time = int(instance.scheduled_time.timestamp( )) if instance.scheduled_time else None lab_name = instance.laboratory.description if instance.laboratory else settings.NOT_FOUND fb_data.update({"labName": lab_name}) if exam_scheduled_time: fb_data.update({"scheduledTime": exam_scheduled_time}) db.child(fb_root).child(instance.pk).remove() if not current_data: db.child(fb_root).child(group_key).set(fb_data) if instance.pk not in new_ids: new_ids.append(instance.pk) db.child(fb_root).child(group_key).child('examIds').set( new_ids) print("Update successfully done!") except Exception as e: print( "Unable to sync with firebase from signals ('preregister'): {0}" .format(e))