Пример #1
0
def new_module(request, domain, app_id):
    "Adds a module to an app"
    app = get_app(domain, app_id)
    lang = request.COOKIES.get('lang', app.langs[0])
    name = request.POST.get('name')
    module_type = request.POST.get('module_type', 'case')
    if module_type == 'case':
        module = app.add_module(Module.new_module(name, lang))
        module_id = module.id
        app.new_form(module_id, "Untitled Form", lang)
        app.save()
        response = back_to_main(request,
                                domain,
                                app_id=app_id,
                                module_id=module_id)
        response.set_cookie('suppress_build_errors', 'yes')
        return response
    elif module_type in MODULE_TYPE_MAP:
        fn = MODULE_TYPE_MAP[module_type][FN]
        validations = MODULE_TYPE_MAP[module_type][VALIDATIONS]
        error = next((v[1] for v in validations if v[0](app)), None)
        if error:
            messages.warning(request, error)
            return back_to_main(request, domain, app_id=app.id)
        else:
            return fn(request, domain, app, name, lang)
    else:
        logger.error('Unexpected module type for new module: "%s"' %
                     module_type)
        return back_to_main(request, domain, app_id=app_id)
Пример #2
0
def new_module(request, domain, app_id):
    "Adds a module to an app"
    app = get_app(domain, app_id)
    lang = request.COOKIES.get('lang', app.langs[0])
    name = request.POST.get('name')
    module_type = request.POST.get('module_type', 'case')
    if module_type == 'case':
        module = app.add_module(Module.new_module(name, lang))
        module_id = module.id
        app.new_form(module_id, "Untitled Form", lang)
        app.save()
        response = back_to_main(request, domain, app_id=app_id, module_id=module_id)
        response.set_cookie('suppress_build_errors', 'yes')
        return response
    elif module_type in MODULE_TYPE_MAP:
        fn = MODULE_TYPE_MAP[module_type][FN]
        validations = MODULE_TYPE_MAP[module_type][VALIDATIONS]
        error = next((v[1] for v in validations if v[0](app)), None)
        if error:
            messages.warning(request, error)
            return back_to_main(request, domain, app_id=app.id)
        else:
            return fn(request, domain, app, name, lang)
    else:
        logger.error('Unexpected module type for new module: "%s"' % module_type)
        return back_to_main(request, domain, app_id=app_id)
Пример #3
0
def new_module(request, domain, app_id):
    "Adds a module to an app"
    app = get_app(domain, app_id)
    from corehq.apps.app_manager.views.utils import get_default_followup_form_xml
    lang = request.COOKIES.get('lang', app.langs[0])
    name = request.POST.get('name')
    module_type = request.POST.get('module_type', 'case')

    if module_type == 'case' or module_type == 'survey':  # survey option added for V2
        if module_type == 'case':
            name = name or 'Case List'
        else:
            name = name or 'Surveys'

        module = app.add_module(Module.new_module(name, lang))
        module_id = module.id

        form_id = None
        unstructured = add_ons.show("empty_case_lists", request, app)
        if module_type == 'case':
            if not unstructured:
                form_id = 0

                # registration form
                register = app.new_form(module_id, _("Registration Form"), lang)
                register.actions.open_case = OpenCaseAction(condition=FormActionCondition(type='always'))
                register.actions.update_case = UpdateCaseAction(
                    condition=FormActionCondition(type='always'))

                # one followup form
                msg = _("This is your follow up form. "
                        "Delete this label and add questions for any follow up visits.")
                attachment = get_default_followup_form_xml(context={'lang': lang, 'default_label': msg})
                followup = app.new_form(module_id, _("Followup Form"), lang, attachment=attachment)
                followup.requires = "case"
                followup.actions.update_case = UpdateCaseAction(condition=FormActionCondition(type='always'))

            _init_module_case_type(module)
        else:
            form_id = 0
            app.new_form(module_id, _("Survey"), lang)

        app.save()
        response = back_to_main(request, domain, app_id=app_id,
                                module_id=module_id, form_id=form_id)
        response.set_cookie('suppress_build_errors', 'yes')
        return response
    elif module_type in MODULE_TYPE_MAP:
        fn = MODULE_TYPE_MAP[module_type][FN]
        validations = MODULE_TYPE_MAP[module_type][VALIDATIONS]
        error = next((v[1] for v in validations if v[0](app)), None)
        if error:
            messages.warning(request, error)
            return back_to_main(request, domain, app_id=app.id)
        else:
            return fn(request, domain, app, name, lang)
    else:
        logger.error('Unexpected module type for new module: "%s"' % module_type)
        return back_to_main(request, domain, app_id=app_id)
Пример #4
0
def new_module(request, domain, app_id):
    "Adds a module to an app"
    app = get_app(domain, app_id)
    from corehq.apps.app_manager.views.utils import get_default_followup_form_xml
    lang = request.COOKIES.get('lang', app.langs[0])
    name = request.POST.get('name')
    module_type = request.POST.get('module_type', 'case')

    if module_type == 'case' or module_type == 'survey':  # survey option added for V2
        if module_type == 'case':
            name = name or 'Case List'
        else:
            name = name or 'Surveys'

        module = app.add_module(Module.new_module(name, lang))
        module_id = module.id

        form_id = None
        unstructured = add_ons.show("empty_case_lists", request, app)
        if module_type == 'case':
            if not unstructured:
                form_id = 0

                # registration form
                register = app.new_form(module_id, _("Registration Form"), lang)
                register.actions.open_case = OpenCaseAction(condition=FormActionCondition(type='always'))
                register.actions.update_case = UpdateCaseAction(
                    condition=FormActionCondition(type='always'))

                # one followup form
                msg = _("This is your follow up form. "
                        "Delete this label and add questions for any follow up visits.")
                attachment = get_default_followup_form_xml(context={'lang': lang, 'default_label': msg})
                followup = app.new_form(module_id, _("Followup Form"), lang, attachment=attachment)
                followup.requires = "case"
                followup.actions.update_case = UpdateCaseAction(condition=FormActionCondition(type='always'))

            _init_module_case_type(module)
        else:
            form_id = 0
            app.new_form(module_id, _("Survey"), lang)

        app.save()
        response = back_to_main(request, domain, app_id=app_id,
                                module_id=module_id, form_id=form_id)
        response.set_cookie('suppress_build_errors', 'yes')
        return response
    elif module_type in MODULE_TYPE_MAP:
        fn = MODULE_TYPE_MAP[module_type][FN]
        validations = MODULE_TYPE_MAP[module_type][VALIDATIONS]
        error = next((v[1] for v in validations if v[0](app)), None)
        if error:
            messages.warning(request, error)
            return back_to_main(request, domain, app_id=app.id)
        else:
            return fn(request, domain, app, name, lang)
    else:
        logger.error('Unexpected module type for new module: "%s"' % module_type)
        return back_to_main(request, domain, app_id=app_id)
