Ejemplo n.º 1
0
    def __init__(self, domain_object, *args, **kwargs):
        self.domain_object = domain_object
        self.can_user_access_all_locations = True
        if 'couch_user' in kwargs:
            couch_user = kwargs.pop('couch_user')
            self.can_user_access_all_locations = couch_user.has_permission(
                domain_object.name, 'access_all_locations')
        super(DashboardFeedFilterForm, self).__init__(*args, **kwargs)

        self.can_restrict_access_by_location = domain_object.has_privilege(
            privileges.RESTRICT_ACCESS_BY_LOCATION)

        if not self.can_restrict_access_by_location or not self.can_user_access_all_locations:
            del self.fields['update_location_restriction']

        self.fields['emwf_case_filter'].widget.set_url(
            reverse(CaseListFilter.options_url,
                    args=(self.domain_object.name, )))
        self.fields['emwf_form_filter'].widget.set_url(
            reverse(ExpandedMobileWorkerFilter.options_url,
                    args=(self.domain_object.name, )))

        self.helper = HQModalFormHelper()
        self.helper.form_tag = False
        self.helper.label_class = 'col-sm-3 col-md-2'
        self.helper.field_class = 'col-sm-9 col-md-10 col-lg-10'
        self.helper.layout = crispy.Layout(*self.layout_fields)
Ejemplo n.º 2
0
    def __init__(self, domain_object, *args, **kwargs):
        self.domain_object = domain_object
        super(DashboardFeedFilterForm, self).__init__(*args, **kwargs)

        self.fields['emwf_case_filter'].widget.set_url(
            reverse(CaseListFilter.options_url,
                    args=(self.domain_object.name, )))
        self.fields['emwf_form_filter'].widget.set_url(
            reverse(ExpandedMobileWorkerFilter.options_url,
                    args=(self.domain_object.name, )))

        self.helper = HQModalFormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(*self.layout_fields)
Ejemplo n.º 3
0
    def init_form(self, post_dict=None):
        fields = OrderedDict()
        for field in self.fields:
            fields[field.slug] = self._make_field(field)

        if self.angular_model:
            field_names = [

                Field(
                    field_name,
                    ng_model="{}.{}".format(self.angular_model, field_name),
                    ng_required="true" if field.required else "false"
                )
                for field_name, field in fields.items()
            ]
        else:
            field_names = list(fields)

        CustomDataForm = type('CustomDataForm' if six.PY3 else b'CustomDataForm', (forms.Form,), fields)
        if self.angular_model:
            CustomDataForm.helper = HQModalFormHelper()
        else:
            CustomDataForm.helper = HQFormHelper()
        CustomDataForm.helper.form_tag = False

        additional_fields = []
        if field_names:
            additional_fields.append(Fieldset(_("Additional Information"), *field_names))
        if post_dict is None:
            additional_fields.append(self.uncategorized_form)
        CustomDataForm.helper.layout = Layout(
            *additional_fields
        )

        CustomDataForm._has_uncategorized = bool(self.uncategorized_form) and post_dict is None

        if post_dict:
            fields = post_dict
        elif self.existing_custom_data is not None:
            fields = add_prefix(self.existing_custom_data, self.prefix)
        else:
            fields = None

        self.form = CustomDataForm(fields, prefix=self.prefix)
        return self.form
