Пример #1
0
    def get(self, instance_id):
        auth_response = authenticate(self, [Permissions.READ_QUESTION])

        if auth_response["valid"]:
            instance = InstanceService.get_instance(instance_id)
            state = StateService.get_next_state_in_instance(instance)

            if state is None:
                self.set_status(404)
                self.write('{"status":"error","message":"Survey does not exist"}')
                self.finish()
            else:
                survey = SurveyService.get_survey(instance.survey_id)
                if str(survey.owner_id) == auth_response["owner_id"]:
                    if state.status == Status.CREATED_START:
                        self.set_status(200)
                        self.write('{"status":"success","status":"NOT STARTED"}')
                        self.flush()
                    elif state.status == Status.TERMINATED_COMPLETE:
                        self.set_status(200)
                        self.write('{"status":"success","status":"COMPLETE"}')
                        self.flush()
                    else:
                        self.set_status(200)
                        self.write('{"status":"success","status":"IN PROGRESS"}')
                        self.flush()

                else:
                    self.set_status(403)
                    self.write('{"status":"error","message":"Owner does not have authorization to see this survey"}')
                    self.flush()
Пример #2
0
    def delete(self, task_id):
        logger.debug("Trying to delete a task")
        auth = authenticate(self, [Permissions.READ_TASK])

        if auth['valid']:
            task = TaskService.get_task(int(task_id))
            survey = SurveyService.get_survey(task.survey_id)

            if survey.owner_id == int(auth['owner_id']):
                TaskService.delete_task(task.id)

                self.set_status(200)

                response = {"status": "success"}
            else:
                response = {
                    "status": "error",
                    "message":
                    "Plugin is not registered by survey administrator"
                }
                self.set_status(403)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
Пример #3
0
    def get(self):
        logger.debug("Querying for tasks")
        auth = authenticate(self, [Permissions.READ_TASK])

        if auth["valid"]:
            surveys = SurveyService.get_surveys_by_owner(auth["owner_id"])

            surveys_tasks = {}

            for survey in surveys:
                surveys_tasks[survey] = TaskService.get_tasks_by_survey_id(
                    survey.id)

            tasks = []

            for survey, task_list in surveys_tasks.items():
                for task in task_list:
                    tasks.append({
                        "id":
                        task.id,
                        "name":
                        task.name,
                        "protocol_name":
                        ProtocolService.get_protocol(survey.protocol_id).name,
                        "enrollment_name":
                        EnrollmentService.get(survey.enrollment_id).name
                    })

            response = {"status": "success", "tasks": tasks}
            self.set_status(200)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
Пример #4
0
    def get(self, instance_id):
        auth_response = authenticate(self, [Permissions.READ_QUESTION])

        if auth_response["valid"]:
            instance = InstanceService.get_instance(instance_id)
            state = StateService.get_next_state_in_instance(instance, Status.AWAITING_USER_RESPONSE)

            if state is None:
                self.set_status(410)
                response = {
                    "status": "error",
                    "message": "No response was expected for this survey"
                }
            else:
                survey = SurveyService.get_survey(instance.survey_id)
                if str(survey.owner_id) == auth_response['owner_id']:
                    question_service = QuestionService()
                    question = question_service.get(survey.protocol_id, state.question_number)

                    if question is not None:
                        self.set_status(200)

                        response = {
                            "status": "success",
                            "question_number": state.question_number,
                            "question_text": question.question_text,
                            "survey_end": question.final
                        }
                    else:
                        self.set_status(410)
                        response = {
                            "status": "error",
                            "message": "No more questions in this survey"
                        }
                else:
                    self.set_status(403)
                    response = {
                        "status": "error",
                        "message": "Owner has not registered plugin"
                    }

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def get(self):
        auth_response = authenticate(self, [Permissions.READ_PARTICIPANT])

        if auth_response["valid"]:
            survey_id = self.get_argument("survey_id")
            instance_id = self.get_argument("instance_id")

            instance = InstanceService.get_instance(instance_id)
            survey = SurveyService.get_survey(survey_id)

            if instance is None or survey is None:
                response = {
                    "status": "error",
                    "message": "Invalid instance or survey ID"
                }

                self.set_status(400)
                self.write(json.dumps(response))
                self.flush()
            else:
                if str(survey.owner_id) == auth_response["owner_id"]:

                    participant = ParticipantService.get_participant(
                        instance.participant_id)

                    response = {
                        "status": "success",
                        "participant": participant.plugin_scratch,
                    }

                    self.set_status(200)
                    self.write(json.dumps(response))
                    self.flush()
                else:
                    response = {
                        "status": "error",
                        "message":
                        "Do not have authorization to make this request"
                    }

                    self.set_status(401)
                    self.write(json.dumps(response))
                    self.flush()