Пример #5
0
def _get_form_designer_view(request, domain, app, module, form):
    if app and app.copy_of:
        messages.warning(request, _(
            "You tried to edit a form that was from a previous release, so "
            "we have directed you to the latest version of your application."
        ))
        return back_to_main(request, domain, app_id=app.id)

    if form.no_vellum:
        messages.warning(request, _(
            "You tried to edit this form in the Form Builder. "
            "However, your administrator has locked this form against editing "
            "in the form builder, so we have redirected you to "
            "the form's front page instead."
        ))
        return back_to_main(request, domain, app_id=app.id,
                            form_unique_id=form.unique_id)

    send_hubspot_form(HUBSPOT_FORM_BUILDER_FORM_ID, request)

    def _form_too_large(_app, _form):
        # form less than 0.1MB, anything larger starts to have
        # performance issues with fullstory
        return _app.blobs['{}.xml'.format(_form.unique_id)]['content_length'] > 102400

    context = get_apps_base_context(request, domain, app)
    context.update(locals())

    vellum_options = _get_base_vellum_options(request, domain, app, context['lang'])
    vellum_options['core'] = _get_vellum_core_context(request, domain, app, module, form, context['lang'])
    vellum_options['plugins'] = _get_vellum_plugins(domain, form, module)
    vellum_options['features'] = _get_vellum_features(request, domain, app)
    context['vellum_options'] = vellum_options

    context.update({
        'vellum_debug': settings.VELLUM_DEBUG,
        'nav_form': form,
        'formdesigner': True,

        'include_fullstory': not _form_too_large(app, form),
        'CKEDITOR_BASEPATH': "app_manager/js/vellum/lib/ckeditor/",
        'show_live_preview': should_show_preview_app(
            request,
            app,
            request.couch_user.username,
        ),
        'show_ui_notification_to_hide_translations': (len(app.langs) > 2),
    })
    context.update(_get_requirejs_context())

    if request.user.is_superuser:
        context.update({'notification_options': _get_notification_options(request, domain, app, form)})

    notify_form_opened(domain, request.couch_user, app.id, form.unique_id)

    return render(request, "app_manager/form_designer.html", context)
Пример #6
0
def rearrange(request, domain, app_id, key):
    """
    This function handles any request to switch two items in a list.
    Key tells us the list in question and must be one of
    'forms', 'modules', 'detail', or 'langs'. The two POST params
    'to' and 'from' give us the indicies of the items to be rearranged.

    """
    app = get_app(domain, app_id)
    ajax = json.loads(request.POST.get('ajax', 'false'))
    i, j = (int(x) for x in (request.POST['to'], request.POST['from']))
    resp = {}
    module_id = None

    try:
        if "forms" == key:
            to_module_id = int(request.POST['to_module_id'])
            from_module_id = int(request.POST['from_module_id'])
            try:
                app.rearrange_forms(to_module_id, from_module_id, i, j)
            except ConflictingCaseTypeError:
                messages.warning(request,
                                 CASE_TYPE_CONFLICT_MSG,
                                 extra_tags="html")
        elif "modules" == key:
            app.rearrange_modules(i, j)
    except IncompatibleFormTypeException:
        if toggles.APP_MANAGER_V2.enabled(domain):
            messages.error(
                request, _('The form cannot be moved into the desired menu.'))
        else:
            messages.error(
                request,
                _('The form can not be moved into the desired module.'))
        return back_to_main(request,
                            domain,
                            app_id=app_id,
                            module_id=module_id)
    except (RearrangeError, ModuleNotFoundException):
        messages.error(
            request,
            _('Oops. '
              'Looks like you got out of sync with us. '
              'The sidebar has been updated, so please try again.'))
        return back_to_main(request,
                            domain,
                            app_id=app_id,
                            module_id=module_id)
    app.save(resp)
    if ajax:
        return HttpResponse(json.dumps(resp))
    else:
        return back_to_main(request,
                            domain,
                            app_id=app_id,
                            module_id=module_id)
Пример #7
0
def rearrange(request, domain, app_id, key):
    """
    This function handles any request to switch two items in a list.
    Key tells us the list in question and must be one of
    'forms', 'modules', 'detail', or 'langs'. The two POST params
    'to' and 'from' give us the indicies of the items to be rearranged.

    """
    app = get_app(domain, app_id)
    ajax = json.loads(request.POST.get('ajax', 'false'))
    from_index, to_index = (int(x) for x in (request.POST['from'],
                                             request.POST['to']))
    resp = {}
    module_id = None

    try:
        if "forms" == key:
            from_module_uid = request.POST['from_module_uid']
            to_module_uid = request.POST['to_module_uid']
            app.rearrange_forms(from_module_uid, to_module_uid, from_index,
                                to_index)
        elif "modules" == key:
            app.rearrange_modules(from_index, to_index)
    except IncompatibleFormTypeException as e:
        error = "{} {}".format(
            _('The form is incompatible with the destination menu and was not moved.'
              ), str(e))
        if ajax:
            return json_response({'error': error}, status_code=400)
        messages.error(request, error)
        return back_to_main(request,
                            domain,
                            app_id=app_id,
                            module_id=module_id)
    except (RearrangeError, ModuleNotFoundException):
        error = _('Oops. '
                  'Looks like you got out of sync with us. '
                  'The sidebar has been updated, so please try again.')
        if ajax:
            return json_response(error, status_code=400)
        messages.error(request, error)
        return back_to_main(request,
                            domain,
                            app_id=app_id,
                            module_id=module_id)
    app.save(resp)
    if ajax:
        return HttpResponse(json.dumps(resp))
    else:
        return back_to_main(request,
                            domain,
                            app_id=app_id,
                            module_id=module_id)
Пример #8
0
def _new_careplan_module(request, domain, app, name, lang):
    from corehq.apps.app_manager.util import new_careplan_module
    target_module_index = request.POST.get('target_module_id')
    target_module = app.get_module(target_module_index)
    if not target_module.case_type:
        name = target_module.name[lang]
        messages.error(request, _("Please set the case type for the target module '{name}'.".format(name=name)))
        return back_to_main(request, domain, app_id=app.id)
    module = new_careplan_module(app, name, lang, target_module)
    app.save()
    response = back_to_main(request, domain, app_id=app.id, module_id=module.id)
    response.set_cookie('suppress_build_errors', 'yes')
    messages.info(request, _('Caution: Care Plan modules are a labs feature'))
    return response
Пример #9
0
def _new_careplan_module(request, domain, app, name, lang):
    from corehq.apps.app_manager.util import new_careplan_module
    target_module_index = request.POST.get('target_module_id')
    target_module = app.get_module(target_module_index)
    if not target_module.case_type:
        name = target_module.name[lang]
        messages.error(request, _("Please set the case type for the target module '{name}'.".format(name=name)))
        return back_to_main(request, domain, app_id=app.id)
    module = new_careplan_module(app, name, lang, target_module)
    app.save()
    response = back_to_main(request, domain, app_id=app.id, module_id=module.id)
    response.set_cookie('suppress_build_errors', 'yes')
    messages.info(request, _('Caution: Care Plan modules are a labs feature'))
    return response
Пример #10
0
def new_form(request, domain, app_id, module_id):
    "Adds a form to an app (under a module)"
    app = get_app(domain, app_id)
    lang = request.COOKIES.get('lang', app.langs[0])
    name = request.POST.get('name')
    form_type = request.POST.get('form_type', 'form')
    if form_type == "shadow":
        app = get_app(domain, app_id)
        module = app.get_module(module_id)
        if module.module_type == "advanced":
            form = module.new_shadow_form(name, lang)
        else:
            raise Exception(
                "Shadow forms may only be created under shadow modules")
    else:
        form = app.new_form(module_id, name, lang)

    if toggles.APP_MANAGER_V2.enabled(
            request.user.username) and form_type != "shadow":
        case_action = request.POST.get('case_action', 'none')
        if case_action == 'update':
            form.requires = 'case'
            form.actions.update_case = UpdateCaseAction(
                condition=FormActionCondition(type='always'))

    app.save()
    # add form_id to locals()
    form_id = form.id
    response = back_to_main(request,
                            domain,
                            app_id=app_id,
                            module_id=module_id,
                            form_id=form_id)
    return response