Ejemplo n.º 4
0
    def __init__(self, has_form_export_permissions,
                 has_case_export_permissions, *args, **kwargs):
        self.has_form_export_permissions = has_form_export_permissions
        self.has_case_export_permissions = has_case_export_permissions
        super(CreateExportTagForm, self).__init__(*args, **kwargs)

        # We shouldn't ever be showing this form if the user has neither permission
        assert self.has_case_export_permissions or self.has_form_export_permissions
        if not (self.has_case_export_permissions
                and self.has_form_export_permissions):
            model_field = self.fields['model_type']
            if self.has_form_export_permissions:
                model_field.initial = "form"
            if self.has_case_export_permissions:
                model_field.initial = 'case'

            model_field.widget.attrs['readonly'] = True
            model_field.widget.attrs['disabled'] = True

        self.helper = HQModalFormHelper()
        self.helper.form_tag = False

        self.helper.layout = crispy.Layout(
            crispy.Div(
                crispy.Field(
                    'model_type',
                    placeholder=_('Select model type'),
                    data_bind="value: modelType",
                ),
                data_bind="visible: !staticModelType",
            ),
            crispy.Div(
                crispy.Div(
                    crispy.Field(
                        'app_type',
                        placeholder=_("Select Application Type"),
                        data_bind=
                        "value: appType, event: {change: updateAppChoices}",
                    ),
                    data_bind="visible: showAppType()",
                ),
                crispy.Field(
                    'application',
                    placeholder=_("Select Application"),
                    data_bind="value: application",
                ),
                crispy.Div(  # Form export fields
                    crispy.Field(
                        'module',
                        placeholder=_("Select Menu"),
                        data_bind="value: module, disable: !application()",
                    ),
                    crispy.Field(
                        'form',
                        placeholder=_("Select Form"),
                        data_bind='''
                            value: form,
                            disable: !module(),
                        ''',
                    ),
                    data_bind="visible: isFormModel()",
                ),
                crispy.Div(  # Case export fields
                    crispy.Field(
                        'case_type',
                        placeholder=_("Select Case Type"),
                        data_bind='''
                            value: caseType,
                            disable: !application(),
                        ''',
                    ),
                    data_bind="visible: isCaseModel()",
                ),
                data_bind="visible: modelType()",
            ))
Ejemplo n.º 5
0
    def __init__(self, project, request_user, *args, **kwargs):
        super(NewMobileWorkerForm, self).__init__(*args, **kwargs)
        email_string = "@{}.commcarehq.org".format(project.name)
        max_chars_username = 80 - len(email_string)
        self.project = project
        self.domain = self.project.name
        self.request_user = request_user
        self.can_access_all_locations = request_user.has_permission(
            self.domain, 'access_all_locations')
        if not self.can_access_all_locations:
            self.fields['location_id'].required = True

        if self.project.strong_mobile_passwords:
            # Use normal text input so auto-generated strong password is visible
            self.fields['new_password'].widget = forms.TextInput()
            self.fields['new_password'].help_text = mark_safe_lazy(
                string_concat(
                    '<i class="fa fa-warning"></i>',
                    ugettext_lazy(
                        'This password is automatically generated. Please copy it or create your own. It will not be shown again.'
                    ), '<br />'))

        if project.uses_locations:
            self.fields['location_id'].widget = forms.Select()
            location_field = crispy.Field(
                'location_id',
                data_bind='value: location_id',
                data_query_url=reverse('location_search', args=[self.domain]),
            )
        else:
            location_field = crispy.Hidden(
                'location_id',
                '',
                data_bind='value: location_id',
            )

        self.helper = HQModalFormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Fieldset(
                _('Basic Information'),
                crispy.Div(crispy.Field(
                    'username',
                    data_bind="value: username, valueUpdate: 'keyup'",
                    maxlength=max_chars_username,
                ),
                           data_bind='''
                        css: {
                            'has-pending': $root.usernameAvailabilityStatus() === $root.STATUS.PENDING,
                            'has-success': $root.usernameAvailabilityStatus() === $root.STATUS.SUCCESS,
                            'has-warning': $root.usernameAvailabilityStatus() === $root.STATUS.WARNING,
                            'has-error': $root.usernameAvailabilityStatus() === $root.STATUS.ERROR,
                        },
                    '''),
                crispy.Field(
                    'first_name',
                    data_bind='value: first_name',
                ),
                crispy.Field(
                    'last_name',
                    data_bind='value: last_name',
                ),
                location_field,
                crispy.Div(hqcrispy.B3MultiField(
                    _("Password"),
                    InlineField(
                        'new_password',
                        data_bind="value: password, valueUpdate: 'input'",
                    ),
                    crispy.HTML('''
                            <p class="help-block" data-bind="if: $root.isSuggestedPassword">
                                <i class="fa fa-warning"></i> {suggested}
                            </p>
                            <p class="help-block" data-bind="ifnot: $root.isSuggestedPassword()">
                                <!-- ko if: $root.passwordStatus() === $root.STATUS.SUCCESS -->
                                    <i class="fa fa-check"></i> {strong}
                                <!-- /ko -->
                                <!-- ko ifnot: $root.useDraconianSecurity() -->
                                    <!-- ko if: $root.passwordStatus() === $root.STATUS.WARNING -->
                                        {almost}
                                    <!-- /ko -->
                                    <!-- ko if: $root.passwordStatus() === $root.STATUS.ERROR -->
                                        <i class="fa fa-warning"></i> {weak}
                                    <!-- /ko -->
                                <!-- /ko -->

                                <!-- ko if: $root.useDraconianSecurity() -->
                                    <!-- ko if: $root.passwordStatus() === $root.STATUS.ERROR -->
                                        <i class="fa fa-warning"></i> {rules}
                                    <!-- /ko -->
                                <!-- /ko -->
                            </p>
                        '''.format(
                        suggested=_(
                            "This password is automatically generated. Please copy it or create "
                            "your own. It will not be shown again."),
                        strong=_("Good Job! Your password is strong!"),
                        almost=
                        _("Your password is almost strong enough! Try adding numbers or symbols!"
                          ),
                        weak=
                        _("Your password is too weak! Try adding numbers or symbols!"
                          ),
                        rules=_(
                            "Password Requirements: 1 special character, 1 number, 1 capital letter, "
                            "minimum length of 8 characters."),
                    )),
                    required=True,
                ),
                           data_bind='''
                        css: {
                            'has-success': $root.passwordStatus() === $root.STATUS.SUCCESS,
                            'has-warning': $root.passwordStatus() === $root.STATUS.WARNING,
                            'has-error': $root.passwordStatus() === $root.STATUS.ERROR,
                        }
                    '''),
            ))
