Exemplo n.º 1
0
    def read(self, **query):
        
        if 'data_inserimento' in query.keys():
            if isinstance(query['data_inserimento'], unicode):
                query['data_inserimento'] = date_from_json(query['data_inserimento'])

                
        if 'id_patient' in query.keys():
            query['id_patient'] = self._get_patient(str(query['id_patient']))
            
            
        if 'id_examination' in query.keys():
            query['id'] = query.pop('id_examination')
        
        if query != {}:
            logger.debug(query)
        
        examination = Examination.objects(**query)
        
        if examination.count() == 0:
            message = Message(ExaminationNoRecordHeader(),
                              data=examination)
            return message
        
        
        message = Message(ExaminationCorrectHeader(),
                          data=examination)
        return message
Exemplo n.º 2
0
    def update(self, **query):

        # Check if a patient has been selected
        if self._currentPatient is None:
            # Get the id from query
            if 'id_patient' in query.keys():
                _ = self._get_patient(str(query['id_patient']))

        patient = self._currentPatient

        if 'birthdate' in query.keys():
            query['birthdate'] = parse_date(query['birthdate'])
            logger.debug(query['birthdate'])

        if '_id' in query.keys():
            _ = query.pop('_id')

        # Try to modify
        if not patient.modify(**query):
            message = Message(PatientErrorHeader(message='Error in modifying'))
            logger.error(message.header.message)
            return message

        # Try to save
        try:
            patient.save()
        except NotUniqueError, err:
            message = Message(
                PatientErrorHeader(message=err.message, user=self.user))
            logger.error(message.header.message)
            return message
Exemplo n.º 3
0
    def create(self, **query):

        # TODO: Check fields if they're correct!

        if 'birthdate' in query.keys():
            query['birthdate'] = datetime.strptime(query['birthdate'],
                                                   "%Y-%m-%dT%H:%M:%S.%fZ")

        patient = Patient(**query)
        try:
            patient.save()
        except (FieldDoesNotExist, NotUniqueError, SaveConditionError) as err:

            message = Message(PatientErrorHeader(message=err.message))
            logger.error(err.message)

            return message

        patient = self._get_patient(patient.id_patient)
        self._currentPatient = patient.first()

        message = Message(
            PatientCorrectHeader(message='Patient correctly created!'),
            data=patient)

        return message
Exemplo n.º 4
0
    def delete(self, **query):

        # Cancellare il report
        report = Report.objects(**query)
        #report = db_wrapper.query('report', **query)

        if report.count() == 0:
            message = Message(
                ReportErrorHeader(message="No Reports in database"),
                data=report)
            return message

        report = report.first()

        e_controller = ExaminationController(user=self.user)
        for ex_ in report.id_examination:
            if ex_.status_name != 'closed':
                _ = e_controller.eject(id=str(ex_.id))
            else:
                message = Message(
                    ReportErrorHeader(message='Cannot delete the report'))
                return message

        try:
            report.delete()
        except Exception, err:
            message = Message(ReportErrorHeader(message="Error in deleting"),
                              data=report)
            return message
Exemplo n.º 5
0
    def _check_examination(self, list_id_examinations):

        if len(list_id_examinations) == 0:
            message = "No examination"
            return Message(ReportErrorHeader(message=message), data=None)

        examination_list = Examination.objects(id__in=list_id_examinations)

        patient_list = []
        data_examination = []
        status_list = []

        for e in examination_list:
            patient_list.append(e.id_patient.id)
            data_examination.append(e.data_inserimento)
            status_list.append(e.status_name)

        if len(np.unique(patient_list)) > 1:
            message = "Examinations are from different patient"
            logger.debug(np.unique(patient_list))
            return Message(ReportErrorHeader(message=message), data=None)

        if len(np.unique(data_examination)) > 1:
            message = "Examinations are from different date"
            logger.debug(np.unique(data_examination))
            return Message(ReportErrorHeader(message=message), data=None)

        if 'closed' in status_list:
            message = "Examinations are already reported"
            logger.debug(np.unique(status_list))
            return Message(ReportErrorHeader(message=message), data=None)

        return examination_list