Пример #11
0
def copy_form(request, domain, app_id, module_id, form_id):
    app = get_app(domain, app_id)
    to_module_id = int(request.POST['to_module_id'])
    try:
        app.copy_form(int(module_id), int(form_id), to_module_id)
    except ConflictingCaseTypeError:
        messages.warning(request, CASE_TYPE_CONFLICT_MSG, extra_tags="html")
        app.save()
    except BlankXFormError:
        # don't save!
        messages.error(
            request,
            _('We could not copy this form, because it is blank.'
              'In order to copy this form, please add some questions first.'))
    except IncompatibleFormTypeException:
        # don't save!
        messages.error(
            request,
            _('This form could not be copied because it '
              'is not compatible with the selected module.'))
    else:
        app.save()

    return back_to_main(request,
                        domain,
                        app_id=app_id,
                        module_id=module_id,
                        form_id=form_id)
Пример #12
0
        def _inner(request, link_domain, data, master_domain=domain):
            clear_app_cache(request, link_domain)
            if data['toggles']:
                for slug in data['toggles'].split(","):
                    set_toggle(slug, link_domain, True, namespace=toggles.NAMESPACE_DOMAIN)
            linked = data.get('linked')
            if linked:
                master_version = get_latest_released_app_version(app.domain, app_id)
                if not master_version:
                    messages.error(request, _("Creating linked app failed."
                                              " Unable to get latest released version of your app."
                                              " Make sure you have at least one released build."))
                    return HttpResponseRedirect(reverse_util('app_settings', params={}, args=[domain, app_id]))

                linked_app = create_linked_app(master_domain, app_id, link_domain, data['name'])
                try:
                    update_linked_app(linked_app, request.couch_user.get_id)
                except AppLinkError as e:
                    linked_app.delete()
                    messages.error(request, str(e))
                    return HttpResponseRedirect(reverse_util('app_settings', params={}, args=[domain, app_id]))

                messages.success(request, _('Application successfully copied and linked.'))
                return HttpResponseRedirect(reverse_util('app_settings', params={}, args=[link_domain, linked_app.get_id]))
            else:
                extra_properties = {'name': data['name']}
                try:
                    app_copy = import_app_util(app_id_or_source, link_domain, extra_properties)
                except ReportConfigurationNotFoundError:
                    messages.error(request, _("Copying the application failed because "
                                              "your application contains a Report Module "
                                              "that references a static UCR configuration."))
                    return HttpResponseRedirect(reverse_util('app_settings', params={}, args=[domain, app_id]))
                return back_to_main(request, app_copy.domain, app_id=app_copy._id)
Пример #13
0
def new_app(request, domain):
    "Adds an app to the database"
    lang = 'en'
    type = request.POST["type"]
    application_version = request.POST.get('application_version', APP_V1)
    cls = str_to_cls[type]
    form_args = []
    if cls == Application:
        app = cls.new_app(domain,
                          "Untitled Application",
                          lang=lang,
                          application_version=application_version)
        module = Module.new_module("Untitled Module", lang)
        app.add_module(module)
        form = app.new_form(0, "Untitled Form", lang)
        form_args = [module.id, form.id]
    else:
        app = cls.new_app(domain, "Untitled Application", lang=lang)
    if request.project.secure_submissions:
        app.secure_submissions = True
    app.save()
    clear_app_cache(request, domain)
    main_args = [request, domain, app.id]
    main_args.extend(form_args)

    return back_to_main(*main_args)
Пример #14
0
def new_form(request, domain, app_id, module_id):
    "Adds a form to an app (under a module)"
    app = get_app(domain, app_id)
    lang = request.COOKIES.get('lang', app.langs[0])
    name = request.POST.get('name')
    form = app.new_form(module_id, name, lang)

    blank_form = render_to_string("app_manager/blank_form.xml", context={
        'xmlns': str(uuid.uuid4()).upper(),
        'name': form.name[lang],
        'lang': lang,
    })
    form.source = blank_form

    if toggles.APP_MANAGER_V2.enabled(domain):
        case_action = request.POST.get('case_action', 'none')
        if case_action == 'update':
            form.requires = 'case'
            form.actions.update_case = UpdateCaseAction(
                condition=FormActionCondition(type='always'))

    app.save()
    # add form_id to locals()
    form_id = form.id
    response = back_to_main(request, domain, app_id=app_id, module_id=module_id,
                            form_id=form_id)
    return response
Пример #15
0
def new_form(request, domain, app_id, module_id):
    "Adds a form to an app (under a module)"
    app = get_app(domain, app_id)
    lang = request.COOKIES.get('lang', app.langs[0])
    name = request.POST.get('name')
    form = app.new_form(module_id, name, lang)

    blank_form = render_to_string("app_manager/blank_form.xml", context={
        'xmlns': str(uuid.uuid4()).upper(),
        'name': form.name[lang],
        'lang': lang,
    })
    form.source = blank_form

    if toggles.APP_MANAGER_V2.enabled(domain):
        case_action = request.POST.get('case_action', 'none')
        if case_action == 'update':
            form.requires = 'case'
            form.actions.update_case = UpdateCaseAction(
                condition=FormActionCondition(type='always'))

    app.save()
    # add form_id to locals()
    form_id = form.id
    response = back_to_main(request, domain, app_id=app_id, module_id=module_id,
                            form_id=form_id)
    return response
Пример #16
0
def revert_to_copy(request, domain, app_id):
    """
    Copies a saved doc back to the original.
    See VersionedDoc.revert_to_copy

    """
    app = get_app(domain, app_id)
    copy = get_app(domain, request.POST['saved_app'])
    app = app.make_reversion_to_copy(copy)
    app.save()
    messages.success(
        request,
        "Successfully reverted to version %s, now at version %s" % (copy.version, app.version)
    )
    if copy.build_comment:
        new_build_comment = "Reverted to version {old_version}\n\n{original_comment}".format(
            old_version=copy.version, original_comment=copy.build_comment)
    else:
        new_build_comment = "Reverted to version {old_version}".format(old_version=copy.version)
    copy = app.make_build(
        comment=new_build_comment,
        user_id=request.couch_user.get_id,
    )
    copy.save(increment_version=False)
    return back_to_main(request, domain, app_id=app_id)
Пример #17
0
 def _inner(request, domain, data):
     clear_app_cache(request, domain)
     if data["toggles"]:
         for slug in data["toggles"].split(","):
             set_toggle(slug, domain, True, namespace=toggles.NAMESPACE_DOMAIN)
     app_copy = import_app_util(app_id_or_source, domain, {"name": data["name"]})
     return back_to_main(request, app_copy.domain, app_id=app_copy._id)
