def handle(self, *args, **options):
     sessions = SQLXFormsSession.objects.filter(
         Q(session_type__isnull=True) | Q(session_type=XFORMS_SESSION_SMS),
         end_time__isnull=True,
     ).all()
     for session in sessions:
         try:
             get_raw_instance(session.session_id)['output']
         except InvalidSessionIdException:
             print "Closing %s %s" % (session.domain, session._id)
             session.end(False)
             session.save()
         except Exception as e:
             print "An unexpected error occurred when processing %s %s" % (session.domain, session._id)
             print e
Example #2
0
 def handle(self, *args, **options):
     sessions = XFormsSession.view(
         "smsforms/open_sms_sessions_by_connection",
         include_docs=True).all()
     for session in sessions:
         try:
             get_raw_instance(session.session_id)
         except InvalidSessionIdException:
             print "Closing %s %s" % (session.domain, session._id)
             session.end(False)
             session.save()
         except Exception as e:
             print "An unexpected error occurred when processing %s %s" % (
                 session.domain, session._id)
             print e
 def handle(self, *args, **options):
     sessions = XFormsSession.view(
         "smsforms/open_sms_sessions_by_connection",
         include_docs=True
     ).all()
     for session in sessions:
         try:
             get_raw_instance(session.session_id)
         except InvalidSessionIdException:
             print "Closing %s %s" % (session.domain, session._id)
             session.end(False)
             session.save()
         except Exception as e:
             print "An unexpected error occurred when processing %s %s" % (session.domain, session._id)
             print e
Example #4
0
 def handle(self, **options):
     sessions = SQLXFormsSession.objects.filter(
         Q(session_type__isnull=True) | Q(session_type=XFORMS_SESSION_SMS),
         end_time__isnull=True,
     ).all()
     for session in sessions:
         try:
             get_raw_instance(session.session_id)['output']
         except InvalidSessionIdException:
             print("Closing %s %s" % (session.domain, session._id))
             session.end(False)
             session.save()
         except Exception as e:
             print("An unexpected error occurred when processing %s %s" %
                   (session.domain, session._id))
             print(e)
Example #5
0
def get_xml(request, session_id):
    try:
        session = get_raw_instance(session_id)
    except EntrySession.InvalidSessionIdException:
        session = None

    return json_response(session)
Example #6
0
def render_form(request, domain):
    # get session
    session_id = request.GET.get('session_id')

    session = get_object_or_404(EntrySession, session_id=session_id)

    try:
        raw_instance = get_raw_instance(session_id, domain)
    except Exception as e:
        return HttpResponse(e, status=500, content_type="text/plain")

    xmlns = raw_instance["xmlns"]
    form_data_xml = raw_instance["output"]

    _, form_data_json = xml2json(form_data_xml)
    pretty_questions = readable.get_questions(domain, session.app_id, xmlns)

    readable_form = readable.get_readable_form_data(form_data_json,
                                                    pretty_questions)

    rendered_readable_form = render_to_string(
        'reports/form/partials/readable_form.html',
        {'questions': readable_form})

    return json_response({
        'form_data': rendered_readable_form,
        'instance_xml': indent_xml(form_data_xml)
    })
Example #7
0
def render_form(request, domain):
    # get session
    session_id = request.GET.get('session_id')

    session = get_object_or_404(EntrySession, session_id=session_id)

    try:
        raw_instance = get_raw_instance(session_id, domain)
    except Exception, e:
        return HttpResponse(e, status=500, content_type="text/plain")
Example #8
0
def render_form(request, domain):
    # get session
    session_id = request.GET.get('session_id')

    session = get_object_or_404(EntrySession, session_id=session_id)

    try:
        raw_instance = get_raw_instance(session_id, domain)
    except Exception, e:
        return HttpResponse(e, status=500, content_type="text/plain")