Exemplo n.º 6
0
    def update(self, **query):

        query['user'] = self.user

        if 'id_examination' in query.keys():
            _ = query.pop('id_examination')

        query = self._check_fields(query)

        if isinstance(query, Message):
            return query

        logger.debug(query)

        action = query.pop('action')
        user = query.pop('user')
        id_report = query.pop('id')

        report = self._get_report(id_report).first()

        if isinstance(report, Message):
            return report

        if report.status_name == 'closed':
            message = "The report is closed"
            return Message(ReportErrorHeader(message=message), data=None)

        if not report.modify(**query):
            message = Message(ReportErrorHeader(message='Error in modifying'))
            logger.error(message.header.message)
            return message

        message = self._update_log(user, action, report)

        if message != None:
            return message

        # Porto gli esami a closed
        e_controller = ExaminationController(user=self.user)
        for ex_ in report.id_examination:
            if ex_.status_name == 'closed':
                break
            _ = e_controller.close(id=str(ex_.id))

        self._currentReport = report
        report = Report.objects(id=str(id_report))
        #report = db_wrapper.query('report', **query)
        message = "Report correctly updated"
        message = Message(ReportCorrectHeader(message=message), data=report)

        return message
Exemplo n.º 7
0
    def _check_fields(self, query):

        for key in query.keys():

            if key == 'user':

                if isinstance(query[key], User):
                    user = query[key]
                else:
                    user = User.objects(username=query[key]).first()

                is_medico = False
                for r in user.roles:
                    if r.role_name == 'medico':
                        is_medico = True
                        query['user'] = user
                        break

                if is_medico:
                    query[key] = user
                else:
                    query[key] = Message(header=UserNotHavingRole(), data=None)

            elif key == 'action':

                if not query[key] in [
                        'create', 'close', 'open', 'update', 'pause'
                ]:
                    query[key] = Message(
                        header=ReportActionForbidden(action=key), data=None)

            elif key == 'id_examination':
                query[key] = self._check_examination(query[key])
                logger.debug(query[key])

            elif key == 'report_text':
                continue

            elif key == 'id':
                continue

            else:
                _ = query.pop(key)

            if isinstance(query[key], Message):
                logger.debug("I'm a message")
                return query[key]

        return query
Exemplo n.º 8
0
    def open(self, **query):
        """
        L'evento open puo essere avviato da closed e suspended
        Quando un esame e' chiuso abbiamo bisogno di una password
        per riaprirlo
        """

        id_ = query['id']
        qs, report = self._pre_event(id_)

        if report.status_name == 'closed':

            password = query['password']
            username = self.user

            if not self._check(username, password) or \
                    report.action_list[-1].user.username != self.user:
                text = "%s not allowed to open this report" % (self.user)
                message = Message(
                    ReportErrorHeader(message=text, user=self.user))
                return message

            # Aggiorno il log solo quando lo riapro da chiuso
            self._update_log(self.user, 'open', report)

        report.status.open(report)

        return self._event_message(report, qs)
Exemplo n.º 9
0
    def read(self, **query):

        if query != {}:
            logger.debug(query)

        report = Report.objects(**query)
        #report = db_wrapper.query('report', **query)

        if report.count() == 0:
            message = Message(
                ReportErrorHeader(message="No Reports in database"),
                data=report)
            return message

        message = Message(ReportCorrectHeader(message="Reports loaded"),
                          data=report)
        return message