Пример #18
0
def revert_to_copy(request, domain, app_id):
    """
    Copies a saved doc back to the original.
    See VersionedDoc.revert_to_copy

    """
    app = get_app(domain, app_id)
    copy = get_app(domain, request.POST['saved_app'])
    app = app.make_reversion_to_copy(copy)
    app.save()
    messages.success(
        request,
        "Successfully reverted to version %s, now at version %s" % (copy.version, app.version)
    )
    if copy.build_comment:
        new_build_comment = "Reverted to version {old_version}\n\n{original_comment}".format(
            old_version=copy.version, original_comment=copy.build_comment)
    else:
        new_build_comment = "Reverted to version {old_version}".format(old_version=copy.version)
    copy = app.make_build(
        comment=new_build_comment,
        user_id=request.couch_user.get_id,
    )
    copy.save(increment_version=False)
    return back_to_main(request, domain, app_id=app_id)
Пример #19
0
def copy_form(request, domain, app_id, form_unique_id):
    app = get_app(domain, app_id)
    form = app.get_form(form_unique_id)
    module = form.get_module()
    to_app = get_app(
        domain,
        request.POST['to_app_id']) if request.POST.get('to_app_id') else app
    to_module_id = int(request.POST['to_module_id'])
    to_module = to_app.get_module(to_module_id)
    new_form = None
    try:
        new_form = app.copy_form(module, form, to_module, rename=True)
        if module['case_type'] != to_module['case_type']:
            messages.warning(request,
                             CASE_TYPE_CONFLICT_MSG,
                             extra_tags="html")
        to_app.save()
    except IncompatibleFormTypeException:
        # don't save!
        messages.error(
            request,
            _('This form could not be copied because it '
              'is not compatible with the selected module.'))
    else:
        to_app.save()

    if new_form:
        return back_to_main(request,
                            domain,
                            app_id=to_app._id,
                            form_unique_id=new_form.unique_id)
    return HttpResponseRedirect(
        reverse('view_form', args=(domain, app._id, form.unique_id)))
Пример #20
0
def revert_to_copy(request, domain, app_id):
    """
    Copies a saved doc back to the original.
    See VersionedDoc.revert_to_copy

    """
    app = get_app(domain, app_id)
    copy = get_app(domain, request.POST['build_id'])
    if copy.get_doc_type() == 'LinkedApplication' and app.get_doc_type() == 'Application':
        copy.convert_to_application()
    app = app.make_reversion_to_copy(copy)
    app.save()
    messages.success(
        request,
        _("Successfully reverted to version %(old_version)s, now at version %(new_version)s") % {
            'old_version': copy.version,
            'new_version': app.version,
        }
    )
    copy_build_comment_params = {
        "old_version": copy.version,
        "original_comment": copy.build_comment,
    }
    if copy.build_comment:
        copy_build_comment_template = _(
            "Reverted to version {old_version}\n\nPrevious build comments:\n{original_comment}")
    else:
        copy_build_comment_template = _("Reverted to version {old_version}")

    copy = app.make_build(
        comment=copy_build_comment_template.format(**copy_build_comment_params),
        user_id=request.couch_user.get_id,
    )
    copy.save(increment_version=False)
    return back_to_main(request, domain, app_id=app_id)
Пример #21
0
 def _inner(request, domain, data):
     clear_app_cache(request, domain)
     if data['toggles']:
         for slug in data['toggles'].split(","):
             set_toggle(slug,
                        domain,
                        True,
                        namespace=toggles.NAMESPACE_DOMAIN)
     extra_properties = {'name': data['name']}
     if data.get('linked'):
         extra_properties['master'] = app_id
         extra_properties['doc_type'] = 'LinkedApplication'
         app = get_app(None, app_id)
         if domain not in app.linked_whitelist:
             app.linked_whitelist.append(domain)
             app.save()
     app_copy = import_app_util(app_id_or_source, domain,
                                extra_properties)
     mobile_ucrs = False
     for module in app_copy.modules:
         if isinstance(module, ReportModule):
             mobile_ucrs = True
             break
     if mobile_ucrs:
         messages.error(
             request,
             _('This linked application uses mobile UCRs '
               'which are currently not supported. For this application '
               'to function correctly, you will need to remove those modules.'
               ))
     return back_to_main(request, app_copy.domain, app_id=app_copy._id)
Пример #22
0
def revert_to_copy(request, domain, app_id):
    """
    Copies a saved doc back to the original.
    See VersionedDoc.revert_to_copy

    """
    app = get_app(domain, app_id)
    copy = get_app(domain, request.POST['saved_app'])
    if copy.get_doc_type() == 'LinkedApplication' and app.get_doc_type() == 'Application':
        copy.convert_to_application()
    app = app.make_reversion_to_copy(copy)
    app.save()
    messages.success(
        request,
        _("Successfully reverted to version %(old_version)s, now at version %(new_version)s") % {
            'old_version': copy.version,
            'new_version': app.version,
        }
    )
    copy_build_comment_params = {
        "old_version": copy.version,
        "original_comment": copy.build_comment,
    }
    if copy.build_comment:
        copy_build_comment_template = _(
            "Reverted to version {old_version}\n\nPrevious build comments:\n{original_comment}")
    else:
        copy_build_comment_template = _("Reverted to version {old_version}")

    copy = app.make_build(
        comment=copy_build_comment_template.format(**copy_build_comment_params),
        user_id=request.couch_user.get_id,
    )
    copy.save(increment_version=False)
    return back_to_main(request, domain, app_id=app_id)
Пример #23
0
def overwrite_module_case_list(request, domain, app_id, module_id):
    app = get_app(domain, app_id)
    source_module_id = int(request.POST['source_module_id'])
    detail_type = request.POST['detail_type']
    assert detail_type in ['short', 'long']
    source_module = app.get_module(source_module_id)
    dest_module = app.get_module(module_id)
    if not hasattr(source_module, 'case_details'):
        messages.error(
            request,
            _("Sorry, couldn't find case list configuration for module {}. "
              "Please report an issue if you believe this is a mistake.").
            format(source_module.default_name()))
    elif source_module.case_type != dest_module.case_type:
        messages.error(
            request,
            _("Please choose a module with the same case type as the current one ({})."
              ).format(dest_module.case_type))
    else:
        setattr(dest_module.case_details, detail_type,
                getattr(source_module.case_details, detail_type))
        app.save()
        messages.success(
            request,
            _('Case list updated form module {}.').format(
                source_module.default_name()))
    return back_to_main(request, domain, app_id=app_id, module_id=module_id)
Пример #24
0
def app_exchange(request, domain):
    template = "app_manager/app_exchange.html"
    records = []
    for obj in ExchangeApplication.objects.all():
        app = get_app(obj.domain, obj.app_id)
        records.append({
            "id": app.get_id,
            "domain": app.domain,
            "name": app.name,
            "comment": app.comment,
            "last_released": obj.last_released.date() if obj.last_released else None,
            "help_link": obj.help_link,
        })

    context = {
        "domain": domain,
        "records": records,
    }

    if request.method == "POST":
        clear_app_cache(request, domain)
        from_domain = request.POST.get('from_domain')
        from_app_id = request.POST.get('from_app_id')
        doc = get_latest_released_app_doc(from_domain, from_app_id)

        if not doc:
            messages.error(request, _("Could not find latest released version of app."))
            return render(request, template, context)

        app_copy = import_app_util(doc, domain)
        return back_to_main(request, domain, app_id=app_copy._id)

    return render(request, template, context)
