Beispiel #1
0
 def page_context(self):
     mobile_users = get_mobile_user_ids(self.domain)
     everyone = set(get_doc_ids_in_domain_by_class(self.domain, CommCareUser))
     deleted = everyone - mobile_users
     return {
         'deleted_mobile_workers': [get_doc_info_by_id(self.domain, id_) for id_ in deleted]
     }
Beispiel #2
0
 def template_context(self):
     return {
         'xforms_session': self.xforms_session,
         'contact': get_doc_info_by_id(self.domain, self.xforms_session.connection_id),
         'start_time': (ServerTime(self.xforms_session.start_time)
                        .user_time(self.timezone).done().strftime(SERVER_DATETIME_FORMAT)),
     }
Beispiel #3
0
    def page_context(self, **kwargs):
        stock_state_limit = 100
        stock_transaction_limit = 10000
        stock_state_limit_exceeded = False
        stock_transaction_limit_exceeded = False

        query = StockTransaction.objects.filter(report__domain=self.domain)
        if self.location_id:
            try:
                case_id = (SQLLocation.objects
                           .get(domain=self.domain, location_id=self.location_id)
                           .supply_point_id)
            except SQLLocation.DoesNotExist:
                messages.error(self.request, 'Your location id did not match a location')
            else:
                query = query.filter(case_id=case_id)

        stock_state_keys = [
            (txn.case_id, txn.section_id, txn.product_id)
            for txn in query
            .order_by('case_id', 'section_id', 'product_id')
            .distinct('case_id', 'section_id', 'product_id')
            [:stock_state_limit]
        ]
        if len(stock_state_keys) >= stock_state_limit:
            stock_state_limit_exceeded = True

        actions_by_stock_state_key = []
        stock_transaction_count = 0
        for stock_state_key in stock_state_keys:
            case_id, section_id, product_id = stock_state_key
            actions = [
                (
                    action.__class__.__name__,
                    action,
                    self.get_server_date_by_form_id(
                        action.stock_transaction.report.form_id),
                ) for action in
                plan_rebuild_stock_state(case_id, section_id, product_id)
            ]
            stock_transaction_count += len(actions)
            if stock_transaction_count > stock_transaction_limit:
                stock_transaction_limit_exceeded = True
                break
            actions_by_stock_state_key.append(
                ({'case_id': case_id, 'section_id': section_id,
                  'product_id': product_id},
                 actions,
                 get_doc_info_by_id(self.domain, case_id))
            )

        assert len(set(stock_state_keys)) == len(stock_state_keys)
        return {
            'actions_by_stock_state_key': actions_by_stock_state_key,
            'stock_state_limit_exceeded': stock_state_limit_exceeded,
            'stock_state_limit': stock_state_limit,
            'stock_transaction_limit_exceeded': stock_transaction_limit_exceeded,
            'stock_transaction_limit': stock_transaction_limit,
        }
Beispiel #4
0
 def _make_row(self, record, link):
     row = [
         '{} -> {}'.format(link.master_domain, link.linked_domain),
         server_to_user_time(record.date, self.timezone),
         self._make_model_cell(record),
         pretty_doc_info(get_doc_info_by_id(self.domain, record.user_id))
     ]
     return row
def get_display_data(data, prop_def, processors=None, timezone=pytz.utc):
    # when prop_def came from a couchdbkit document, it will be a LazyDict with
    # a broken pop method.  This conversion also has the effect of a shallow
    # copy, which we want.
    prop_def = dict(prop_def)

    default_processors = {
        'yesno': yesno,
        'doc_info': lambda value: pretty_doc_info(
            get_doc_info_by_id(data['domain'], value)
        )
    }
    processors = processors or {}
    processors.update(default_processors)

    def format_key(key):
        key = key.replace('_', ' ')
        return key.replace('-', ' ')

    expr = prop_def.pop('expr')
    name = prop_def.pop('name', format_key(expr))
    format = prop_def.pop('format', None)
    process = prop_def.pop('process', None)

    # todo: nested attributes, jsonpath, indexing into related documents
    val = data.get(expr, None)

    if prop_def.pop('parse_date', None):
        val = parse_date_or_datetime(val)
    is_utc = prop_def.pop('is_utc', True)
    if isinstance(val, datetime.datetime):
        if is_utc:
            if val.tzinfo is None:
                val = val.replace(tzinfo=pytz.utc)
            val = adjust_datetime_to_timezone(val, val.tzinfo, timezone.zone)
        else:
            val = val.replace(tzinfo=timezone)

    try:
        val = conditional_escape(processors[process](val))
    except KeyError:
        val = mark_safe(to_html(None, val, 
            timezone=timezone, key_format=format_key, collapse_lists=True,
            **prop_def))
    if format:
        val = mark_safe(format.format(val))

    return {
        "expr": expr,
        "name": name,
        "value": val
    }