Exemplo n.º 10
0
    def create(self, **query):

        query['user'] = self.user

        logger.debug(query)

        query = self._check_fields(query)

        if isinstance(query, Message):
            logger.debug("I'm a message!")
            return query

        query['action_list'] = [self._create_action(query)]

        if isinstance(query['action_list'], Message):
            return query['action_list']

        query['id_patient'] = query['id_examination'][0].id_patient.id_patient

        logger.debug(query)

        report = Report(**query)
        # report = db_wrapper.insert('report', **query)
        try:
            report.save()
        except (FieldDoesNotExist, NotUniqueError, SaveConditionError) as err:

            txt_message = "Report cannot be saved: %s " % (err.message)
            logger.error(txt_message)
            message = Message(ReportErrorHeader(message=txt_message))
            return message

        # Porto gli esami a reported
        e_controller = ExaminationController(user=self.user)
        for ex_ in report.id_examination:
            _ = e_controller.eject(id=str(ex_.id))

        self._currentReport = report

        message = "Report correctly created"
        report = Report.objects(id=report.id)
        # query = {'id':report.id}
        # report = db_wrapper.query('report', **query)
        message = Message(ReportCorrectHeader(message=message), data=report)

        return message
Exemplo n.º 11
0
 def _check_fields(self, query, **kwargs):
     
     for k_ in kwargs.keys():
         if kwargs[k_] == None:
             msg = Message(NotFoundHeader(name=k_))
             logger.error(msg.header.message)
             return msg
         else:
             if k_ == 'id_technician':
                 if not kwargs[k_].has_role('tecnico'):
                     # TODO: Ad-hoc header
                     msg = Message(NotFoundHeader(name=k_))
                     logger.error(msg.header.message)
                     return msg
                 
             query[k_] = kwargs[k_]
             
     return query
Exemplo n.º 12
0
 def _update_technician(self, user, examination):
     
     query = dict()
     query['id_technician'] = User.objects(username=user).first()
     
     if not examination.modify(**query):
         message = Message(ExaminationErrorHeader(message='Error in modifying'))
         logger.error(message.header.message)
         return message
     
     # Try to save
     try:
         examination.save()
     except NotUniqueError, err:
         message = Message(ExaminationErrorHeader(message=err.message, 
                                                  user=self.user)) 
         logger.error(message.header.message)
         return message
Exemplo n.º 13
0
    def _check_status(self, report, status):
        """Deprecated"""

        if report.status_name != status:
            text = "Report is not %s" % (status)
            message = Message(ReportErrorHeader(message=text, user=self.user))
            return message

        return None
Exemplo n.º 14
0
    def read(self, **query):

        # TODO: Check query fields!

        if 'id_patient' in query.keys():
            query['id_patient'] = str(query['id_patient'])

        # return only present patients!
        query['status'] = 'Attivo'

        patients = Patient.objects(**query)

        # Patient list empty
        if patients.count() == 0:
            message = Message(PatientNoRecordHeader(), data=patients)
            logger.error(message.header.message)
            return message

        message = Message(PatientCorrectHeader(), data=patients)

        return message
Exemplo n.º 15
0
    def _get_report(self, id_report):
        """Deprecated: to be subsituted with a function in a superclass"""
        report = Report.objects(id=str(id_report))

        if report == None:
            message = 'No report with this id'
            Message(ReportErrorHeader(message=message), data=None)
            logger.error(message)
            return message

        self._currentReport = report.first()
        return report
Exemplo n.º 16
0
    def print_report(self, **query):
        # Get information about the report
        # Pack into the Message
        # Send it to controller
        id_ = query['id']
        _, report = self._pre_event(id_)

        data = dict()
        data['patient_first_name'] = report.id_examination[
            0].id_patient.first_name
        data['patient_id_patient'] = report.id_examination[
            0].id_patient.id_patient
        data['patient_last_name'] = report.id_examination[
            0].id_patient.last_name
        data['patient_birth_date'] = report.id_examination[
            0].id_patient.birthdate
        data['patient_age'] = report.id_examination[0].id_patient.age
        data['examination_date'] = report.id_examination[0].data_inserimento
        data['examination_tecnico_first_name'] = report.id_examination[
            0].id_technician.first_name
        data['examination_tecnico_last_name'] = report.id_examination[
            0].id_technician.last_name

        data['report_id'] = id_

        data['examination_title'] = []
        for e in report.id_examination:
            data['examination_title'].append(e.id_typology.descrizione_breve)

        data['text'] = report.report_text.encode('ascii', 'xmlcharrefreplace')
        data['status'] = report.status_name
        data['medico_first_name'] = report.action_list[-1].user.first_name
        data['medico_last_name'] = report.action_list[-1].user.last_name
        data['is_modified'] = True
        for action in report.action_list[::-1]:
            if action.action == 'create' or action.action == 'closed':
                data['is_modified'] = True
                data['open_data'] = action.data

        message = Message(ReportCorrectHeader(message='Printing Report',
                                              user=self.user),
                          data=data)

        logger.debug(message.header.message)
        logger.debug(message.data)
        return message