Ejemplo n.º 6
0
    def init_form(self, post_dict=None):
        fields = OrderedDict()
        if domain_has_privilege(self.domain, privileges.APP_USER_PROFILES):
            profiles = self.model.get_profiles()
            if profiles:
                attrs = {
                    'data-placeholder': _('Select a profile'),
                    'data-allow-clear': 'true',
                }
                if not self.ko_model:
                    attrs.update({'class': 'hqwebapp-select2'})
                fields[PROFILE_SLUG] = forms.IntegerField(
                    label=_('Profile'),
                    required=False,
                    widget=Select(choices=[(p.id, p.name) for p in profiles],
                                  attrs=attrs))
        for field in self.fields:
            fields[field.slug] = self._make_field(field)

        if self.ko_model:
            field_names = []
            for field_name, field in fields.items():
                data_binds = [
                    f"value: {self.ko_model}.{field_name}.value",
                    f"disable: {self.ko_model}.{field_name}.disable",
                ]
                if hasattr(field, 'choices') or field_name == PROFILE_SLUG:
                    data_binds.append("select2: " + json.dumps([{
                        "id": id,
                        "text": text
                    } for id, text in field.widget.choices]))
                field_names.append(
                    Field(field_name, data_bind=", ".join(data_binds)))
        else:
            field_names = list(fields)

        CustomDataForm = type('CustomDataForm', (forms.Form, ), fields)
        if self.ko_model:
            CustomDataForm.helper = HQModalFormHelper()
        else:
            CustomDataForm.helper = HQFormHelper()
        CustomDataForm.helper.form_tag = False

        additional_fields = []
        if field_names:
            additional_fields.append(
                Fieldset(_("Additional Information"),
                         *field_names,
                         css_class="custom-data-fieldset"))
        if post_dict is None:
            additional_fields.append(self.uncategorized_form)
        CustomDataForm.helper.layout = Layout(*additional_fields)

        CustomDataForm._has_uncategorized = bool(
            self.uncategorized_form) and post_dict is None

        if post_dict:
            fields = post_dict.copy()  # make mutable
        elif self.existing_custom_data is not None:
            fields = add_prefix(self.existing_custom_data, self.prefix)
        else:
            fields = None

        # Add profile fields so that form validation passes
        if fields:
            try:
                profile_fields = CustomDataFieldsProfile.objects.get(
                    id=int(fields.get(with_prefix(PROFILE_SLUG, self.prefix))),
                    definition__field_type=self.field_view.field_type,
                    definition__domain=self.domain,
                ).fields
            except (ValueError, TypeError,
                    CustomDataFieldsProfile.DoesNotExist):
                profile_fields = {}
            fields.update(add_prefix(profile_fields, self.prefix))

        self.form = CustomDataForm(fields, prefix=self.prefix)
        return self.form