Beispiel #6
0
def get_display_data(data, prop_def, processors=None, timezone=pytz.utc):
    # when prop_def came from a couchdbkit document, it will be a LazyDict with
    # a broken pop method.  This conversion also has the effect of a shallow
    # copy, which we want.
    prop_def = dict(prop_def)

    default_processors = {
        'yesno': yesno,
        'doc_info': lambda value: pretty_doc_info(
            get_doc_info_by_id(data['domain'], value)
        )
    }
    processors = processors or {}
    processors.update(default_processors)

    expr_name = _get_expr_name(prop_def)
    expr = prop_def.pop('expr')
    name = prop_def.pop('name', None) or _format_slug_string_for_display(expr)
    format = prop_def.pop('format', None)
    process = prop_def.pop('process', None)
    timeago = prop_def.get('timeago', False)
    has_history = prop_def.pop('has_history', False)

    val = eval_expr(expr, data)

    if prop_def.pop('parse_date', None):
        val = _parse_date_or_datetime(val)
    # is_utc is deprecated in favor of is_phone_time
    # but preserving here for backwards compatibility
    # is_utc = False is just reinterpreted as is_phone_time = True
    is_phone_time = prop_def.pop('is_phone_time',
                                 not prop_def.pop('is_utc', True))
    if isinstance(val, datetime.datetime):
        if not is_phone_time:
            val = ServerTime(val).user_time(timezone).done()
        else:
            val = PhoneTime(val, timezone).user_time(timezone).done()

    try:
        val = conditional_escape(processors[process](val))
    except KeyError:
        val = mark_safe(_to_html(val, timeago=timeago))
    if format:
        val = mark_safe(format.format(val))

    return {
        "expr": expr_name,
        "name": name,
        "value": val,
        "has_history": has_history,
    }
Beispiel #7
0
 def template_context(self):
     return {
         "xforms_session": self.xforms_session,
         "xform_instance": (
             XFormInstance.get(self.xforms_session.submission_id) if self.xforms_session.submission_id else None
         ),
         "contact": get_doc_info_by_id(self.domain, self.xforms_session.connection_id),
         "start_time": (
             ServerTime(self.xforms_session.start_time)
             .user_time(self.timezone)
             .done()
             .strftime(SERVER_DATETIME_FORMAT)
         ),
     }
Beispiel #8
0
    def page_context(self, **kwargs):
        stock_state_limit = 100
        stock_transaction_limit = 10000
        stock_state_limit_exceeded = False
        stock_transaction_limit_exceeded = False

        stock_state_keys = [
            (txn.case_id, txn.section_id, txn.product_id)
            for txn in
            StockTransaction.objects.filter(report__domain=self.domain)
            .order_by('case_id', 'section_id', 'product_id')
            .distinct('case_id', 'section_id', 'product_id')
            [:stock_state_limit]
        ]
        if len(stock_state_keys) >= stock_state_limit:
            stock_state_limit_exceeded = True

        actions_by_stock_state_key = []
        stock_transaction_count = 0
        for stock_state_key in stock_state_keys:
            case_id, section_id, product_id = stock_state_key
            actions = [
                (
                    action.__class__.__name__,
                    action,
                    self.get_server_date_by_form_id(
                        action.stock_transaction.report.form_id),
                ) for action in
                plan_rebuild_stock_state(case_id, section_id, product_id)
            ]
            stock_transaction_count += len(actions)
            if stock_transaction_count > stock_transaction_limit:
                stock_transaction_limit_exceeded = True
                break
            actions_by_stock_state_key.append(
                ({'case_id': case_id, 'section_id': section_id,
                  'product_id': product_id},
                 actions,
                 get_doc_info_by_id(self.domain, case_id))
            )

        assert len(set(stock_state_keys)) == len(stock_state_keys)
        return {
            'actions_by_stock_state_key': actions_by_stock_state_key,
            'stock_state_limit_exceeded': stock_state_limit_exceeded,
            'stock_state_limit': stock_state_limit,
            'stock_transaction_limit_exceeded': stock_transaction_limit_exceeded,
            'stock_transaction_limit': stock_transaction_limit,
        }