Пример #25
0
        def _inner(request, link_domain, data, master_domain=domain):
            clear_app_cache(request, link_domain)
            if data['toggles']:
                for slug in data['toggles'].split(","):
                    set_toggle(slug, link_domain, True, namespace=toggles.NAMESPACE_DOMAIN)
            linked = data.get('linked')
            if linked:
                for module in app.modules:
                    if isinstance(module, ReportModule):
                        messages.error(request, _('This linked application uses mobile UCRs which '
                                                  'are currently not supported. For this application to '
                                                  'function correctly, you will need to remove those modules.'))
                        return HttpResponseRedirect(reverse_util('app_settings', params={}, args=[domain, app_id]))

                master_version = get_latest_released_app_version(app.domain, app_id)
                if not master_version:
                    messages.error(request, _("Creating linked app failed."
                                              " Unable to get latest released version of your app."
                                              " Make sure you have at least one released build."))
                    return HttpResponseRedirect(reverse_util('app_settings', params={}, args=[domain, app_id]))

                linked_app = create_linked_app(master_domain, app_id, link_domain, data['name'])
                try:
                    update_linked_app(linked_app, request.couch_user.get_id)
                except AppLinkError as e:
                    messages.error(request, str(e))
                    return HttpResponseRedirect(reverse_util('app_settings', params={}, args=[domain, app_id]))

                messages.success(request, _('Application successfully copied and linked.'))
                return HttpResponseRedirect(reverse_util('app_settings', params={}, args=[link_domain, linked_app.get_id]))
            else:
                extra_properties = {'name': data['name']}
                app_copy = import_app_util(app_id_or_source, link_domain, extra_properties)
                return back_to_main(request, app_copy.domain, app_id=app_copy._id)
Пример #26
0
def import_app(request, domain):
    template = "app_manager/import_app.html"
    if request.method == "POST":
        clear_app_cache(request, domain)
        name = request.POST.get('name')
        compressed = request.POST.get('compressed')

        valid_request = True
        if not name:
            messages.error(
                request,
                _("You must submit a name for the application you are importing."
                  ))
            valid_request = False
        if not compressed:
            messages.error(request, _("You must submit the source data."))
            valid_request = False

        if not valid_request:
            return render(request, template, {'domain': domain})

        source = decompress([
            six.unichr(int(x)) if int(x) < 256 else int(x)
            for x in compressed.split(',')
        ])
        source = json.loads(source)
        assert (source is not None)
        app = import_app_util(source, domain, {'name': name})

        return back_to_main(request, domain, app_id=app._id)
    else:
        app_id = request.GET.get('app')
        redirect_domain = request.GET.get('domain') or None
        if redirect_domain is not None:
            redirect_domain = redirect_domain.lower()
            if Domain.get_by_name(redirect_domain):
                return HttpResponseRedirect(
                    reverse('import_app', args=[redirect_domain]) +
                    "?app={app_id}".format(app_id=app_id))
            else:
                if redirect_domain:
                    messages.error(
                        request, "We can't find a project called \"%s\"." %
                        redirect_domain)
                else:
                    messages.error(request, "You left the project name blank.")
                return HttpResponseRedirect(
                    request.META.get('HTTP_REFERER', request.path))

        if app_id:
            app = get_app(None, app_id)
            assert (app.get_doc_type() in ('Application', 'RemoteApp'))
            assert (request.couch_user.is_member_of(app.domain))
        else:
            app = None

        return render(request, template, {
            'domain': domain,
            'app': app,
        })
Пример #27
0
        def _inner(request, link_domain, data, master_domain=domain):
            clear_app_cache(request, link_domain)
            if data['toggles']:
                for slug in data['toggles'].split(","):
                    set_toggle(slug,
                               link_domain,
                               True,
                               namespace=toggles.NAMESPACE_DOMAIN)
            linked = data.get('linked')
            if linked:
                master_version = get_latest_released_app_version(
                    app.domain, app_id)
                if not master_version:
                    messages.error(
                        request,
                        _("Creating linked app failed."
                          " Unable to get latest released version of your app."
                          " Make sure you have at least one released build."))
                    return HttpResponseRedirect(
                        reverse_util('app_settings',
                                     params={},
                                     args=[domain, app_id]))

                linked_app = create_linked_app(master_domain, app_id,
                                               link_domain, data['name'])
                try:
                    update_linked_app(linked_app, request.couch_user.get_id)
                except AppLinkError as e:
                    linked_app.delete()
                    messages.error(request, str(e))
                    return HttpResponseRedirect(
                        reverse_util('app_settings',
                                     params={},
                                     args=[domain, app_id]))

                messages.success(
                    request, _('Application successfully copied and linked.'))
                return HttpResponseRedirect(
                    reverse_util('app_settings',
                                 params={},
                                 args=[link_domain, linked_app.get_id]))
            else:
                extra_properties = {'name': data['name']}
                try:
                    app_copy = import_app_util(app_id_or_source, link_domain,
                                               extra_properties)
                except ReportConfigurationNotFoundError:
                    messages.error(
                        request,
                        _("Copying the application failed because "
                          "your application contains a Report Module "
                          "that references a static UCR configuration."))
                    return HttpResponseRedirect(
                        reverse_util('app_settings',
                                     params={},
                                     args=[domain, app_id]))
                return back_to_main(request,
                                    app_copy.domain,
                                    app_id=app_copy._id)
Пример #28
0
def new_module(request, domain, app_id):
    "Adds a module to an app"
    app = get_app(domain, app_id)
    lang = request.COOKIES.get('lang', app.langs[0])
    name = request.POST.get('name')
    module_type = request.POST.get('module_type', 'case')

    if module_type == 'case' or module_type == 'survey':  # survey option added for V2

        if toggles.APP_MANAGER_V2.enabled(domain):
            if module_type == 'case':
                name = name or 'Record List'
            else:
                name = name or 'Surveys'

        module = app.add_module(Module.new_module(name, lang))
        module_id = module.id

        if not toggles.APP_MANAGER_V2.enabled(domain):
            app.new_form(module_id, "Untitled Form", lang)
        elif module_type == 'case':
            register = app.new_form(module_id, "Register", lang)
            register.case_action = 'open'  # TODO: this doesn't work
            followup = app.new_form(module_id, "Followup", lang)
            followup.case_action = 'update'  # TODO: this doesn't work
            module.case_type = 'case'  # TODO: make unique across domain
        else:
            form = app.new_form(module_id, "Survey", lang)
            form.case_action = 'none'

        app.save()
        response = back_to_main(request, domain, app_id=app_id, module_id=module_id)
        response.set_cookie('suppress_build_errors', 'yes')
        return response
    elif module_type in MODULE_TYPE_MAP:
        fn = MODULE_TYPE_MAP[module_type][FN]
        validations = MODULE_TYPE_MAP[module_type][VALIDATIONS]
        error = next((v[1] for v in validations if v[0](app)), None)
        if error:
            messages.warning(request, error)
            return back_to_main(request, domain, app_id=app.id)
        else:
            return fn(request, domain, app, name, lang)
    else:
        logger.error('Unexpected module type for new module: "%s"' % module_type)
        return back_to_main(request, domain, app_id=app_id)
Пример #29
0
def _copy_app_helper(request, from_app_id, to_domain, to_app_name):
    extra_properties = {'name': to_app_name}
    app_copy = import_app_util(from_app_id, to_domain, extra_properties,
                               request)
    if is_linked_app(app_copy):
        app_copy = app_copy.convert_to_application()
        app_copy.save()
    return back_to_main(request, app_copy.domain, app_id=app_copy._id)