Пример #6
0
    def get(self, task_id):
        auth = authenticate(self, [Permissions.READ_TASK])

        if auth['valid']:
            task = TaskService.get_task(int(task_id))
            survey = SurveyService.get_survey(task.survey_id)

            if survey.owner_id == int(auth['owner_id']):
                time_rule = TimeRuleService().get(survey.id, task.time_rule_id)
                date_times = time_rule.get_date_times()

                dts = []

                for dt in date_times:

                    hour_str = str(
                        dt.hour) if dt.hour > 9 else '0' + str(dt.hour)
                    minute_str = str(
                        dt.minute) if dt.minute > 9 else '0' + str(dt.minute)

                    dts.append({
                        "year": dt.year,
                        "month": dt.month,
                        "day": dt.day,
                        "time": hour_str + ":" + minute_str
                    })

                response = {"status": "success", "run_times": dts}
                self.set_status(200)
            else:
                response = {
                    "status": "error",
                    "message":
                    "Plugin is not registered by survey administrator"
                }
                self.set_status(403)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def start_instance(instance):
        instance_id = instance.id
        print("Starting instance " + str(instance_id))

        survey = SurveyService.get_survey(instance.survey_id)
        timeout_minutes = survey.timeout
        timeout_timestamp = datetime.now(tz=pytz.utc) + timedelta(
            minutes=timeout_minutes)

        StateService.create_state(instance_id, 1, Status.CREATED_START,
                                  timeout_timestamp, 0)

        participants = ParticipantService.get_participants_in_enrollment(
            survey.enrollment_id)
        plugin_ids = set()

        for participant in participants:
            plugin_ids.add(participant.plugin_id)

        for plugin_id in plugin_ids:
            PluginService.poke(plugin_id, survey.id)
Пример #8
0
    def post(self, instance_id):
        auth_response = authenticate(self, [Permissions.WRITE_SURVEY])

        if auth_response["valid"]:
            data = json_decode(self.request.body)

            if 'action' in data:
                action = data['action'].lower()
            else:
                self.set_status(400)
                self.write('{"status":"error","message":"Missing action parameter"}')
                self.flush()
                return

            if action == 'start':
                instance = InstanceService.get_instance(instance_id)
                state = StateService.get_next_state_in_instance(instance, Status.CREATED_START)

                if state is not None:
                    survey = SurveyService.get_survey(instance.survey_id)
                    if str(survey.owner_id) == auth_response["owner_id"]:
                        state.status = Status.AWAITING_USER_RESPONSE.value
                        StateService.update_state(state)
                        self.set_status(200)
                        self.write('{"status":"success","status":"STARTED"}')
                        self.flush()
                    else:
                        self.set_status(403)
                        self.write('{"status":"error","message":"Owner does not have authorization to start survey"}')
                        self.flush()
                else:
                    self.set_status(410)
                    self.write('{"status":"error","message":"Survey already started, or does not exist"}')
                    self.flush()
            else:
                self.set_status(400)
                self.write('{"status":"error","message":"Invalid action parameter"}')
                self.flush()
