Example #1
0
    def test_create(self):

        user = User.objects(username='******').first()
        self.controller.user = user
        query = dict()

        priority = Priority.objects(priority_name='ROUTINE').first()
        technician = User.objects(username='******').first()
        #typology = Typology.objects(codice_regionale='RM11').first()

        query['id_creator'] = str(user.username)
        query['id_priority'] = str(priority.priority_name)  # Routine
        query['id_technician'] = str(technician.id)  # Daniele-Tecnico
        query['exams'] = [{
            "priority": "ALTA",
            "modality": "MR",
            "sala": "RM1.5T",
            "distretto": "TORACE",
            "nome": "RM TORACE SENZA MDC",
            "selected": True
        }]
        query['id_patient'] = _get_current_patient_id()
        query['medico_richiedente'] = 'Mauro Caffarini'
        query['accession_number'] = '11111111'
        query['data_inserimento'] = "1983-05-18T13:08:00.0Z"

        message = self.controller.create(**query)
        print message.header.message
        self.assertEqual(message.header.code, 200)
Example #2
0
def run(database_config, n_loaded=50):

    db_config = parse_db_config(database_config)
    _ = easyris_connect(**db_config)
    #client = connect(database, port=port)

    Examination.drop_collection()

    priority_list = Priority.objects()
    typology_list = Typology.objects()
    patient_list = Patient.objects()

    user1 = User.objects(username='******').first()
    user2 = User.objects(username='******').first()

    for _ in range(n_loaded):

        ip = random.randint(0, len(patient_list) - 1)
        it = random.randint(0, len(typology_list) - 1)
        ipr = random.randint(0, len(priority_list) - 1)

        patient = patient_list[ip]
        typology = typology_list[it]
        priority = priority_list[ipr]
        random_number = random.randint(1, 10)

        if random_number > 5:
            now = datetime.now()
            date_ = datetime(year=now.year, month=now.month, day=now.day)
            if random_number == 8:
                status_name = 'completed'
                status = CompletedExaminationStatus()
            else:
                status_name = 'new'
                status = NewExaminationStatus()

        else:
            date_ = datetime(year=2016, month=02, day=02)
            status_name = 'completed'
            status = CompletedExaminationStatus()

        examination = Examination(id_patient=patient,
                                  medico_richiedente='Mauro Caffarini',
                                  data_inserimento=date_,
                                  id_priority=priority,
                                  id_typology=typology,
                                  id_technician=user2,
                                  id_creator=user1,
                                  status_name=status_name,
                                  status=status,
                                  codice_esenzione='67577568',
                                  examination_note='ok')

        examination.save()
Example #3
0
    def test_model(self):
        print "---- Testing Examination ----"
        patient1 = Patient.objects(first_name="Tecla").first()
        user1 = User.objects(username='******').first()
        user2 = User.objects(username='******').first()

        typology = Typology.objects(modality='MR').first()

        priority = Priority.objects(priority_name='ALTA').first()

        examination = Examination(id_patient=patient1,
                                  medico_richiedente='Pinco Pallo',
                                  data_inserimento=datetime(year=2016,
                                                            day=02,
                                                            month=02),
                                  id_priority=priority,
                                  id_typology=typology,
                                  id_creator=user1,
                                  id_technician=user2,
                                  accession_number='12345665',
                                  codice_esenzione='67577568',
                                  examination_note='ok')

        print '----------------------'
        examination.save()
        assert examination.status.name == 'new'

        print '------ Object saved -----------'
        examination.status.start(examination)
        assert examination.status_name == 'scheduled'
        examination.status.go(examination)
        examination.status.pause(examination)
        assert examination.status_name == 'incomplete'

        examination.status.start(examination)
        examination.status.go(examination)
        assert examination.status_name == 'running'

        examination.status.eject(examination)
        examination.status.stop(examination)
        assert examination.status_name == 'rescheduled'

        examination.status.start(examination)
        assert examination.status_name == 'rescheduled'

        examination.status.go(examination)
        examination.status.finish(examination)
        assert examination.status_name == 'completed'

        examination.status.eject(examination)
        assert examination.status_name == 'reported'
Example #4
0
    def test_update(self):
        user = User.objects(username='******').first()
        self.controller.user = user
        query = dict()

        examination_list = _get_correct_examinations()

        query['action'] = 'create'
        query['report_text'] = "Do cazz e sciut l Acquafan"
        query['id_examination'] = [str(e.id) for e in examination_list]

        message = self.controller.create(**query)
        self.assertEqual(message.header.code, 500)

        query = dict()
        query['id'] = str(message.data.first().id)
        query['action'] = 'update'
        query['report_text'] = "Gesu"

        message = self.controller.update(**query)
        print message.header.message
        self.assertEqual(message.header.code, 500)
        self.assertEqual(len(self.controller._currentReport.action_list), 2)
        self.assertEqual(self.controller._currentReport.report_text,
                         query['report_text'])