Пример #30
0
def undo_delete_module(request, domain, record_id):
    record = DeleteModuleRecord.get(record_id)
    record.undo()
    messages.success(request, 'Module successfully restored.')
    return back_to_main(request,
                        domain,
                        app_id=record.app_id,
                        module_id=record.module_id)
Пример #31
0
def _new_advanced_module(request, domain, app, name, lang):
    module = app.add_module(AdvancedModule.new_module(name, lang))
    module_id = module.id
    app.new_form(module_id, _("Untitled Form"), lang)

    app.save()
    response = back_to_main(request, domain, app_id=app.id, module_id=module_id)
    response.set_cookie('suppress_build_errors', 'yes')
    messages.info(request, _('Caution: Advanced modules are a labs feature'))
    return response
Пример #32
0
def _new_advanced_module(request, domain, app, name, lang):
    module = app.add_module(AdvancedModule.new_module(name, lang))
    module_id = module.id
    app.new_form(module_id, _("Untitled Form"), lang)

    app.save()
    response = back_to_main(request, domain, app_id=app.id, module_id=module_id)
    response.set_cookie('suppress_build_errors', 'yes')
    messages.info(request, _('Caution: Advanced modules are a labs feature'))
    return response
Пример #33
0
def rearrange(request, domain, app_id, key):
    """
    This function handles any request to switch two items in a list.
    Key tells us the list in question and must be one of
    'forms', 'modules', 'detail', or 'langs'. The two POST params
    'to' and 'from' give us the indicies of the items to be rearranged.

    """
    app = get_app(domain, app_id)
    ajax = json.loads(request.POST.get('ajax', 'false'))
    i, j = (int(x) for x in (request.POST['to'], request.POST['from']))
    resp = {}
    module_id = None

    try:
        if "forms" == key:
            to_module_id = int(request.POST['to_module_id'])
            from_module_id = int(request.POST['from_module_id'])
            app.rearrange_forms(to_module_id, from_module_id, i, j)
        elif "modules" == key:
            app.rearrange_modules(i, j)
    except IncompatibleFormTypeException as e:
        error = "{} {}".format(_('The form is incompatible with the destination menu and was not moved.'), str(e))
        if ajax:
            return json_response({'error': error}, status_code=400)
        messages.error(request, error)
        return back_to_main(request, domain, app_id=app_id, module_id=module_id)
    except (RearrangeError, ModuleNotFoundException):
        error = _(
            'Oops. '
            'Looks like you got out of sync with us. '
            'The sidebar has been updated, so please try again.'
        )
        if ajax:
            return json_response(error, status_code=400)
        messages.error(request, error)
        return back_to_main(request, domain, app_id=app_id, module_id=module_id)
    app.save(resp)
    if ajax:
        return HttpResponse(json.dumps(resp))
    else:
        return back_to_main(request, domain, app_id=app_id, module_id=module_id)
Пример #34
0
def delete_app_lang(request, domain, app_id):
    """
    DEPRECATED
    Called when a language (such as 'zh') is to be deleted from app.langs

    """
    lang_id = int(request.POST['index'])
    app = get_app(domain, app_id)
    del app.langs[lang_id]
    app.save()
    return back_to_main(request, domain, app_id=app_id)
Пример #35
0
def delete_app_lang(request, domain, app_id):
    """
    DEPRECATED
    Called when a language (such as 'zh') is to be deleted from app.langs

    """
    lang_id = int(request.POST["index"])
    app = get_app(domain, app_id)
    del app.langs[lang_id]
    app.save()
    return back_to_main(request, domain, app_id=app_id)
Пример #36
0
 def _inner(request, domain, data):
     clear_app_cache(request, domain)
     if data['toggles']:
         for slug in data['toggles'].split(","):
             set_toggle(slug,
                        domain,
                        True,
                        namespace=toggles.NAMESPACE_DOMAIN)
     app_copy = import_app_util(app_id_or_source, domain,
                                {'name': data['name']})
     return back_to_main(request, app_copy.domain, app_id=app_copy._id)
Пример #37
0
def rearrange(request, domain, app_id, key):
    """
    This function handles any request to switch two items in a list.
    Key tells us the list in question and must be one of
    'forms', 'modules', 'detail', or 'langs'. The two POST params
    'to' and 'from' give us the indicies of the items to be rearranged.

    """
    app = get_app(domain, app_id)
    ajax = json.loads(request.POST.get('ajax', 'false'))
    i, j = (int(x) for x in (request.POST['to'], request.POST['from']))
    resp = {}
    module_id = None

    try:
        if "forms" == key:
            to_module_id = int(request.POST['to_module_id'])
            from_module_id = int(request.POST['from_module_id'])
            try:
                app.rearrange_forms(to_module_id, from_module_id, i, j)
            except ConflictingCaseTypeError:
                messages.warning(request, CASE_TYPE_CONFLICT_MSG, extra_tags="html")
        elif "modules" == key:
            app.rearrange_modules(i, j)
    except IncompatibleFormTypeException:
        messages.error(request, _(
            'The form can not be moved into the desired module.'
        ))
        return back_to_main(request, domain, app_id=app_id, module_id=module_id)
    except (RearrangeError, ModuleNotFoundException):
        messages.error(request, _(
            'Oops. '
            'Looks like you got out of sync with us. '
            'The sidebar has been updated, so please try again.'
        ))
        return back_to_main(request, domain, app_id=app_id, module_id=module_id)
    app.save(resp)
    if ajax:
        return HttpResponse(json.dumps(resp))
    else:
        return back_to_main(request, domain, app_id=app_id, module_id=module_id)
Пример #38
0
def new_form(request, domain, app_id, module_id):
    "Adds a form to an app (under a module)"
    app = get_app(domain, app_id)
    lang = request.COOKIES.get('lang', app.langs[0])
    name = request.POST.get('name')
    form = app.new_form(module_id, name, lang)
    app.save()
    # add form_id to locals()
    form_id = form.id
    response = back_to_main(request, domain, app_id=app_id, module_id=module_id,
                            form_id=form_id)
    return response
Пример #39
0
def new_form(request, domain, app_id, module_id):
    "Adds a form to an app (under a module)"
    app = get_app(domain, app_id)
    lang = request.COOKIES.get('lang', app.langs[0])
    name = request.POST.get('name')
    form = app.new_form(module_id, name, lang)
    app.save()
    # add form_id to locals()
    form_id = form.id
    response = back_to_main(request, domain, app_id=app_id, module_id=module_id,
                            form_id=form_id)
    return response
Пример #40
0
def undo_delete_app(request, domain, record_id):
    try:
        app = get_app(domain, record_id)
        app.unretire()
        app_id = app.id
    except Exception:
        record = DeleteApplicationRecord.get(record_id)
        record.undo()
        app_id = record.app_id
    clear_app_cache(request, domain)
    messages.success(request, "Application successfully restored.")
    return back_to_main(request, domain, app_id=app_id)
Пример #41
0
def undo_delete_app(request, domain, record_id):
    try:
        app = get_app(domain, record_id)
        app.unretire()
        app_id = app.id
    except Exception:
        record = DeleteApplicationRecord.get(record_id)
        record.undo()
        app_id = record.app_id
    clear_app_cache(request, domain)
    messages.success(request, 'Application successfully restored.')
    return back_to_main(request, domain, app_id=app_id)