Пример #9
0
    def get(self, instance_id, question_number):
        auth_response = authenticate(self, [Permissions.READ_QUESTION])

        if auth_response['valid']:
            instance = InstanceService.get_instance(instance_id)
            instance_id = instance.id
            state = StateService.get_state_by_instance_and_question(instance, question_number)

            if state is None:
                self.set_status(404)
                self.write('{"status":"error","message":"Question or survey does not exist"}')
                self.finish()
            else:
                survey = SurveyService.get_survey(instance.survey_id)
                question_service = QuestionService()
                question = question_service.get(survey.protocol_id, state.question_number)

                if question is None:
                    self.set_status(404)
                    self.write('{"status":"error","message":"Question does not exist"}')
                    self.finish()
                else:
                    q_text = question.question_text

                    if state.status == Status.TERMINATED_COMPLETE:
                        response_service = ResponseService()
                        survey_id = instance.survey_id
                        response_set = response_service.get_response_set(survey_id, instance_id)
                        response = response_set.get_response(question.variable_name)

                        self.set_status(200)
                        self.write('{"status":"success","question_text":"' + q_text
                                   + '","responded":"True","response:":"' + response + '"')
                        self.finish()
                    else:
                        self.set_status(200)
                        self.write('{"status":"success","question_text":"' + q_text + '","responded":"False"')
                        self.finish()