Exemplo n.º 17
0
    def _update_log(self, user, action, report):

        query_action = dict()
        query_action['user'] = user
        query_action['action'] = action

        query_action = self._check_fields(query_action)

        if isinstance(query_action, Message):
            return query_action

        report.action_list.append(self._create_action(query_action))

        try:
            report.save()
        except NotUniqueError, err:
            message = Message(
                ReportErrorHeader(message=err.message, user=self.user))
            logger.error(message.header.message)
            return message
Exemplo n.º 18
0
 def _event_message(self, examination, qs):
     
     message_ = 'Examination is now %s' %(examination.status_name)
     return Message(ExaminationCorrectHeader(message=message_),
                    data=qs)
Exemplo n.º 19
0
class ReportController(object):

    _permission = PermissionController()

    def __init__(self, name='report', user=None):
        self._currentReport = None
        self.name = name
        self.user = user
        return

    def _get_report(self, id_report):
        """Deprecated: to be subsituted with a function in a superclass"""
        report = Report.objects(id=str(id_report))

        if report == None:
            message = 'No report with this id'
            Message(ReportErrorHeader(message=message), data=None)
            logger.error(message)
            return message

        self._currentReport = report.first()
        return report

    def _check_fields(self, query):

        for key in query.keys():

            if key == 'user':

                if isinstance(query[key], User):
                    user = query[key]
                else:
                    user = User.objects(username=query[key]).first()

                is_medico = False
                for r in user.roles:
                    if r.role_name == 'medico':
                        is_medico = True
                        query['user'] = user
                        break

                if is_medico:
                    query[key] = user
                else:
                    query[key] = Message(header=UserNotHavingRole(), data=None)

            elif key == 'action':

                if not query[key] in [
                        'create', 'close', 'open', 'update', 'pause'
                ]:
                    query[key] = Message(
                        header=ReportActionForbidden(action=key), data=None)

            elif key == 'id_examination':
                query[key] = self._check_examination(query[key])
                logger.debug(query[key])

            elif key == 'report_text':
                continue

            elif key == 'id':
                continue

            else:
                _ = query.pop(key)

            if isinstance(query[key], Message):
                logger.debug("I'm a message")
                return query[key]

        return query

    def _check_examination(self, list_id_examinations):

        if len(list_id_examinations) == 0:
            message = "No examination"
            return Message(ReportErrorHeader(message=message), data=None)

        examination_list = Examination.objects(id__in=list_id_examinations)

        patient_list = []
        data_examination = []
        status_list = []

        for e in examination_list:
            patient_list.append(e.id_patient.id)
            data_examination.append(e.data_inserimento)
            status_list.append(e.status_name)

        if len(np.unique(patient_list)) > 1:
            message = "Examinations are from different patient"
            logger.debug(np.unique(patient_list))
            return Message(ReportErrorHeader(message=message), data=None)

        if len(np.unique(data_examination)) > 1:
            message = "Examinations are from different date"
            logger.debug(np.unique(data_examination))
            return Message(ReportErrorHeader(message=message), data=None)

        if 'closed' in status_list:
            message = "Examinations are already reported"
            logger.debug(np.unique(status_list))
            return Message(ReportErrorHeader(message=message), data=None)

        return examination_list

    def _create_action(self, query):

        action = query.pop('action')
        user = query.pop('user')

        report_action = ReportAction(user=user, action=action)

        return report_action

    def create(self, **query):

        query['user'] = self.user

        logger.debug(query)

        query = self._check_fields(query)

        if isinstance(query, Message):
            logger.debug("I'm a message!")
            return query

        query['action_list'] = [self._create_action(query)]

        if isinstance(query['action_list'], Message):
            return query['action_list']

        query['id_patient'] = query['id_examination'][0].id_patient.id_patient

        logger.debug(query)

        report = Report(**query)
        # report = db_wrapper.insert('report', **query)
        try:
            report.save()
        except (FieldDoesNotExist, NotUniqueError, SaveConditionError) as err:

            txt_message = "Report cannot be saved: %s " % (err.message)
            logger.error(txt_message)
            message = Message(ReportErrorHeader(message=txt_message))
            return message

        # Porto gli esami a reported
        e_controller = ExaminationController(user=self.user)
        for ex_ in report.id_examination:
            _ = e_controller.eject(id=str(ex_.id))

        self._currentReport = report

        message = "Report correctly created"
        report = Report.objects(id=report.id)
        # query = {'id':report.id}
        # report = db_wrapper.query('report', **query)
        message = Message(ReportCorrectHeader(message=message), data=report)

        return message

    def read(self, **query):

        if query != {}:
            logger.debug(query)

        report = Report.objects(**query)
        #report = db_wrapper.query('report', **query)

        if report.count() == 0:
            message = Message(
                ReportErrorHeader(message="No Reports in database"),
                data=report)
            return message

        message = Message(ReportCorrectHeader(message="Reports loaded"),
                          data=report)
        return message

    def update(self, **query):

        query['user'] = self.user

        if 'id_examination' in query.keys():
            _ = query.pop('id_examination')

        query = self._check_fields(query)

        if isinstance(query, Message):
            return query

        logger.debug(query)

        action = query.pop('action')
        user = query.pop('user')
        id_report = query.pop('id')

        report = self._get_report(id_report).first()

        if isinstance(report, Message):
            return report

        if report.status_name == 'closed':
            message = "The report is closed"
            return Message(ReportErrorHeader(message=message), data=None)

        if not report.modify(**query):
            message = Message(ReportErrorHeader(message='Error in modifying'))
            logger.error(message.header.message)
            return message

        message = self._update_log(user, action, report)

        if message != None:
            return message

        # Porto gli esami a closed
        e_controller = ExaminationController(user=self.user)
        for ex_ in report.id_examination:
            if ex_.status_name == 'closed':
                break
            _ = e_controller.close(id=str(ex_.id))

        self._currentReport = report
        report = Report.objects(id=str(id_report))
        #report = db_wrapper.query('report', **query)
        message = "Report correctly updated"
        message = Message(ReportCorrectHeader(message=message), data=report)

        return message

    def delete(self, **query):

        # Cancellare il report
        report = Report.objects(**query)
        #report = db_wrapper.query('report', **query)

        if report.count() == 0:
            message = Message(
                ReportErrorHeader(message="No Reports in database"),
                data=report)
            return message

        report = report.first()

        e_controller = ExaminationController(user=self.user)
        for ex_ in report.id_examination:
            if ex_.status_name != 'closed':
                _ = e_controller.eject(id=str(ex_.id))
            else:
                message = Message(
                    ReportErrorHeader(message='Cannot delete the report'))
                return message

        try:
            report.delete()
        except Exception, err:
            message = Message(ReportErrorHeader(message="Error in deleting"),
                              data=report)
            return message

        message = Message(ReportCorrectHeader(message='Report deleted'),
                          data=None)

        return message