Example #9
0
def submit_unfinished_form(session_id, include_case_side_effects=False):
    """
    Gets the raw instance of the session's form and submits it. This is used with
    sms and ivr surveys to save all questions answered so far in a session that
    needs to close.

    If include_case_side_effects is False, no case create / update / close actions
    will be performed, but the form will still be submitted.

    The form is only submitted if the smsforms session has not yet completed.
    """
    session = SQLXFormsSession.by_session_id(session_id)
    if session is not None and session.end_time is None:
        # Get and clean the raw xml
        try:
            xml = get_raw_instance(session_id)['output']
        except InvalidSessionIdException:
            session.end(completed=False)
            session.save()
            return
        root = XML(xml)
        case_tag_regex = re.compile("^(\{.*\}){0,1}case$") # Use regex in order to search regardless of namespace
        meta_tag_regex = re.compile("^(\{.*\}){0,1}meta$")
        timeEnd_tag_regex = re.compile("^(\{.*\}){0,1}timeEnd$")
        current_timstamp = json_format_datetime(datetime.utcnow())
        for child in root:
            if case_tag_regex.match(child.tag) is not None:
                # Found the case tag
                case_element = child
                case_element.set("date_modified", current_timstamp)
                if not include_case_side_effects:
                    # Remove case actions (create, update, close)
                    child_elements = [case_action for case_action in case_element]
                    for case_action in child_elements:
                        case_element.remove(case_action)
            elif meta_tag_regex.match(child.tag) is not None:
                # Found the meta tag, now set the value for timeEnd
                for meta_child in child:
                    if timeEnd_tag_regex.match(meta_child.tag):
                        meta_child.text = current_timstamp
        cleaned_xml = tostring(root)
        
        # Submit the xml and end the session
        resp = submit_form_locally(cleaned_xml, session.domain,
            app_id=session.app_id)
        xform_id = resp['X-CommCareHQ-FormID']
        session.end(completed=False)
        session.submission_id = xform_id
        session.save()
        
        # Tag the submission as a partial submission
        xform = XFormInstance.get(xform_id)
        xform.partial_submission = True
        xform.survey_incentive = session.survey_incentive
        xform.save()
Example #10
0
def submit_unfinished_form(session_id, include_case_side_effects=False):
    """
    Gets the raw instance of the session's form and submits it. This is used with
    sms and ivr surveys to save all questions answered so far in a session that
    needs to close.

    If include_case_side_effects is False, no case create / update / close actions
    will be performed, but the form will still be submitted.

    The form is only submitted if the smsforms session has not yet completed.
    """
    session = SQLXFormsSession.by_session_id(session_id)
    if session is not None and session.end_time is None:
        # Get and clean the raw xml
        try:
            xml = get_raw_instance(session_id)['output']
        except InvalidSessionIdException:
            session.end(completed=False)
            session.save()
            return
        root = XML(xml)
        case_tag_regex = re.compile("^(\{.*\}){0,1}case$") # Use regex in order to search regardless of namespace
        meta_tag_regex = re.compile("^(\{.*\}){0,1}meta$")
        timeEnd_tag_regex = re.compile("^(\{.*\}){0,1}timeEnd$")
        current_timstamp = json_format_datetime(datetime.utcnow())
        for child in root:
            if case_tag_regex.match(child.tag) is not None:
                # Found the case tag
                case_element = child
                case_element.set("date_modified", current_timstamp)
                if not include_case_side_effects:
                    # Remove case actions (create, update, close)
                    child_elements = [case_action for case_action in case_element]
                    for case_action in child_elements:
                        case_element.remove(case_action)
            elif meta_tag_regex.match(child.tag) is not None:
                # Found the meta tag, now set the value for timeEnd
                for meta_child in child:
                    if timeEnd_tag_regex.match(meta_child.tag):
                        meta_child.text = current_timstamp
        cleaned_xml = tostring(root)
        
        # Submit the xml and end the session
        resp = submit_form_locally(cleaned_xml, session.domain,
            app_id=session.app_id)
        xform_id = resp['X-CommCareHQ-FormID']
        session.end(completed=False)
        session.submission_id = xform_id
        session.save()
        
        # Tag the submission as a partial submission
        xform = XFormInstance.get(xform_id)
        xform.partial_submission = True
        xform.survey_incentive = session.survey_incentive
        xform.save()