Example #5
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
Example #6
0
    def test_close(self):
        user = User.objects(username='******').first()
        self.controller.user = user
        query = dict()
        report = Report.objects().first()
        query['id'] = str(report.id)
        query['user'] = '******'
        message = self.controller.close(**query)

        report = Report.objects(id=report.id).first()

        assert report.status_name == 'closed'
        assert message.header.code == 500
        assert len(report.action_list) == 2
        assert report.action_list[-1].action == 'close'
Example #7
0
    def test_bad_examinations(self):
        user = User.objects(username='******').first()
        self.controller.user = user
        query = dict()

        examination_list = _get_random_examinations()

        query['action'] = 'open'
        query['user'] = '******'
        query['report_text'] = "Do cazz e sciut l Acquafan"
        query['id_examination'] = [str(e.id) for e in examination_list]

        message = self.controller.create(**query)
        print message.header.message
        self.assertEqual(message.header.code, 501)
Example #8
0
    def test_create(self):
        user = User.objects(username='******').first()
        self.controller.user = user
        query = dict()

        examination_list = _get_correct_examinations()
        print[str(e.data_inserimento) for e in examination_list]

        query['action'] = 'create'
        query['user'] = '******'
        query['report_text'] = "Do cazz e sciut l Acquafan"
        query['id_examination'] = [str(e.id) for e in examination_list]

        message = self.controller.create(**query)
        print "Message: "
        print message.data
        self.assertEqual(message.header.code, 500)
Example #9
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
Example #10
0
    def login(self, username=None, password=None):

        message_data = {'is_authenticated': False, 'user': None, 'qs': None}
        qs = User.objects(username=username)

        logged_user = qs.first()

        if len(qs) == 0:
            # No user with this username
            message = Message(UserNotFoundHeader(), data=message_data)
            logger.debug(message.header.message)
            return message

        if logged_user.check_password(password):
            message_data['user'] = logged_user
            message_data['is_authenticated'] = True
            message_data['qs'] = qs
            message = Message(UserLoggedHeader(), data=message_data)
            logger.debug(message.header.message)
        else:
            message = Message(UserNotAuthenticatedHeader(), data=message_data)
            logger.debug(message.header.message)

        return message
Example #11
0
def run(database_config, n_loaded=50):
    
    db_config = parse_db_config(database_config)

    _ = easyris_connect(**db_config)
    
    Report.drop_collection()
    
    user = User.objects(username='******').first()
    
    examination_list = Examination.objects(status_name='completed',
                                           data_inserimento=datetime.datetime(year=2016,
                                                                              month=02,
                                                                              day=02))
    
    # Trovo i pazienti con piu esami
    id_patient_list = [e.id_patient.id_patient for e in examination_list]
    counter = collections.Counter(id_patient_list)
    
    if len(counter) < n_loaded:
        n_loaded = len(counter) / 2
    
    print n_loaded
    
    for i in range(n_loaded):
        
        id_patient = counter.keys()[i]
        patient = Patient.objects(id_patient=id_patient).first()
        patient_examination = Examination.objects(id_patient=patient.id,
                                                  status_name='completed',
                                                  data_inserimento=datetime.datetime(year=2016,
                                                                            month=02,
                                                                            day=02))

        dates_ = np.unique([e.data_inserimento for e in patient_examination])
        
        for d_ in dates_:
            data_ = datetime.datetime(d_.year, d_.month, d_.day)
            same_date_examination = Examination.objects(id_patient=patient.id,
                                                        data_inserimento=data_,
                                                        status_name='completed')
        

        report_log = ReportAction(
                                     user=user,
                                     action='create'
                                     )
               

        report = Report(
                        id_examination = [e for e in same_date_examination],
                        report_text = "Il paziente bla bla bla",
                        action_list = [report_log],
                        id_patient = id_patient,
                        status=SuspendedReportStatus(),
                        status_name='suspended'
                        )

        report.save()
        
        for e in same_date_examination:
            e.modify(status=ClosedExaminationStatus(),
                     status_name='closed')
            e.save()