Exemplo n.º 20
0
    def create(self, **query):
        
        pt_controller = PatientController()
        pt_message = pt_controller.read(id_patient=query['id_patient'])
        
        if pt_message.header.code == 101:
            return pt_message
        
        query['id_patient'] = pt_message.data[0]
        logger.debug(pt_message.data[0].first_name)
        
        if 'data_inserimento' in query.keys():
            query['data_inserimento'] = parse_date(query['data_inserimento'])
            logger.debug(query['data_inserimento'])

        query['id_creator'] = User.objects(username=query['id_creator']).first()
        
        list_examination = query.pop('exams')
        
        if len(list_examination) == 0:
            message = Message(ExaminationErrorHeader(message='No Examination in Request'))
            logger.error(message.header.message)
            return message
        
        examination = None
        
        for i, exam_ in enumerate(list_examination):
            
            typology = Typology.objects(examination_name=exam_['nome']).first()
            priority = Priority.objects(priority_name=exam_['priority']).first()
            query = self._check_fields(query,
                                   id_priority=priority,
                                   id_typology=typology,
                                   )

            if not isinstance(query, dict):
                # It is a message!
                return query
            
            qs = Examination.objects(**query)
            
            logger.debug(query)
            logger.debug("No. of examinations: "+str(len(qs)))
            
            if len(qs) != 0:
                continue
            
            examination = Examination(**query)
            
            pacs_data = _build_pacs_data(examination)
            send_to_pacs.apply_async(link_error=pacs_error_handler.s(), kwargs={'data':pacs_data}, )
            #send_to_pacs(pacs_data)
            try:
                examination.save()
            except (FieldDoesNotExist,
                    NotUniqueError,
                    SaveConditionError) as err:
                
                txt_message = "On %s examination: %s" % (str(i+1), err.message)
                logger.error(txt_message)
                message = Message(ExaminationErrorHeader(message=txt_message))
                return message
            
            logger.debug("Examination created: "+str(examination.data_inserimento))
            examination = self._get_examination(examination.id)
            examination.status = NewExaminationStatus(examination)
        
        
        if examination == None:
            message = "Examination already stored"
            examination = qs
        else:
            message = 'Examination created correctly'
        
        message = Message(ExaminationCorrectHeader(message=message),
                          data=examination)
        
        self._currentExamination = examination
        
        return message