Пример #42
0
def revert_to_copy(request, domain, app_id):
    """
    Copies a saved doc back to the original.
    See VersionedDoc.revert_to_copy

    """
    app = get_app(domain, app_id)
    copy = get_app(domain, request.POST["saved_app"])
    app = app.make_reversion_to_copy(copy)
    app.save()
    messages.success(request, "Successfully reverted to version %s, now at version %s" % (copy.version, app.version))
    return back_to_main(request, domain, app_id=app_id)
Пример #43
0
def delete_app(request, domain, app_id):
    "Deletes an app from the database"
    app = get_app(domain, app_id)
    record = app.delete_app()
    messages.success(
        request,
        _('You have deleted an application. <a href="%s" class="post-link">Undo</a>'
          ) % reverse('undo_delete_app', args=[domain, record.get_id]),
        extra_tags='html')
    app.save()
    clear_app_cache(request, domain)
    return back_to_main(request, domain)
Пример #44
0
def _new_report_module(request, domain, app, name, lang):
    module = app.add_module(ReportModule.new_module(name, lang))
    # by default add all reports
    module.report_configs = [
        ReportAppConfig(
            report_id=report._id,
            header={lang: report.title},
            description={lang: report.description},
        ) for report in ReportConfiguration.by_domain(domain)
    ]
    app.save()
    return back_to_main(request, domain, app_id=app.id, module_id=module.id)
Пример #45
0
def import_app(request, domain, template="app_manager/import_app.html"):
    if request.method == "POST":
        clear_app_cache(request, domain)
        name = request.POST.get('name')
        compressed = request.POST.get('compressed')

        valid_request = True
        if not name:
            messages.error(request, _("You must submit a name for the application you are importing."))
            valid_request = False
        if not compressed:
            messages.error(request, _("You must submit the source data."))
            valid_request = False

        if not valid_request:
            return render(request, template, {'domain': domain})

        source = decompress([chr(int(x)) if int(x) < 256 else int(x) for x in compressed.split(',')])
        source = json.loads(source)
        assert(source is not None)
        app = import_app_util(source, domain, {'name': name})

        return back_to_main(request, domain, app_id=app._id)
    else:
        app_id = request.GET.get('app')
        redirect_domain = request.GET.get('domain') or None
        if redirect_domain is not None:
            redirect_domain = redirect_domain.lower()
            if Domain.get_by_name(redirect_domain):
                return HttpResponseRedirect(
                    reverse('import_app', args=[redirect_domain])
                    + "?app={app_id}".format(app_id=app_id)
                )
            else:
                if redirect_domain:
                    messages.error(request, "We can't find a project called %s." % redirect_domain)
                else:
                    messages.error(request, "You left the project name blank.")
                return HttpResponseRedirect(request.META.get('HTTP_REFERER', request.path))

        if app_id:
            app = get_app(None, app_id)
            assert(app.get_doc_type() in ('Application', 'RemoteApp'))
            assert(request.couch_user.is_member_of(app.domain))
        else:
            app = None

        return render(request, template, {
            'domain': domain,
            'app': app,
            'is_superuser': request.couch_user.is_superuser
        })
Пример #46
0
def view_app(request, domain, app_id=None):
    from corehq.apps.app_manager.views.view_generic import view_generic
    # redirect old m=&f= urls
    module_id = request.GET.get('m', None)
    form_id = request.GET.get('f', None)
    if module_id or form_id:
        soft_assert('{}@{}'.format('skelly', 'dimagi.com')).call(
            False, 'old m=&f= url still in use'
        )
        return back_to_main(request, domain, app_id=app_id, module_id=module_id,
                            form_id=form_id)

    return view_generic(request, domain, app_id)
Пример #47
0
def delete_app(request, domain, app_id):
    "Deletes an app from the database"
    app = get_app(domain, app_id)
    record = app.delete_app()
    messages.success(
        request,
        _('You have deleted an application. <a href="%s" class="post-link">Undo</a>')
        % reverse("undo_delete_app", args=[domain, record.get_id]),
        extra_tags="html",
    )
    app.save()
    clear_app_cache(request, domain)
    return back_to_main(request, domain)
Пример #48
0
def _new_report_module(request, domain, app, name, lang):
    module = app.add_module(ReportModule.new_module(name, lang))
    # by default add all reports
    module.report_configs = [
        ReportAppConfig(
            report_id=report._id,
            header={lang: report.title},
            description=report.description,
        )
        for report in ReportConfiguration.by_domain(domain)
    ]
    app.save()
    return back_to_main(request, domain, app_id=app.id, module_id=module.id)
Пример #49
0
def new_form(request, domain, app_id, module_unique_id):
    """
    Adds a form to an app (under a module)
    """
    app = get_app(domain, app_id)

    try:
        module = app.get_module_by_unique_id(module_unique_id)
    except ModuleNotFoundException:
        raise HttpResponseBadRequest

    lang = request.COOKIES.get('lang', app.langs[0])
    form_type = request.POST.get('form_type', 'form')
    case_action = request.POST.get('case_action', 'none')

    if case_action == 'open':
        name = _('Register')
    elif case_action == 'update':
        name = _('Followup')
    elif module.is_training_module:
        name = _('Lesson')
    else:
        name = _('Survey')

    if form_type == "shadow":
        if module.module_type == "advanced":
            form = module.new_shadow_form(name, lang)
        else:
            raise Exception("Shadow forms may only be created under shadow modules")
    else:
        form = module.new_form(name, lang)

    if form_type != "shadow":
        if case_action == 'update':
            form.requires = 'case'
            form.actions.update_case = UpdateCaseAction(
                condition=FormActionCondition(type='always'))
        elif case_action == 'open':
            form.actions.open_case = OpenCaseAction(
                condition=FormActionCondition(type='always'))
            form.actions.update_case = UpdateCaseAction(
                condition=FormActionCondition(type='always'))

    app.save()
    return back_to_main(
        request, domain,
        app_id=app.id,
        module_unique_id=module.unique_id,
        form_unique_id=form.unique_id
    )
Пример #50
0
def new_form(request, domain, app_id, module_unique_id):
    """
    Adds a form to an app (under a module)
    """
    app = get_app(domain, app_id)

    try:
        module = app.get_module_by_unique_id(module_unique_id)
    except ModuleNotFoundException:
        raise HttpResponseBadRequest

    lang = request.COOKIES.get('lang', app.langs[0])
    form_type = request.POST.get('form_type', 'form')
    case_action = request.POST.get('case_action', 'none')

    if case_action == 'open':
        name = _('Register')
    elif case_action == 'update':
        name = _('Followup')
    elif module.is_training_module:
        name = _('Lesson')
    else:
        name = _('Survey')

    if form_type == "shadow":
        if module.module_type == "advanced":
            form = module.new_shadow_form(name, lang)
        else:
            raise Exception("Shadow forms may only be created under shadow modules")
    else:
        form = module.new_form(name, lang)

    if form_type != "shadow":
        if case_action == 'update':
            form.requires = 'case'
            form.actions.update_case = UpdateCaseAction(
                condition=FormActionCondition(type='always'))
        elif case_action == 'open':
            form.actions.open_case = OpenCaseAction(
                condition=FormActionCondition(type='always'))
            form.actions.update_case = UpdateCaseAction(
                condition=FormActionCondition(type='always'))

    app.save()
    return back_to_main(
        request, domain,
        app_id=app.id,
        module_unique_id=module.unique_id,
        form_unique_id=form.unique_id
    )