Beispiel #9
0
    def handle(self, domain, **options):
        mobile_users = get_mobile_user_ids(domain)
        everyone = set(get_doc_ids_in_domain_by_class(domain, CommCareUser))
        deleted = everyone - mobile_users
        # See also corehq.apps.dump_reload.management.commands.print_domain_stats._get_couchdb_counts

        id_ = None
        for id_ in deleted:
            if options['with_usernames']:
                doc_info = get_doc_info_by_id(domain, id_)
                print(id_, doc_info.display)
            else:
                print(id_)
        if id_ is None:
            print('Domain "{}" has no deleted users'.format(domain))
Beispiel #10
0
 def get_actions_by_stock_state_key(self, case_id, section_id, product_id):
     actions = [
         (
             action.__class__.__name__,
             action,
             self.get_server_date_by_form_id(
                 action.stock_transaction.report.form_id),
         ) for action in
         plan_rebuild_stock_state(case_id, section_id, product_id)
     ]
     return (
         {'case_id': case_id,
          'section_id': section_id,
          'product_id': product_id},
         actions,
         get_doc_info_by_id(self.domain, case_id)
     )
Beispiel #11
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.
    
    """
    # don't actually use the passed in timezone since we assume form submissions already come
    # in in local time.
    # todo: we should revisit this when we properly handle timezones in form processing.
    timezone = pytz.utc
    case_id = options.get('case_id')
    side_pane = options.get('side_pane', False)
    user = options.get('user', None)

    _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 = CommCareCase.get(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._id:
            url = reverse('case_details', args=[domain, this_case._id])
        else:
            url = "#"

        definition = get_definition(sorted_case_update_keys(b.keys()))
        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 = form.top_level_tags().get('meta', None) or {}
    definition = get_definition(sorted_form_metadata_keys(meta.keys()))
    form_meta_data = _get_tables_as_columns(meta, definition)
    if 'auth_context' in form:
        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)

    request = options.get('request', None)
    user_can_edit = (
        request and user and request.domain
        and (user.can_edit_data() or user.is_commcare_user())
    )
    show_edit_submission = (
        user_can_edit
        and has_privilege(request, privileges.CLOUDCARE)
        and toggle_enabled(request, toggles.EDIT_SUBMISSIONS)
    )
    # stuffing this in the same flag as case rebuild
    show_resave = (
        user_can_edit and toggle_enabled(request, toggles.CASE_REBUILD)
    )
    return render_to_string("reports/form/partials/single_form.html", {
        "context_case_id": case_id,
        "instance": form,
        "is_archived": form.doc_type == "XFormArchived",
        "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,
        "user": user,
        "show_edit_submission": show_edit_submission,
        "show_resave": show_resave,
    })
Beispiel #12
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))
Beispiel #13
0
        collections.namedtuple("DisplayProcessor", "processor, returns_html")):
    def __call__(self, value, data):
        return self.processor(value, data)


VALUE_DISPLAY_PROCESSORS = {
    'date':
    DisplayProcessor(lambda value, data: _parse_date_or_datetime(value),
                     False),
    'yesno':
    DisplayProcessor(lambda value, data: conditional_escape(yesno(value)),
                     False),
    'doc_info':
    DisplayProcessor(
        lambda value, data: pretty_doc_info(
            get_doc_info_by_id(data['domain'], value)), True)
}

register = template.Library()


def _is_list_like(val):
    return isinstance(val, collections.Iterable) and not isinstance(val, str)


def _parse_date_or_datetime(val):
    def parse():
        if not val:
            return None

        # datetime is a subclass of date
Beispiel #14
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.
    
    """
    # don't actually use the passed in timezone since we assume form submissions already come
    # in in local time.
    # todo: we should revisit this when we properly handle timezones in form processing.
    timezone = pytz.utc
    case_id = options.get('case_id')
    side_pane = options.get('side_pane', False)
    user = options.get('user', None)
    case_id_attr = "@%s" % const.CASE_TAG_ID

    _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(case_id_attr) == case_id:
            case_blocks.pop(i)
            case_blocks.insert(0, block)

    cases = []
    for b in case_blocks:
        this_case_id = b.get(case_id_attr)
        try:
            this_case = CommCareCase.get(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._id:
            url = reverse('case_details', args=[domain, this_case._id])
        else:
            url = "#"

        definition = get_definition(sorted_case_update_keys(b.keys()))
        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 = form.top_level_tags().get('meta', None) or {}
    definition = get_definition(sorted_form_metadata_keys(meta.keys()))
    form_meta_data = _get_tables_as_columns(meta, definition)
    if 'auth_context' in form:
        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)

    edit_session_data = {'user_id': meta_userID}
    if len(case_blocks) == 1 and case_blocks[0].get(case_id_attr):
        edit_session_data["case_id"] = case_blocks[0].get(case_id_attr)

    return render_to_string("reports/form/partials/single_form.html", {
        "context_case_id": case_id,
        "instance": form,
        "form_meta": options.get('form_meta', {}),
        "maps_api_key": settings.GMAPS_API_KEY,
        "is_archived": form.doc_type == "XFormArchived",
        "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,
        "user": user,
        "edit_session_data": edit_session_data,
        "request": options.get('request', None),  # needed for toggles
    })