Ejemplo n.º 7
0
    def __init__(self, project, request_user, *args, **kwargs):
        super(NewMobileWorkerForm, self).__init__(*args, **kwargs)
        email_string = "@{}.commcarehq.org".format(project.name)
        max_chars_username = 80 - len(email_string)
        self.project = project
        self.domain = self.project.name
        self.request_user = request_user
        self.can_access_all_locations = request_user.has_permission(self.domain, 'access_all_locations')
        if not self.can_access_all_locations:
            self.fields['location_id'].required = True

        if self.project.strong_mobile_passwords:
            if settings.ENABLE_DRACONIAN_SECURITY_FEATURES:
                validator = "validate_password_draconian"
            else:
                validator = "validate_password_standard"
            self.fields['password'].widget = forms.TextInput(attrs={
                validator: "",
                "ng_keydown": "markNonDefault()",
                "class": "default",
            })
            self.fields['password'].help_text = mark_safe_lazy(string_concat('<i class="fa fa-warning"></i>',
                ugettext_lazy('This password is automatically generated. Please copy it or create your own. It will not be shown again.'),
                '<br />'
            ))

        if project.uses_locations:
            self.fields['location_id'].widget = forms.Select(choices=[('', '')])    # blank option for placeholder
            location_field = crispy.Field(
                'location_id',
                ng_model='mobileWorker.location_id',
                ng_required="true" if self.fields['location_id'].required else "false",
            )
        else:
            location_field = crispy.Hidden(
                'location_id',
                '',
                ng_model='mobileWorker.location_id',
            )

        self.helper = HQModalFormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Fieldset(
                _('Basic Information'),
                crispy.Field(
                    'username',
                    ng_required="true",
                    validate_username="",
                    # What this says is, update as normal or when the element
                    # loses focus. If the update is normal, wait 300 ms to
                    # send the request again. If the update is on blur,
                    # send the request.
                    ng_model_options="{ "
                                      " updateOn: 'default blur', "
                                      " debounce: {'default': 300, 'blur': 0} "
                                      "}",
                    ng_model='mobileWorker.username',
                    ng_maxlength=max_chars_username,
                    maxlength=max_chars_username,
                ),
                crispy.Field(
                    'first_name',
                    ng_required="false",
                    ng_model='mobileWorker.first_name',
                    ng_maxlength="30",
                ),
                crispy.Field(
                    'last_name',
                    ng_required="false",
                    ng_model='mobileWorker.last_name',
                    ng_maxlength="30",
                ),
                location_field,
                crispy.Field(
                    'password',
                    ng_required="true",
                    ng_model='mobileWorker.password',
                    data_bind="value: password, valueUpdate: 'input'",
                ),
            )
        )