Example #11
0
def submit_unfinished_form(session_id, include_case_side_effects=False):
    session = XFormsSession.latest_by_session_id(session_id)
    if session is not None and session.end_time is None:
        # Get and clean the raw xml
        try:
            xml = get_raw_instance(session_id)
        except InvalidSessionIdException:
            session.end(completed=False)
            session.save()
            return
        root = XML(xml)
        case_tag_regex = re.compile(
            "^(\{.*\}){0,1}case$"
        )  # Use regex in order to search regardless of namespace
        meta_tag_regex = re.compile("^(\{.*\}){0,1}meta$")
        timeEnd_tag_regex = re.compile("^(\{.*\}){0,1}timeEnd$")
        current_timstamp = json_format_datetime(datetime.utcnow())
        for child in root:
            if case_tag_regex.match(child.tag) is not None:
                # Found the case tag
                case_element = child
                case_element.set("date_modified", current_timstamp)
                if not include_case_side_effects:
                    # Remove case actions (create, update, close)
                    child_elements = [
                        case_action for case_action in case_element
                    ]
                    for case_action in child_elements:
                        case_element.remove(case_action)
            elif meta_tag_regex.match(child.tag) is not None:
                # Found the meta tag, now set the value for timeEnd
                for meta_child in child:
                    if timeEnd_tag_regex.match(meta_child.tag):
                        meta_child.text = current_timstamp
        cleaned_xml = tostring(root)

        # Submit the xml and end the session
        resp = submit_form_locally(cleaned_xml,
                                   session.domain,
                                   app_id=session.app_id)
        xform_id = resp['X-CommCareHQ-FormID']
        session.end(completed=False)
        session.submission_id = xform_id
        session.save()

        # Tag the submission as a partial submission
        xform = XFormInstance.get(xform_id)
        xform.partial_submission = True
        xform.survey_incentive = session.survey_incentive
        xform.save()
Example #12
0
def submit_unfinished_form(session_id, include_case_side_effects=False):
    session = XFormsSession.latest_by_session_id(session_id)
    if session is not None and session.end_time is None:
        # Get and clean the raw xml
        try:
            xml = get_raw_instance(session_id)
        except InvalidSessionIdException:
            session.end(completed=False)
            session.save()
            return
        root = XML(xml)
        case_tag_regex = re.compile("^(\{.*\}){0,1}case$") # Use regex in order to search regardless of namespace
        meta_tag_regex = re.compile("^(\{.*\}){0,1}meta$")
        timeEnd_tag_regex = re.compile("^(\{.*\}){0,1}timeEnd$")
        current_timstamp = json_format_datetime(datetime.utcnow())
        for child in root:
            if case_tag_regex.match(child.tag) is not None:
                # Found the case tag
                case_element = child
                case_element.set("date_modified", current_timstamp)
                if not include_case_side_effects:
                    # Remove case actions (create, update, close)
                    child_elements = [case_action for case_action in case_element]
                    for case_action in child_elements:
                        case_element.remove(case_action)
            elif meta_tag_regex.match(child.tag) is not None:
                # Found the meta tag, now set the value for timeEnd
                for meta_child in child:
                    if timeEnd_tag_regex.match(meta_child.tag):
                        meta_child.text = current_timstamp
        cleaned_xml = tostring(root)
        
        # Submit the xml and end the session
        resp = submit_form_locally(cleaned_xml, session.domain,
            app_id=session.app_id)
        xform_id = resp['X-CommCareHQ-FormID']
        session.end(completed=False)
        session.submission_id = xform_id
        session.save()
        
        # Tag the submission as a partial submission
        xform = XFormInstance.get(xform_id)
        xform.partial_submission = True
        xform.survey_incentive = session.survey_incentive
        xform.save()
Example #13
0
def _handle_xformresponse_error(response, msg, session, router, answer=None):
    """
    Attempts to retrieve whatever partial XForm Instance (raw XML) may exist 
    and posts it to couchforms.
    
    Also sets the session.error flag (and session.error_msg).
    """
    if not response.is_error:
        return
    session.error = True
    session.error_msg = str(response.error)[:255] #max_length in model
    session.save()
    session_id = response.session_id or session.session_id
    if response.status == 'http-error':
        # TODO: translate / customize
        err_resp = _("There was a server error. Please try again later")
        if session_id:
            partial = api.get_raw_instance(session_id)
            logger.error('HTTP ERROR. Attempted to get partial XForm instance. Content: %s' % partial)
            if partial:
                # fire off a the partial using the form-error signal
                form_error.send(sender="smsforms", session=session,form=unicode(partial).strip(), router=router)
            return _respond_and_end(err_resp, msg, session)
        else:
            msg.respond(err_resp)
            return True
    elif response.status == 'validation-error' and session:
        logger.debug('Handling Validation Error')
        last_response = api.current_question(session.session_id)
        if last_response.event and last_response.event.text_prompt:
            if answer:
                ret_msg = '%s:"%s" in "%s"' % (response.error, answer, 
                                               session.question_to_prompt(last_response))
            else:
                ret_msg = '%s for "%s"' % (response.error, 
                                           session.question_to_prompt(last_response))
        else:
            ret_msg = response.error
        return _respond_and_end(ret_msg, msg, session)