def _get_cases_changed_context(domain, form, case_id=None):
    case_blocks = extract_case_blocks(form)
    for i, block in enumerate(list(case_blocks)):
        if case_id and block.get(const.CASE_ATTR_ID) == case_id:
            case_blocks.pop(i)
            case_blocks.insert(0, block)
    cases = []
    for b in case_blocks:
        this_case_id = b.get(const.CASE_ATTR_ID)
        try:
            this_case = CaseAccessors(domain).get_case(
                this_case_id) if this_case_id else None
            valid_case = True
        except ResourceNotFound:
            this_case = None
            valid_case = False

        if this_case and this_case.case_id:
            url = reverse('case_details', args=[domain, this_case.case_id])
        else:
            url = "#"

        definition = get_default_definition(
            sorted_case_update_keys(b.keys()),
            assume_phonetimes=(
                not form.metadata
                or (form.metadata.deviceID != CLOUDCARE_DEVICE_ID)),
        )
        cases.append({
            "is_current_case":
            case_id and this_case_id == case_id,
            "name":
            case_inline_display(this_case),
            "table":
            get_tables_as_columns(b,
                                  definition,
                                  timezone=get_timezone_for_request()),
            "url":
            url,
            "valid_case":
            valid_case,
            "case_type":
            this_case.type if valid_case else None,
        })

    return {'cases': cases}
Example #2
0
def _get_form_metadata_context(domain, form, support_enabled=False):
    meta = _top_level_tags(form).get('meta', None) or {}
    meta['received_on'] = json_format_datetime(form.received_on)
    meta['server_modified_on'] = json_format_datetime(
        form.server_modified_on) if form.server_modified_on else ''
    if support_enabled:
        meta['last_sync_token'] = form.last_sync_token

    definition = get_default_definition(sorted_form_metadata_keys(list(meta)))
    form_meta_data = get_tables_as_columns(meta,
                                           definition,
                                           timezone=get_timezone_for_request())
    if getattr(form, 'auth_context', None):
        auth_context = AuthContext(form.auth_context)
        auth_context_user_id = auth_context.user_id
        auth_user_info = get_doc_info_by_id(domain, auth_context_user_id)
    else:
        auth_user_info = get_doc_info_by_id(domain, None)
        auth_context = AuthContext(
            user_id=None,
            authenticated=False,
            domain=domain,
        )
    meta_userID = meta.get('userID')
    meta_username = meta.get('username')
    if meta_userID == 'demo_user':
        user_info = DocInfo(
            domain=domain,
            display='demo_user',
        )
    elif meta_username == 'admin':
        user_info = DocInfo(
            domain=domain,
            display='admin',
        )
    else:
        user_info = get_doc_info_by_id(domain, meta_userID)

    return {
        "form_meta_data": form_meta_data,
        "auth_context": auth_context,
        "auth_user_info": auth_user_info,
        "user_info": user_info,
    }