Пример #10
0
    def post(self):
        logger.debug("Posting new task")

        task_name = self.get_argument("name")
        protocol_id = int(self.get_argument("protocol_id"))
        enrollment_id = int(self.get_argument("enrollment_id"))
        time_rule = json.loads(self.get_argument("time_rule"))
        enable_notes = self.get_argument("enable_notes", False)
        timeout = int(self.get_argument("timeout"), 20)
        enable_warnings = self.get_argument("enable_warnings", True)
        enable_notes = 1 if enable_notes else 0
        enable_warnings = 1 if enable_warnings else 0

        all_run_times = []
        all_run_dates = []
        local_tz = pytz.timezone(time_rule['timezone'])
        date_conversion = time_rule["run_date"]
        time_conversion = time_rule["run_times"]
        for several_run_time in time_conversion:
            datetime_without_tz = datetime.strptime(
                str(date_conversion) + " " + str(several_run_time),
                "%Y-%m-%d %H:%M")
            datetime_with_tz = local_tz.localize(
                datetime_without_tz, is_dst=True)  # No daylight saving time
            datetime_in_utc = datetime_with_tz.astimezone(pytz.utc)
            str_utc_time = datetime_in_utc.strftime('%Y-%m-%d %H:%M %Z')
            all_run_dates.append(str_utc_time[:10])
            all_run_times.append(str_utc_time[11:16])

        time_rule["run_date"] = str_utc_time[:10]
        time_rule["run_times"] = all_run_times

        auth = authenticate(self,
                            [Permissions.WRITE_TASK, Permissions.WRITE_SURVEY])

        if auth["valid"]:
            owner_id = int(auth['owner_id'])
            response = None

            if ProtocolService.is_owned_by(protocol_id, int(auth['owner_id'])):
                if EnrollmentService.is_owned_by(enrollment_id, owner_id):
                    params = time_rule["params"]
                    run_time_values = time_rule["run_times"]

                    run_times = []

                    for run_time_value in run_time_values:
                        rtv = run_time_value.split(":")
                        hour = int(rtv[0])
                        minute = int(rtv[1])
                        run_times.append(
                            datetime.now(tz=pytz.utc).replace(hour=hour,
                                                              minute=minute,
                                                              second=0))
                    until = datetime.strptime(
                        time_rule["run_date"],
                        "%Y-%m-%d").replace(tzinfo=pytz.utc)
                    run_date = datetime.strptime(
                        time_rule["run_date"],
                        "%Y-%m-%d").replace(tzinfo=pytz.utc)
                    last_date = datetime.strptime(time_rule["run_date"],
                                                  "%Y-%m-%d")
                    start_date = datetime.strptime(time_rule["run_date"],
                                                   "%Y-%m-%d")
                    intervalcount = 'no_repeat'
                    every = 0
                    if time_rule["type"] == 'no_repeat':
                        intervalcount = 'no_repeat'
                        time_rule = NoRepeat(run_date, run_times)
                    elif time_rule["type"] == 'daily':
                        intervalcount = 'daily'
                        every = int(params["every"])
                        until = datetime.strptime(
                            time_rule['until'],
                            "%Y-%m-%d").replace(tzinfo=pytz.utc)
                        last_date = datetime.strptime(time_rule['until'],
                                                      "%Y-%m-%d")
                        time_rule = RepeatsDaily(run_date, every, until,
                                                 run_times)
                    elif time_rule["type"] == 'weekly':
                        intervalcount = 'weekly'
                        every = int(params["every"])
                        until = datetime.strptime(
                            time_rule['until'],
                            "%Y-%m-%d").replace(tzinfo=pytz.utc)
                        time_rule = RepeatsWeekly(every, params['days'],
                                                  run_times, run_date, until)
                    elif time_rule["type"] == 'monthly_date':
                        intervalcount = 'monthly_date'
                        every = int(params["every"])
                        until = datetime.strptime(
                            time_rule['until'],
                            "%Y-%m-%d").replace(tzinfo=pytz.utc)
                        time_rule = RepeatsMonthlyDate(every, params['dates'],
                                                       until, run_times)
                    elif time_rule["type"] == 'monthly_day':
                        intervalcount = 'monthly_day'
                        every = int(params["every"])
                        until = datetime.strptime(
                            time_rule['until'],
                            "%Y-%m-%d").replace(tzinfo=pytz.utc)
                        time_rule = RepeatsMonthlyDay(every, params['param1'],
                                                      params['days'], until,
                                                      run_times)
                    else:
                        response = {
                            "status":
                            "error",
                            "message":
                            time_rule['type'] + " is not a valid time rule"
                        }
                        self.set_status(400)

                    for daysNo in range((last_date - start_date).days + 1):
                        DataManagement.dataStorage.append(enrollment_id)
                        listParticipants = []
                        participants = ParticipantService.get_participants_in_enrollment(
                            enrollment_id)
                        for participant in participants:
                            listParticipants.append(participant.id)
                        DataManagement.dataStorage.append(listParticipants)
                        DataManagement.dataStorage.append(start_date)
                        DataManagement.dataStorage.append(run_time_values)
                        DataManagement.dataStorage.append("cig_ecig")
                        DataManagement.dataStorage.append(until)
                        DataManagement.dataStorage.append(intervalcount)
                        DataManagement.dataStorage.append(protocol_id)
                        DataManagement.dataStorage.append("scheduled")
                        DataManagement.get_schedule()
                        start_date = start_date + timedelta(days=every)
                else:
                    response = {
                        "status": "error",
                        "message": "Enrollment not owned by account"
                    }
                    self.set_status(401)
            else:
                response = {
                    "status": "error",
                    "message": "Protocol not owned by account"
                }
                self.set_status(401)

            if response is None:
                survey = SurveyService.create_survey(owner_id, protocol_id,
                                                     enrollment_id,
                                                     enable_notes, timeout,
                                                     enable_warnings)
                time_rule_id = TimeRuleService().insert(survey.id, time_rule)
                TaskService.create_task(task_name, survey.id, time_rule_id)
                DataManagement.getSurveyid(survey.id)
                response = {"status": "success"}
                self.set_status(200)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