Exemplo n.º 21
0
class PatientController(object):
    def __init__(self, name='patient', user=None, **kwargs):

        # TODO: If no patients??
        self._currentPatient = None
        self.name = name
        self.user = user
        #super(PatientController, self).__init__()

    def create(self, **query):

        # TODO: Check fields if they're correct!

        if 'birthdate' in query.keys():
            query['birthdate'] = datetime.strptime(query['birthdate'],
                                                   "%Y-%m-%dT%H:%M:%S.%fZ")

        patient = Patient(**query)
        try:
            patient.save()
        except (FieldDoesNotExist, NotUniqueError, SaveConditionError) as err:

            message = Message(PatientErrorHeader(message=err.message))
            logger.error(err.message)

            return message

        patient = self._get_patient(patient.id_patient)
        self._currentPatient = patient.first()

        message = Message(
            PatientCorrectHeader(message='Patient correctly created!'),
            data=patient)

        return message

    def update(self, **query):

        # Check if a patient has been selected
        if self._currentPatient is None:
            # Get the id from query
            if 'id_patient' in query.keys():
                _ = self._get_patient(str(query['id_patient']))

        patient = self._currentPatient

        if 'birthdate' in query.keys():
            query['birthdate'] = parse_date(query['birthdate'])
            logger.debug(query['birthdate'])

        if '_id' in query.keys():
            _ = query.pop('_id')

        # Try to modify
        if not patient.modify(**query):
            message = Message(PatientErrorHeader(message='Error in modifying'))
            logger.error(message.header.message)
            return message

        # Try to save
        try:
            patient.save()
        except NotUniqueError, err:
            message = Message(
                PatientErrorHeader(message=err.message, user=self.user))
            logger.error(message.header.message)
            return message

        patient = self._get_patient(patient.id_patient)

        # Everything ok!!!
        message = Message(
            PatientCorrectHeader(message='Patient correctly modified!'),
            data=patient)

        return message