Example #3
0
def render_form(form, domain, options):
    """
    Uses options since Django 1.3 doesn't seem to support templatetag kwargs.
    Change to kwargs when we're on a version of Django that does.

    """

    timezone = get_timezone_for_request()
    case_id = options.get('case_id')
    side_pane = options.get('side_pane', False)
    user = options.get('user', None)
    request = options.get('request', None)
    support_enabled = toggle_enabled(request, toggles.SUPPORT)

    _get_tables_as_columns = partial(get_tables_as_columns, timezone=timezone)

    # Form Data tab
    form_data, question_list_not_found = get_readable_data_for_submission(form)

    # Case Changes tab
    case_blocks = extract_case_blocks(form)
    for i, block in enumerate(list(case_blocks)):
        if case_id and block.get(const.CASE_ATTR_ID) == case_id:
            case_blocks.pop(i)
            case_blocks.insert(0, block)

    cases = []
    for b in case_blocks:
        this_case_id = b.get(const.CASE_ATTR_ID)
        try:
            this_case = CaseAccessors(domain).get_case(this_case_id) if this_case_id else None
            valid_case = True
        except ResourceNotFound:
            this_case = None
            valid_case = False

        if this_case and this_case.case_id:
            url = reverse('case_details', args=[domain, this_case.case_id])
        else:
            url = "#"

        definition = get_default_definition(
            sorted_case_update_keys(b.keys()),
            assume_phonetimes=(not form.metadata or
                               (form.metadata.deviceID != CLOUDCARE_DEVICE_ID)),
        )
        cases.append({
            "is_current_case": case_id and this_case_id == case_id,
            "name": case_inline_display(this_case),
            "table": _get_tables_as_columns(b, definition),
            "url": url,
            "valid_case": valid_case
        })

    # Form Metadata tab
    meta = _top_level_tags(form).get('meta', None) or {}
    meta['received_on'] = json_format_datetime(form.received_on)
    if support_enabled:
        meta['last_sync_token'] = form.last_sync_token

    definition = get_default_definition(sorted_form_metadata_keys(meta.keys()))
    form_meta_data = _get_tables_as_columns(meta, definition)
    if getattr(form, 'auth_context', None):
        auth_context = AuthContext(form.auth_context)
        auth_context_user_id = auth_context.user_id
        auth_user_info = get_doc_info_by_id(domain, auth_context_user_id)
    else:
        auth_user_info = get_doc_info_by_id(domain, None)
        auth_context = AuthContext(
            user_id=None,
            authenticated=False,
            domain=domain,
        )
    meta_userID = meta.get('userID')
    meta_username = meta.get('username')
    if meta_userID == 'demo_user':
        user_info = DocInfo(
            domain=domain,
            display='demo_user',
        )
    elif meta_username == 'admin':
        user_info = DocInfo(
            domain=domain,
            display='admin',
        )
    else:
        user_info = get_doc_info_by_id(domain, meta_userID)

    user_can_edit = (
        request and user and request.domain
        and (user.can_edit_data() or user.is_commcare_user())
    )
    show_edit_options = (
        user_can_edit
        and can_edit_form_location(domain, user, form)
    )
    show_edit_submission = (
        user_can_edit
        and has_privilege(request, privileges.DATA_CLEANUP)
        and not form.is_deprecated
    )

    show_resave = (
        user_can_edit and support_enabled
    )

    def _get_edit_info(instance):
        info = {
            'was_edited': False,
            'is_edit': False,
        }
        if instance.is_deprecated:
            info.update({
                'was_edited': True,
                'latest_version': instance.orig_id,
            })
        if getattr(instance, 'edited_on', None) and getattr(instance, 'deprecated_form_id', None):
            info.update({
                'is_edit': True,
                'edited_on': instance.edited_on,
                'previous_version': instance.deprecated_form_id
            })
        return info

    return render_to_string("reports/form/partials/single_form.html", {
        "context_case_id": case_id,
        "instance": form,
        "is_archived": form.is_archived,
        "edit_info": _get_edit_info(form),
        "domain": domain,
        'question_list_not_found': question_list_not_found,
        "form_data": form_data,
        "cases": cases,
        "form_table_options": {
            # todo: wells if display config has more than one column
            "put_loners_in_wells": False
        },
        "form_meta_data": form_meta_data,
        "auth_context": auth_context,
        "auth_user_info": auth_user_info,
        "user_info": user_info,
        "side_pane": side_pane,
        "show_edit_options": show_edit_options,
        "show_edit_submission": show_edit_submission,
        "show_resave": show_resave,
    }, RequestContext(request))
Example #4
0
    get_case_url = options['get_case_url']

    data = copy.deepcopy(wrapped_case.to_full_dict())

    default_properties = _get_tables_as_rows(data, display)

    dynamic_data = wrapped_case.dynamic_properties()

    for section in display:
        for row in section['layout']:
            for item in row:
                dynamic_data.pop(item.get("expr"), None)

    if dynamic_data:
        dynamic_keys = sorted(dynamic_data.keys())
        definition = get_default_definition(
            dynamic_keys, num_columns=DYNAMIC_CASE_PROPERTIES_COLUMNS)

        dynamic_properties = _get_tables_as_rows(dynamic_data, definition)
    else:
        dynamic_properties = None

    the_time_is_now = datetime.datetime.utcnow()
    tz_offset_ms = int(
        timezone.utcoffset(the_time_is_now).total_seconds()) * 1000
    tz_abbrev = timezone.localize(the_time_is_now).tzname()

    # ledgers
    def _product_name(product_id):
        try:
            return SQLProduct.objects.get(product_id=product_id).name
        except SQLProduct.DoesNotExist:
Example #5
0
def render_form(form, domain, options):
    """
    Uses options since Django 1.3 doesn't seem to support templatetag kwargs.
    Change to kwargs when we're on a version of Django that does.

    """

    timezone = get_timezone_for_request()
    case_id = options.get('case_id')
    side_pane = options.get('side_pane', False)
    user = options.get('user', None)
    request = options.get('request', None)
    support_enabled = toggle_enabled(request, toggles.SUPPORT)

    _get_tables_as_columns = partial(get_tables_as_columns, timezone=timezone)

    # Form Data tab
    form_data, question_list_not_found = get_readable_data_for_submission(form)

    # Case Changes tab
    case_blocks = extract_case_blocks(form)
    for i, block in enumerate(list(case_blocks)):
        if case_id and block.get(const.CASE_ATTR_ID) == case_id:
            case_blocks.pop(i)
            case_blocks.insert(0, block)

    cases = []
    for b in case_blocks:
        this_case_id = b.get(const.CASE_ATTR_ID)
        try:
            this_case = CaseAccessors(domain).get_case(
                this_case_id) if this_case_id else None
            valid_case = True
        except ResourceNotFound:
            this_case = None
            valid_case = False

        if this_case and this_case.case_id:
            url = reverse('case_details', args=[domain, this_case.case_id])
        else:
            url = "#"

        definition = get_default_definition(
            sorted_case_update_keys(b.keys()),
            assume_phonetimes=(
                not form.metadata
                or (form.metadata.deviceID != CLOUDCARE_DEVICE_ID)),
        )
        cases.append({
            "is_current_case": case_id and this_case_id == case_id,
            "name": case_inline_display(this_case),
            "table": _get_tables_as_columns(b, definition),
            "url": url,
            "valid_case": valid_case
        })

    # Form Metadata tab
    meta = _top_level_tags(form).get('meta', None) or {}
    meta['received_on'] = json_format_datetime(form.received_on)
    if support_enabled:
        meta['last_sync_token'] = form.last_sync_token

    definition = get_default_definition(sorted_form_metadata_keys(meta.keys()))
    form_meta_data = _get_tables_as_columns(meta, definition)
    if getattr(form, 'auth_context', None):
        auth_context = AuthContext(form.auth_context)
        auth_context_user_id = auth_context.user_id
        auth_user_info = get_doc_info_by_id(domain, auth_context_user_id)
    else:
        auth_user_info = get_doc_info_by_id(domain, None)
        auth_context = AuthContext(
            user_id=None,
            authenticated=False,
            domain=domain,
        )
    meta_userID = meta.get('userID')
    meta_username = meta.get('username')
    if meta_userID == 'demo_user':
        user_info = DocInfo(
            domain=domain,
            display='demo_user',
        )
    elif meta_username == 'admin':
        user_info = DocInfo(
            domain=domain,
            display='admin',
        )
    else:
        user_info = get_doc_info_by_id(domain, meta_userID)

    user_can_edit = (request and user and request.domain
                     and (user.can_edit_data() or user.is_commcare_user()))
    show_edit_options = (user_can_edit
                         and can_edit_form_location(domain, user, form))
    show_edit_submission = (user_can_edit
                            and has_privilege(request, privileges.DATA_CLEANUP)
                            and not form.is_deprecated)

    show_resave = (user_can_edit and support_enabled)

    def _get_edit_info(instance):
        info = {
            'was_edited': False,
            'is_edit': False,
        }
        if instance.is_deprecated:
            info.update({
                'was_edited': True,
                'latest_version': instance.orig_id,
            })
        if getattr(instance, 'edited_on', None) and getattr(
                instance, 'deprecated_form_id', None):
            info.update({
                'is_edit': True,
                'edited_on': instance.edited_on,
                'previous_version': instance.deprecated_form_id
            })
        return info

    return render_to_string(
        "reports/form/partials/single_form.html",
        {
            "context_case_id": case_id,
            "instance": form,
            "is_archived": form.is_archived,
            "edit_info": _get_edit_info(form),
            "domain": domain,
            'question_list_not_found': question_list_not_found,
            "form_data": form_data,
            "cases": cases,
            "form_table_options": {
                # todo: wells if display config has more than one column
                "put_loners_in_wells": False
            },
            "form_meta_data": form_meta_data,
            "auth_context": auth_context,
            "auth_user_info": auth_user_info,
            "user_info": user_info,
            "side_pane": side_pane,
            "show_edit_options": show_edit_options,
            "show_edit_submission": show_edit_submission,
            "show_resave": show_resave,
        },
        RequestContext(request))