Beispiel #15
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.
    
    """
    # don't actually use the passed in timezone since we assume form submissions already come
    # in in local time.
    # todo: we should revisit this when we properly handle timezones in form processing.
    timezone = pytz.utc
    case_id = options.get('case_id')

    case_id_attr = "@%s" % const.CASE_TAG_ID

    _get_tables_as_columns = partial(get_tables_as_columns, timezone=timezone)

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

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

    cases = []
    for b in case_blocks:
        this_case_id = b.get(case_id_attr)
        try:
            this_case = CommCareCase.get(
                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._id:
            url = reverse('case_details', args=[domain, this_case._id])
        else:
            url = "#"

        definition = get_definition(sorted_case_update_keys(b.keys()))
        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 = form.top_level_tags().get('meta', {})
    definition = get_definition(sorted_form_metadata_keys(meta.keys()))
    form_meta_data = _get_tables_as_columns(meta, definition)
    if 'auth_context' in form:
        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 render_to_string(
        "reports/form/partials/single_form.html",
        {
            "context_case_id": case_id,
            "instance": form,
            "is_archived": form.doc_type == "XFormArchived",
            "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,
        })
Beispiel #16
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))
Beispiel #17
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.
    
    """
    # don't actually use the passed in timezone since we assume form submissions already come
    # in in local time.
    # todo: we should revisit this when we properly handle timezones in form processing.
    timezone = pytz.utc
    case_id = options.get('case_id')

    readable_form_data = READABLE_FORM_DATA.enabled(domain)
    use_old_reason = ''

    case_id_attr = "@%s" % const.CASE_TAG_ID

    _get_tables_as_columns = partial(get_tables_as_columns, timezone=timezone)

    form_dict = form.top_level_tags()
    form_dict.pop('change', None)  # this data already in Case Changes tab
    # Form Data tab
    if readable_form_data:
        try:
            form_data = get_readable_form_data(form)
        except QuestionListNotFound as e:
            readable_form_data = False
            use_old_reason = e.message

    if not readable_form_data:
        form_keys = [k for k in form_dict.keys() if form_key_filter(k)]
        form_data = _get_tables_as_columns(form_dict, get_definition(form_keys))

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

    cases = []
    for b in case_blocks:
        this_case_id = b.get(case_id_attr)
        try:
            this_case = CommCareCase.get(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._id:
            url = reverse('case_details', args=[domain, this_case._id])
        else:
            url = "#"

        definition = get_definition(sorted_case_update_keys(b.keys()))
        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 = form_dict.pop('meta', {})
    definition = get_definition(sorted_form_metadata_keys(meta.keys()))
    form_meta_data = _get_tables_as_columns(meta, definition)
    if 'auth_context' in form:
        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 render_to_string("reports/form/partials/single_form.html", {
        "context_case_id": case_id,
        "instance": form,
        "is_archived": form.doc_type == "XFormArchived",
        "domain": domain,
        'readable_form_data': readable_form_data,
        'use_old_reason': use_old_reason,
        "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,
    })