Пример #11
0
    def post(self, instance_id):
        auth_response = authenticate(self, [Permissions.WRITE_RESPONSE])
        if auth_response["valid"]:
            data = json_decode(self.request.body)
            if 'response' in data:
                response = data['response']
                contact = data['contact']
            else:
                self.set_status(400)
                self.write('{"status":"error","message":"Missing response parameter"}')
                return
            
            instance = InstanceService.get_instance(instance_id)
            if instance is None:
                self.set_status(410)
                self.write('{"status":"error","message":"No response was expected for this survey"}')
                self.finish()
                return

            instance_id = instance.id  # Ensure that id is of right type
            state = StateService.get_next_state_in_instance(instance, Status.AWAITING_USER_RESPONSE)
            if state is not None and state.status is not Status.NO_RESPONSE_REQUIRED:
                survey = SurveyService.get_survey(instance.survey_id)
                if str(survey.owner_id) == auth_response["owner_id"]:
                    question_number = state.question_number
                    question_service = QuestionService()
                    question = question_service.get(survey.protocol_id, question_number)
                    now = datetime.now(tz=pytz.utc)
                    now_csv_entry = str(datetime.now(tz=pytz.utc))
                    loaddata = LoadData()
                    participant_id = loaddata.sendparticpantid(contact)
                    loaddata_response = LoadData1()
                    #loaddata_response.concatresponse(participant_id,question_number,response, now_csv_entry[:10],now_csv_entry[11:16])
                    if question is not None:

                        if question.final:
                            state.status = Status.TERMINATED_COMPLETE.value
                            StateService.update_state(state)

                            self.set_status(200)
                            self.write('{"status":"success","response_accepted":"False","reason":"Survey has finished"}')
                            self.flush()
                        elif state.timeout.replace(tzinfo=pytz.utc) < now:
                            state.status = Status.TERMINATED_TIMEOUT.value
                            state.save()
                            self.set_status(200)
                            self.write(
                                '{"status":"success","response_accepted":"False","reason":"Survey has timed out"}')
                        else:
                            state.status = Status.PROCESSING_USER_RESPONSE.value
                            StateService.update_state(state)
                            loaddata_response.concatresponse(participant_id,question_number,response, now_csv_entry[:10])
                            new_questions = question.process(response)
                            if new_questions == 'INV_RESP':
                                state.status = Status.AWAITING_USER_RESPONSE.value
                                StateService.update_state(state)

                                self.set_status(200)
                                self.write('{"status":"success","response_accepted":"False","reason":"Invalid Response","pass_along_message":"'
                                           + question.invalid_message + '"}')
                                self.flush()
                            else:
                                response_service = ResponseService()
                                variable_name = question.variable_name
                                survey_id = instance.survey_id
                                response_service.insert_response(survey_id, instance_id, variable_name, response)

                                if new_questions is not None:
                                    for new_question in new_questions:
                                        #print("Is this the final question", isFinal)
                                        #if not new_question.final:
                                        if not question.final:
                                            status = Status.CREATED_MID
                                        else:
                                            status = Status.NO_RESPONSE_REQUIRED

                                        StateService.create_state(instance_id, new_question[0][1], status,
                                                                  state.timeout, new_question[1])

                                state.status = Status.TERMINATED_COMPLETE.value
                                StateService.update_state(state)

                                new_state = StateService.get_next_state_in_instance(instance, Status.CREATED_MID)

                                new_state.status = Status.AWAITING_USER_RESPONSE.value
                                StateService.update_state(new_state)

                                self.set_status(200)
                                self.write('{"status":"success","response_accepted":"True"}')
                                self.flush()

                    else:
                        self.set_status(410, "No response was expected for this survey")
                        self.write('{"status":"error","message":"No response was expected for this survey"}')
                        self.finish()
                else:
                    self.set_status(403)
                    self.write('{"status":"error","message":"Owner does not have authorization to modify survey"}')
                    self.flush()
            else:
                self.set_status(410)
                self.write('{"status":"error","message":"No response was expected for this survey"}')
                self.finish()
Пример #12
0
from smsurvey.core.model.model import Model

from smsurvey import config
from smsurvey.core.services.instance_service import InstanceService
from smsurvey.core.services.owner_service import OwnerService
from smsurvey.core.services.enrollment_service import EnrollmentService
from smsurvey.core.services.survey_service import SurveyService
from smsurvey.core.services.protocol_service import ProtocolService

Model.from_database(config.DAO)

owner = OwnerService.get("sam", "mhealth")

enrollment = EnrollmentService.get_by_owner(owner.id)[0]
survey = SurveyService.create_survey(owner.id,
                                     ProtocolService.get_all_protocols()[0].id,
                                     enrollment.id, 1, 20, 1)

instances = InstanceService.create_instances(survey.id)