Example #6
0
def render_case(case, options):
    """
    Uses options since Django 1.3 doesn't seem to support templatetag kwargs.
    Change to kwargs when we're on a version of Django that does.
    """
    from corehq.apps.hqwebapp.templatetags.proptable_tags import get_tables_as_rows, get_default_definition
    wrapped_case = get_wrapped_case(case)
    timezone = options.get('timezone', pytz.utc)
    timezone = timezone.localize(datetime.datetime.utcnow()).tzinfo
    _get_tables_as_rows = partial(get_tables_as_rows, timezone=timezone)
    display = options.get('display') or wrapped_case.get_display_config()
    show_transaction_export = options.get('show_transaction_export') or False
    get_case_url = options['get_case_url']

    data = copy.deepcopy(wrapped_case.to_full_dict())

    default_properties = _get_tables_as_rows(data, display)

    dynamic_data = wrapped_case.dynamic_properties()

    for section in display:
        for row in section['layout']:
            for item in row:
                dynamic_data.pop(item.get("expr"), None)

    if dynamic_data:
        dynamic_keys = sorted(dynamic_data.keys())
        definition = get_default_definition(
            dynamic_keys, num_columns=DYNAMIC_CASE_PROPERTIES_COLUMNS)

        dynamic_properties = _get_tables_as_rows(dynamic_data, definition)
    else:
        dynamic_properties = None

    the_time_is_now = datetime.datetime.utcnow()
    tz_offset_ms = int(timezone.utcoffset(the_time_is_now).total_seconds()) * 1000
    tz_abbrev = timezone.localize(the_time_is_now).tzname()

    # ledgers
    def _product_name(product_id):
        try:
            return SQLProduct.objects.get(product_id=product_id).name
        except SQLProduct.DoesNotExist:
            return (_('Unknown Product ("{}")').format(product_id))

    ledger_map = LedgerAccessors(case.domain).get_case_ledger_state(case.case_id, ensure_form_id=True)
    for section, product_map in ledger_map.items():
        product_tuples = sorted(
            (_product_name(product_id), product_map[product_id]) for product_id in product_map
        )
        ledger_map[section] = product_tuples

    return render_to_string("case/partials/single_case.html", {
        "default_properties": default_properties,
        "default_properties_options": {
            "style": "table"
        },
        "dynamic_properties": dynamic_properties,
        "dynamic_properties_options": {
            "style": "table"
        },
        "case": wrapped_case.case,
        "case_actions": mark_safe(json.dumps(wrapped_case.actions())),
        "timezone": timezone,
        "tz_abbrev": tz_abbrev,
        "case_hierarchy_options": {
            "show_view_buttons": True,
            "get_case_url": get_case_url,
            "timezone": timezone
        },
        "ledgers": ledger_map,
        "timezone_offset": tz_offset_ms,
        "show_transaction_export": show_transaction_export,
        "xform_api_url": reverse('single_case_forms', args=[case.domain, case.case_id]),
    })