Ejemplo n.º 8
0
    def __init__(self, project, request_user, *args, **kwargs):
        super(NewMobileWorkerForm, self).__init__(*args, **kwargs)
        email_string = "@{}.{}".format(project.name, settings.HQ_ACCOUNT_ROOT)
        max_chars_username = 80 - len(email_string)
        self.project = project
        self.domain = self.project.name
        self.request_user = request_user
        self.can_access_all_locations = request_user.has_permission(self.domain, 'access_all_locations')
        if not self.can_access_all_locations:
            self.fields['location_id'].required = True

        if self.project.strong_mobile_passwords:
            # Use normal text input so auto-generated strong password is visible
            self.fields['new_password'].widget = forms.TextInput()
            self.fields['new_password'].help_text = mark_safe_lazy(
                format_lazy(
                    '<i class="fa fa-warning"></i>{}<br />',
                    ugettext_lazy(
                        'This password is automatically generated. '
                        'Please copy it or create your own. It will not be shown again.'),
                )
            )

        if project.uses_locations:
            self.fields['location_id'].widget = forms.Select()
            location_field = crispy.Field(
                'location_id',
                data_bind='value: location_id',
                data_query_url=reverse('location_search', args=[self.domain]),
            )
        else:
            location_field = crispy.Hidden(
                'location_id',
                '',
                data_bind='value: location_id',
            )

        self.two_stage_provisioning_enabled = TWO_STAGE_USER_PROVISIONING.enabled(self.domain)
        if self.two_stage_provisioning_enabled:
            confirm_account_field = crispy.Field(
                'force_account_confirmation',
                data_bind='checked: force_account_confirmation',
            )
            email_field = crispy.Div(
                crispy.Field(
                    'email',
                    data_bind="value: email, valueUpdate: 'keyup'",
                ),
                data_bind='''
                    css: {
                        'has-error': $root.emailStatus() === $root.STATUS.ERROR,
                    },
                '''
            )
            send_email_field = crispy.Field(
                'send_account_confirmation_email',
                data_bind='checked: send_account_confirmation_email, enable: sendConfirmationEmailEnabled',
            )
        else:
            confirm_account_field = crispy.Hidden(
                'force_account_confirmation',
                '',
                data_bind='value: force_account_confirmation',
            )
            email_field = crispy.Hidden(
                'email',
                '',
                data_bind='value: email',
            )
            send_email_field = crispy.Hidden(
                'send_account_confirmation_email',
                '',
                data_bind='value: send_account_confirmation_email',
            )


        self.helper = HQModalFormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Fieldset(
                _('Basic Information'),
                crispy.Div(
                    crispy.Field(
                        'username',
                        data_bind="value: username, valueUpdate: 'keyup'",
                        maxlength=max_chars_username,
                    ),
                    data_bind='''
                        css: {
                            'has-pending': $root.usernameAvailabilityStatus() === $root.STATUS.PENDING,
                            'has-success': $root.usernameAvailabilityStatus() === $root.STATUS.SUCCESS,
                            'has-warning': $root.usernameAvailabilityStatus() === $root.STATUS.WARNING,
                            'has-error': $root.usernameAvailabilityStatus() === $root.STATUS.ERROR,
                        },
                    '''
                ),
                crispy.Field(
                    'first_name',
                    data_bind='value: first_name',
                ),
                crispy.Field(
                    'last_name',
                    data_bind='value: last_name',
                ),
                location_field,
                confirm_account_field,
                email_field,
                send_email_field,
                crispy.Div(
                    hqcrispy.B3MultiField(
                        _("Password"),
                        InlineField(
                            'new_password',
                            data_bind="value: password, valueUpdate: 'input', enable: passwordEnabled",
                        ),
                        crispy.HTML('''
                            <p class="help-block" data-bind="if: $root.isSuggestedPassword">
                                <i class="fa fa-warning"></i> {suggested}
                            </p>
                            <p class="help-block" data-bind="ifnot: $root.isSuggestedPassword()">
                                <!-- ko ifnot: $root.skipStandardValidations() -->
                                    <!-- ko if: $root.passwordStatus() === $root.STATUS.SUCCESS -->
                                        <i class="fa fa-check"></i> {strong}
                                    <!-- /ko -->
                                    <!-- ko if: $root.passwordStatus() === $root.STATUS.WARNING -->
                                        {almost}
                                    <!-- /ko -->
                                    <!-- ko if: $root.passwordStatus() === $root.STATUS.ERROR -->
                                        <i class="fa fa-warning"></i> {weak}
                                    <!-- /ko -->
                                <!-- /ko -->

                                <!-- ko if: $root.skipStandardValidations() -->
                                    <i class="fa fa-info-circle"></i> {custom_warning}
                                <!-- /ko -->
                                <!-- ko if: $root.passwordStatus() === $root.STATUS.DISABLED -->
                                    <i class="fa fa-warning"></i> {disabled}
                                <!-- /ko -->
                            </p>
                        '''.format(
                            suggested=_("This password is automatically generated. Please copy it or create "
                                "your own. It will not be shown again."),
                            strong=_("Good Job! Your password is strong!"),
                            almost=_("Your password is almost strong enough! Try adding numbers or symbols!"),
                            weak=_("Your password is too weak! Try adding numbers or symbols!"),
                            custom_warning=_(settings.CUSTOM_PASSWORD_STRENGTH_MESSAGE),
                            disabled=_("Setting a password is disabled. "
                                       "The user will set their own password on confirming their account email."),
                        )),
                        required=True,
                    ),
                    data_bind='''
                        css: {
                            'has-success': $root.passwordStatus() === $root.STATUS.SUCCESS,
                            'has-warning': $root.passwordStatus() === $root.STATUS.WARNING,
                            'has-error': $root.passwordStatus() === $root.STATUS.ERROR,
                        }
                    ''' if not has_custom_clean_password() else ''
                ),
            )
        )