Пример #51
0
def delete_form(request, domain, app_id, module_unique_id, form_unique_id):
    "Deletes a form from an app"
    app = get_app(domain, app_id)
    record = app.delete_form(module_unique_id, form_unique_id)
    if record is not None:
        messages.success(
            request,
            'You have deleted a form. <a href="%s" class="post-link">Undo</a>'
            % reverse('undo_delete_form', args=[domain, record.get_id]),
            extra_tags='html'
        )
        app.save()
    return back_to_main(
        request, domain, app_id=app_id,
        module_id=app.get_module_by_unique_id(module_unique_id).id)
Пример #52
0
def drop_user_case(request, domain, app_id):
    app = get_app(domain, app_id)
    for module in app.get_modules():
        for form in module.get_forms():
            if form.form_type == "module_form":
                if "usercase_update" in form.actions and form.actions["usercase_update"].update:
                    form.actions["usercase_update"].update = {}
                if "usercase_preload" in form.actions and form.actions["usercase_preload"].preload:
                    form.actions["usercase_preload"].preload = {}
            else:
                for action in list(form.actions.load_update_cases):
                    if action.auto_select and action.auto_select.mode == AUTO_SELECT_USERCASE:
                        form.actions.load_update_cases.remove(action)
    app.save()
    messages.success(request, _("You have successfully removed User Case properties from this application."))
    return back_to_main(request, domain, app_id=app_id)
Пример #53
0
def delete_module(request, domain, app_id, module_unique_id):
    "Deletes a module from an app"
    app = get_app(domain, app_id)
    try:
        record = app.delete_module(module_unique_id)
    except ModuleNotFoundException:
        return bail(request, domain, app_id)
    if record is not None:
        messages.success(
            request,
            'You have deleted a module. <a href="%s" class="post-link">Undo</a>' % reverse(
                'undo_delete_module', args=[domain, record.get_id]
            ),
            extra_tags='html'
        )
        app.save()
    return back_to_main(request, domain, app_id=app_id)
Пример #54
0
def undo_delete_form(request, domain, record_id):
    record = DeleteFormRecord.get(record_id)
    try:
        record.undo()
        messages.success(request, 'Form successfully restored.')
    except ModuleNotFoundException:
        messages.error(
            request,
            'Form could not be restored: module is missing.'
        )

    return back_to_main(
        request,
        domain,
        app_id=record.app_id,
        module_id=record.module_id,
        form_id=record.form_id
    )
Пример #55
0
def download_jad(request, domain, app_id):
    """
    See ApplicationBase.create_jadjar_from_build_files

    """
    app = request.app
    if not app.copy_of:
        app.set_media_versions()
    jad, _ = app.create_jadjar_from_build_files()
    try:
        response = HttpResponse(jad)
    except Exception:
        messages.error(request, BAD_BUILD_MESSAGE)
        return back_to_main(request, domain, app_id=app_id)
    set_file_download(response, "CommCare.jad")
    response["Content-Type"] = "text/vnd.sun.j2me.app-descriptor"
    response["Content-Length"] = len(jad)
    return response
Пример #56
0
def delete_form(request, domain, app_id, module_unique_id, form_unique_id):
    "Deletes a form from an app"
    app = get_app(domain, app_id)
    record = app.delete_form(module_unique_id, form_unique_id)
    if record is not None:
        messages.success(
            request,
            'You have deleted a form. <a href="%s" class="post-link">Undo</a>'
            % reverse('undo_delete_form', args=[domain, record.get_id]),
            extra_tags='html'
        )
        app.save()
        clear_xmlns_app_id_cache(domain)
    try:
        module_id = app.get_module_by_unique_id(module_unique_id).id
    except ModuleNotFoundException as e:
        messages.error(request, six.text_type(e))
        module_id = None

    return back_to_main(request, domain, app_id=app_id, module_id=module_id)
Пример #57
0
def copy_form(request, domain, app_id, module_id, form_id):
    app = get_app(domain, app_id)
    to_module_id = int(request.POST['to_module_id'])
    try:
        app.copy_form(int(module_id), int(form_id), to_module_id)
    except ConflictingCaseTypeError:
        messages.warning(request, CASE_TYPE_CONFLICT_MSG, extra_tags="html")
        app.save()
    except BlankXFormError:
        # don't save!
        messages.error(request, _('We could not copy this form, because it is blank.'
                              'In order to copy this form, please add some questions first.'))
    except IncompatibleFormTypeException:
        # don't save!
        messages.error(request, _('This form could not be copied because it '
                              'is not compatible with the selected module.'))
    else:
        app.save()

    return back_to_main(request, domain, app_id=app_id, module_id=module_id,
                        form_id=form_id)
Пример #58
0
def download_jar(request, domain, app_id):
    """
    See ApplicationBase.create_jadjar_from_build_files

    This is the only view that will actually be called
    in the process of downloading a complete CommCare.jar
    build (i.e. over the air to a phone).

    """
    response = HttpResponse(content_type="application/java-archive")
    app = request.app
    if not app.copy_of:
        app.set_media_versions()
    _, jar = app.create_jadjar_from_build_files()
    set_file_download(response, 'CommCare.jar')
    response['Content-Length'] = len(jar)
    try:
        response.write(jar)
    except Exception:
        messages.error(request, BAD_BUILD_MESSAGE)
        return back_to_main(request, domain, app_id=app_id)
    return response
Пример #59
0
def new_app(request, domain):
    "Adds an app to the database"
    lang = "en"
    type = request.POST["type"]
    cls = str_to_cls[type]
    form_args = []
    if cls == Application:
        app = cls.new_app(domain, "Untitled Application", lang=lang)
        module = Module.new_module("Untitled Module", lang)
        app.add_module(module)
        form = app.new_form(0, "Untitled Form", lang)
        form_args = [module.id, form.id]
    else:
        app = cls.new_app(domain, "Untitled Application", lang=lang)
    if request.project.secure_submissions:
        app.secure_submissions = True
    app.save()
    clear_app_cache(request, domain)
    main_args = [request, domain, app.id]
    main_args.extend(form_args)

    return back_to_main(*main_args)
Пример #60
0
def overwrite_module_case_list(request, domain, app_id, module_unique_id):
    app = get_app(domain, app_id)
    source_module_unique_id = request.POST['source_module_unique_id']
    source_module = app.get_module_by_unique_id(source_module_unique_id)
    dest_module = app.get_module_by_unique_id(module_unique_id)
    detail_type = request.POST['detail_type']
    assert detail_type in ['short', 'long']
    if not hasattr(source_module, 'case_details'):
        messages.error(
            request,
            _("Sorry, couldn't find case list configuration for module {}. "
              "Please report an issue if you believe this is a mistake.").format(source_module.default_name()))
    elif source_module.case_type != dest_module.case_type:
        messages.error(
            request,
            _("Please choose a module with the same case type as the current one ({}).").format(
                dest_module.case_type)
        )
    else:
        setattr(dest_module.case_details, detail_type, getattr(source_module.case_details, detail_type))
        app.save()
        messages.success(request, _('Case list updated form module {}.').format(source_module.default_name()))
    return back_to_main(request, domain, app_id=app_id, module_unique_id=module_unique_id)