Example #12
0
    def test_accession_number(self):
        print "---- Testing Examination ----"
        patient1 = Patient.objects(first_name="Tecla").first()
        user1 = User.objects(username='******').first()
        user2 = User.objects(username='******').first()

        typology_qs = Typology.objects(room='RM1.5T',
                                       distretto_corporeo='TESTA/COLLO')

        typology1 = typology_qs[0]
        typology2 = typology_qs[1]

        assert typology1.examination_name != typology2.examination_name

        priority = Priority.objects(priority_name='ALTA').first()

        examination1 = Examination(
            id_patient=patient1,
            medico_richiedente='Pinco Pallo',
            data_inserimento=datetime(year=2016, day=05, month=02),
            id_priority=priority,
            id_typology=typology1,
            id_creator=user1,
            id_technician=user2,
            #accession_number='12345665',
            codice_esenzione='67577568',
            examination_note='ok')

        examination2 = Examination(
            id_patient=patient1,
            medico_richiedente='Pinco Pallo',
            data_inserimento=datetime(year=2016, day=05, month=02),
            id_priority=priority,
            id_typology=typology2,
            id_creator=user1,
            id_technician=user2,
            #accession_number='12345665',
            codice_esenzione='67577568',
            examination_note='ok')

        examination1.save()
        examination2.save()

        assert examination1.accession_number == examination2.accession_number

        examination3 = Examination(
            id_patient=patient1,
            medico_richiedente='Pinco Pallo',
            data_inserimento=datetime(year=2016, day=05, month=03),
            id_priority=priority,
            id_typology=typology2,
            id_creator=user1,
            id_technician=user2,
            #accession_number='12345665',
            codice_esenzione='67577568',
            examination_note='ok')
        examination3.save()

        assert examination2.accession_number != examination3.accession_number

        return
Example #13
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
Example #14
0
def run(database_config):

    from easyris.base.database import parse_db_config, easyris_connect

    db_config = parse_db_config(database_config)
    conn = easyris_connect(**db_config)

    actions = ['create', 'read', 'update', 'delete']

    actions_examination_status = [
        'start', 'go', 'stop', 'pause', 'finish', 'eject'
    ]
    actions_report_status = ['close', 'save', 'print', 'open']
    resources = [
        'patient', 'examination', 'report', 'examination_status',
        'report_status'
    ]

    permission_ = itertools.product(resources, actions)
    Permission.drop_collection()
    permission_list = []
    for it in permission_:
        p = Permission(it[1], it[0])
        p.save()
        permission_list.append(p)

    ex_status_permission = itertools.product(['examination'],
                                             actions_examination_status)
    for it in ex_status_permission:
        p = Permission(it[1], it[0])
        p.save()
        permission_list.append(p)

    report_status_permission = itertools.product(['report'],
                                                 actions_report_status)
    for it in report_status_permission:
        p = Permission(it[1], it[0])
        p.save()
        permission_list.append(p)

    permission_dict = {
        'accettazione':
        np.array([1, 2, 3, 5, 6, 13, 14, 18, 30]) - 1,
        'tecnico':
        np.array([2, 6, 7, 8, 14, 15, 16, 18, 21, 22, 23, 24, 25]) - 1,
        'medico':
        np.array([2, 6, 9, 10, 11, 14, 17, 18, 19, 26, 27, 28, 29, 30]) - 1,
        'amministrazione':
        np.array([2, 6, 10, 14, 18]) - 1,
        'admin':
        np.arange(30)
    }

    Role.drop_collection()
    for key_, value_ in permission_dict.iteritems():
        role_ = Role(key_, [permission_list[i] for i in value_])
        role_.save()

    User.drop_collection()
    role_medico = Role.objects(role_name='medico').first()

    user1 = User(username='******',
                 password='******',
                 roles=[role_medico],
                 first_name='Massimo',
                 last_name='Caulo',
                 telephone_number='3289876543',
                 mobile_number='3212345678',
                 email='*****@*****.**')
    user1.save()

    role_acc = Role.objects(role_name='accettazione').first()
    user2 = User(username='******',
                 password='******',
                 roles=[role_acc],
                 first_name='Gaetano',
                 last_name='Di Gaetano',
                 telephone_number='3289876543',
                 mobile_number='3212345678',
                 email='*****@*****.**')
    user2.save()

    role_tecnico = Role.objects(role_name='tecnico').first()
    user3 = User(username='******',
                 password='******',
                 roles=[role_tecnico],
                 first_name='Daniele',
                 last_name='Petrucci',
                 telephone_number='3289876543',
                 mobile_number='3212345678',
                 email='*****@*****.**')

    user3.save()

    role_amministrazione = Role.objects(role_name='amministrazione').first()
    user4 = User(username='******',
                 password='******',
                 roles=[role_amministrazione],
                 first_name='Carlo',
                 last_name='Michetti',
                 telephone_number='3289876543',
                 mobile_number='3212345678',
                 email='*****@*****.**')

    user4.save()

    role_admin = Role.objects(role_name='admin').first()
    user5 = User(username='******',
                 password='******',
                 roles=[role_admin],
                 first_name='Piero',
                 last_name='Chiacchiaretta',
                 telephone_number='3289876543',
                 mobile_number='3212345678',
                 email='*****@*****.**')

    user5.save()

    user11 = User(username='******',
                  password='******',
                  roles=[role_medico],
                  first_name='Valentina',
                  last_name='Panara',
                  telephone_number='3289876543',
                  mobile_number='3212345678',
                  email='*****@*****.**')
    user11.save()
Example #15
0
 def load_user(self, id_):
     return User.objects(id=id_).first()