Exemplo n.º 1
0
def get_app_build(app_dict):
    domain = Domain._get_by_name(app_dict['domain'])
    if domain.use_cloudcare_releases:
        return ApplicationBase.get(app_dict['_id']).get_latest_app()['_id']
    else:
        return ApplicationBase.get_latest_build(app_dict['domain'], app_dict['_id'])['_id']
    return None
Exemplo n.º 2
0
def get_app_build(app_dict):
    domain = Domain.get_by_name(app_dict["domain"])
    if domain.use_cloudcare_releases:
        return ApplicationBase.get(app_dict["_id"]).get_latest_app()["_id"]
    else:
        return ApplicationBase.get_latest_build(app_dict["domain"], app_dict["_id"])["_id"]
    return None
Exemplo n.º 3
0
def clear_app_cache(request, domain):
    ApplicationBase.get_db().view(
        'app_manager/applications_brief',
        startkey=[domain],
        limit=1,
    ).all()
    ApplicationsTab.clear_dropdown_cache(domain, request.couch_user.get_id)
Exemplo n.º 4
0
def get_app_build(app_dict):
    domain = Domain.get_by_name(app_dict['domain'])
    if domain.use_cloudcare_releases:
        return ApplicationBase.get(app_dict['_id']).get_latest_app()['_id']
    else:
        return ApplicationBase.get_latest_build(app_dict['domain'],
                                                app_dict['_id'])['_id']
    return None
Exemplo n.º 5
0
    def save(self, request, domain):
        res = DomainGlobalSettingsForm.save(self, request, domain)

        if not res:
            return False
        try:
            domain.project_type = self.cleaned_data['project_type']
            domain.customer_type = self.cleaned_data['customer_type']
            domain.is_test = self.cleaned_data['is_test']
            domain.commconnect_enabled = self.cleaned_data.get(
                'commconnect_enabled', False)
            domain.survey_management_enabled = self.cleaned_data.get(
                'survey_management_enabled', False)
            domain.sms_case_registration_enabled = self.cleaned_data.get(
                'sms_case_registration_enabled', False)
            domain.sms_case_registration_type = self.cleaned_data.get(
                'sms_case_registration_type')
            domain.sms_case_registration_owner_id = self.cleaned_data.get(
                'sms_case_registration_owner_id')
            domain.sms_case_registration_user_id = self.cleaned_data.get(
                'sms_case_registration_user_id')
            domain.default_sms_backend_id = self.cleaned_data.get(
                'default_sms_backend_id')
            domain.call_center_config.enabled = self.cleaned_data.get(
                'call_center_enabled', False)
            if domain.call_center_config.enabled:
                domain.internal.using_call_center = True
                domain.call_center_config.case_owner_id = self.cleaned_data.get(
                    'call_center_case_owner', None)
                domain.call_center_config.case_type = self.cleaned_data.get(
                    'call_center_case_type', None)
            domain.restrict_superusers = self.cleaned_data.get(
                'restrict_superusers', False)
            domain.ota_restore_caching = self.cleaned_data.get(
                'ota_restore_caching', False)
            cloudcare_releases = self.cleaned_data.get('cloudcare_releases')
            if cloudcare_releases and domain.cloudcare_releases != 'default':
                # you're never allowed to change from default
                domain.cloudcare_releases = cloudcare_releases
            secure_submissions = self.cleaned_data.get('secure_submissions',
                                                       False)
            apps_to_save = []
            if secure_submissions != domain.secure_submissions:
                for app in ApplicationBase.by_domain(domain.name):
                    if app.secure_submissions != secure_submissions:
                        app.secure_submissions = secure_submissions
                        apps_to_save.append(app)
            domain.secure_submissions = secure_submissions
            domain.save()
            if apps_to_save:
                ApplicationBase.bulk_save(apps_to_save)
            return True
        except Exception, e:
            logging.exception("couldn't save project settings - error is %s" %
                              e)
            return False
Exemplo n.º 6
0
    def save(self, request, domain):
        try:
            if self.can_use_custom_logo:
                logo = self.cleaned_data['logo']
                if logo:

                    input_image = Image.open(io.BytesIO(logo.read()))
                    input_image.load()
                    input_image.thumbnail(LOGO_SIZE)
                    # had issues trying to use a BytesIO instead
                    tmpfilename = "/tmp/%s_%s" % (uuid.uuid4(), logo.name)
                    input_image.save(tmpfilename, 'PNG')

                    with open(tmpfilename) as tmpfile:
                        domain.put_attachment(tmpfile, name=LOGO_ATTACHMENT)
                elif self.cleaned_data['delete_logo']:
                    domain.delete_attachment(LOGO_ATTACHMENT)

            domain.call_center_config.enabled = self.cleaned_data.get('call_center_enabled', False)
            if domain.call_center_config.enabled:
                domain.internal.using_call_center = True
                domain.call_center_config.case_owner_id = self.cleaned_data.get('call_center_case_owner', None)
                domain.call_center_config.case_type = self.cleaned_data.get('call_center_case_type', None)

            global_tz = self.cleaned_data['default_timezone']
            if domain.default_timezone != global_tz:
                domain.default_timezone = global_tz
                users = WebUser.by_domain(domain.name)
                users_to_save = []
                for user in users:
                    dm = user.get_domain_membership(domain.name)
                    if not dm.override_global_tz and dm.timezone != global_tz:
                        dm.timezone = global_tz
                        users_to_save.append(user)
                if users_to_save:
                    WebUser.bulk_save(users_to_save)

            secure_submissions = self.cleaned_data.get(
                'secure_submissions', False)
            apps_to_save = []
            if secure_submissions != domain.secure_submissions:
                for app in get_apps_in_domain(domain.name):
                    if app.secure_submissions != secure_submissions:
                        app.secure_submissions = secure_submissions
                        apps_to_save.append(app)
            domain.secure_submissions = secure_submissions
            domain.save()
            if apps_to_save:
                ApplicationBase.bulk_save(apps_to_save)
            return True
        except Exception:
            return False
Exemplo n.º 7
0
def clear_app_cache(request, domain):
    ApplicationBase.get_db().view('app_manager/applications_brief',
        startkey=[domain],
        limit=1,
    ).all()
    for is_active in True, False:
        key = make_template_fragment_key('header_tab', [
            domain,
            None,  # tab.org should be None for any non org page
            ApplicationsTab.view,
            is_active,
            request.couch_user.get_id,
            get_language(),
        ])
        cache.delete(key)
Exemplo n.º 8
0
 def _app_latest_build_json(app_id):
     build = ApplicationBase.view('app_manager/saved_app',
                                  startkey=[domain, app_id, {}],
                                  endkey=[domain, app_id],
                                  descending=True,
                                  limit=1).one()
     return build._doc if build else None
Exemplo n.º 9
0
def get_cloudcare_app():
    """
    Total hack function to get direct links to the cloud care application pages
    """

    from corehq.apps.cloudcare import api

    app = api.get_cloudcare_app(PACT_DOMAIN, PACT_CLOUD_APPNAME)
    app_id = app['_id']

    pact_cloudcare = filter(lambda x: x['name']['en'] == PACT_CLOUDCARE_MODULE,
                            app['modules'])
    forms = pact_cloudcare[0]['forms']
    ret = dict((f['name']['en'], ix) for (ix, f) in enumerate(forms))

    url_root = '/a/%(domain)s/cloudcare/apps/view/%(build_id)s/%(module_id)s/%(form_id)s/case/%(case_id)s/enter/'
    ret['url_root'] = url_root
    ret['domain'] = PACT_DOMAIN
    ret['app_id'] = app_id
    latest_build = ApplicationBase.get_latest_build(PACT_DOMAIN, app_id)
    if latest_build is not None:
        latest_build_id = latest_build['_id']
        ret['build_id'] = latest_build_id
    ret['module_id'] = 0
    return ret
Exemplo n.º 10
0
 def testAppsBrief(self):
     """Test that ApplicationBase can wrap the
     truncated version returned by applications_brief
     """
     self.app.save()
     apps = ApplicationBase.get_db().view("app_manager/applications_brief", startkey=[self.domain], limit=1).all()
     self.assertEqual(len(apps), 1)
Exemplo n.º 11
0
def get_form_list(domain):
    form_list = []
    for app in ApplicationBase.view("app_manager/applications_brief",
                                    startkey=[domain],
                                    endkey=[domain, {}]):
        latest_app = get_app(domain, app._id, latest=True)
        if latest_app.doc_type == "Application":
            lang = latest_app.langs[0]
            for m in latest_app.get_modules():
                for f in m.get_forms():
                    try:
                        module_name = m.name[lang]
                    except Exception:
                        module_name = m.name.items()[0][1]
                    try:
                        form_name = f.name[lang]
                    except Exception:
                        form_name = f.name.items()[0][1]
                    form_list.append({
                        "code":
                        f.unique_id,
                        "name":
                        app.name + "/" + module_name + "/" + form_name
                    })
    return form_list
Exemplo n.º 12
0
def case_list(request, domain):
    
    apps = filter(lambda app: app.doc_type == "Application",
                  ApplicationBase.view('app_manager/applications_brief', 
                                       startkey=[domain], endkey=[domain, {}]))
    
    user_id = request.REQUEST.get("user_id", request.couch_user.get_id)
    app_id = request.REQUEST.get("app_id", "")
    module_id = int(request.REQUEST.get("module_id", "0"))
    language = request.REQUEST.get("language", "en")
    
    if not app_id and apps:
        app_id = apps[0].get_id
    
    if app_id:
        app = Application.get(app_id)
        case_short = app.modules[module_id].get_detail("case_short")
        case_long = app.modules[module_id].get_detail("case_long")
    else:
        case_short=""
        case_long=""
    
    return render_to_response(request, "cloudcare/list_cases.html", 
                              {"domain": domain,
                               "language": language,
                               "user_id": user_id,
                               "apps": apps,
                               "case_short": json.dumps(case_short._doc),
                               "case_long": json.dumps(case_long._doc),
                               "cases": json.dumps(get_owned_cases(domain, user_id),
                                                   default=json_handler)})
Exemplo n.º 13
0
 def get_doc_ids():
     for result in db.view("domain/domains", reduce=False).all():
         yield result["id"]
     for result in ApplicationBase.get_db().view(
         "app_manager/applications", startkey=[None], endkey=[None, {}], reduce=False
     ):
         yield result["id"]
Exemplo n.º 14
0
def has_app(domain, *args):
    return bool(ApplicationBase.get_db().view(
        'app_manager/applications_brief',
        startkey=[domain],
        endkey=[domain, {}],
        limit=1
    ).first())
Exemplo n.º 15
0
 def _app_latest_build_json(app_id):
     build = ApplicationBase.view('app_manager/saved_app',
                                  startkey=[domain, app_id, {}],
                                  endkey=[domain, app_id],
                                  descending=True,
                                  limit=1).one()
     return get_app_json(build) if build else None
Exemplo n.º 16
0
def app_list(request, domain, urlPath):
    preview = string_to_boolean(request.REQUEST.get("preview", "false"))
    language = request.couch_user.language or "en"
    
    def _app_latest_build_json(app_id):
        build = ApplicationBase.view('app_manager/saved_app',
                                     startkey=[domain, app["_id"], {}],
                                     endkey=[domain, app["_id"]],
                                     descending=True,
                                     limit=1).one()
        return build._doc if build else None
                                     
    if not preview:
        apps = get_cloudcare_apps(domain)
        # replace the apps with the last build of each app
        apps = [_app_latest_build_json(app["_id"])for app in apps]
    
    else:
        apps = ApplicationBase.view('app_manager/applications_brief', startkey=[domain], endkey=[domain, {}])
        apps = [app._doc for app in apps if app and app.application_version == "2.0"]
    
    # trim out empty apps
    apps = filter(lambda app: app, apps)
    return render_to_response(request, "cloudcare/cloudcare_home.html", 
                              {"domain": domain,
                               "language": language,
                               "apps": json.dumps(apps),
                               "apps_raw": apps,
                               "preview": preview,
                               "maps_api_key": settings.GMAPS_API_KEY })
Exemplo n.º 17
0
    def __init__(self, report, case_dict):

        next_visit = VISIT_SCHEDULE[0]
        last_inter = None
        for action in case_dict['actions']:
            if action['xform_xmlns'] in LAST_INTERACTION_LIST:
                last_inter = action

        for visit_key, visit in enumerate(VISIT_SCHEDULE):
            for key, action in enumerate(case_dict['actions']):
                if visit['xmlns'] == action['xform_xmlns']:
                    try:
                        next_visit = VISIT_SCHEDULE[visit_key + 1]
                        del case_dict['actions'][key]
                        break
                    except IndexError:
                        next_visit = 'last'
        self.next_visit = next_visit
        if last_inter:
            self.last_interaction = last_inter['date']
        self.app_dict = get_cloudcare_app(report.domain, SUCCEED_CM_APPNAME)
        self.latest_build = ApplicationBase.get_latest_build(
            report.domain, self.app_dict['_id'])['_id']
        super(PatientListReportDisplay, self).__init__(report, case_dict)
        self.update_target_date_case_properties()
Exemplo n.º 18
0
 def get_doc_ids():
     for result in db.view('domain/domains', reduce=False).all():
         yield result['id']
     for result in ApplicationBase.get_db().view(
             'app_manager/applications',
             startkey=[None],
             endkey=[None, {}],
             reduce=False):
         yield result['id']
Exemplo n.º 19
0
def get_form_list(domain):
    form_list = []
    for app in ApplicationBase.view("app_manager/applications_brief", startkey=[domain], endkey=[domain, {}]):
        latest_app = get_app(domain, app._id, latest=True)
        if latest_app.doc_type == "Application":
            for m in latest_app.get_modules():
                for f in m.get_forms():
                    form_list.append({"code": f.unique_id, "name": f.full_path_name})
    return form_list
Exemplo n.º 20
0
    def obj_get_list(self, bundle, domain, **kwargs):
        # There should be few enough apps per domain that doing an explicit refresh for each is OK.
        # This is the easiest way to filter remote apps
        # Later we could serialize them to their URL or whatevs but it is not that useful yet
        application_bases = ApplicationBase.by_domain(domain)

        # This wraps in the appropriate class so that is_remote_app() returns the correct answer
        applications = [get_app(domain, application_base.id) for application_base in application_bases]

        return [app for app in applications if not app.is_remote_app()]
Exemplo n.º 21
0
 def form_valid(self, form):
     db = ApplicationBase.get_db()
     build_jsons = db.all_docs(keys=form.build_ids, include_docs=True)
     docs = []
     for doc in [build_json['doc'] for build_json in build_jsons.all()]:
         if doc.get('doc_type') in ['Application', 'RemoteApp']:
             doc['build_broken'] = True
             docs.append(doc)
     db.bulk_save(docs)
     return HttpResponse("posted!")
Exemplo n.º 22
0
 def testAppsBrief(self):
     """Test that ApplicationBase can wrap the
     truncated version returned by applications_brief
     """
     self.app.save()
     apps = ApplicationBase.get_db().view('app_manager/applications_brief',
         startkey=[self.domain],
         limit=1,
     ).all()
     self.assertEqual(len(apps), 1)
Exemplo n.º 23
0
 def form_valid(self, form):
     db = ApplicationBase.get_db()
     build_jsons = db.all_docs(keys=form.build_ids, include_docs=True)
     docs = []
     for doc in [build_json['doc'] for build_json in build_jsons.all()]:
         if doc.get('doc_type') in ['Application', 'RemoteApp']:
             doc['build_broken'] = True
             docs.append(doc)
     db.bulk_save(docs)
     return HttpResponse("posted!")
Exemplo n.º 24
0
 def form_valid(self, form):
     db = ApplicationBase.get_db()
     build_jsons = db.all_docs(keys=form.build_ids, include_docs=True)
     docs = []
     for doc in [build_json["doc"] for build_json in build_jsons.all()]:
         if doc.get("doc_type") in ["Application", "RemoteApp"]:
             doc["build_broken"] = True
             docs.append(doc)
     db.bulk_save(docs)
     return HttpResponse("posted!")
Exemplo n.º 25
0
    def save(self, request, domain):
        res = DomainGlobalSettingsForm.save(self, request, domain)

        if not res:
            return False
        try:
            domain.project_type = self.cleaned_data['project_type']
            domain.customer_type = self.cleaned_data['customer_type']
            domain.is_test = self.cleaned_data['is_test']
            domain.commconnect_enabled = self.cleaned_data.get(
                    'commconnect_enabled', False)
            domain.survey_management_enabled = self.cleaned_data.get('survey_management_enabled', False)
            domain.sms_case_registration_enabled = self.cleaned_data.get('sms_case_registration_enabled', False)
            domain.sms_case_registration_type = self.cleaned_data.get('sms_case_registration_type')
            domain.sms_case_registration_owner_id = self.cleaned_data.get('sms_case_registration_owner_id')
            domain.sms_case_registration_user_id = self.cleaned_data.get('sms_case_registration_user_id')
            domain.default_sms_backend_id = self.cleaned_data.get('default_sms_backend_id')
            domain.call_center_config.enabled = self.cleaned_data.get('call_center_enabled', False)
            if domain.call_center_config.enabled:
                domain.internal.using_call_center = True
                domain.call_center_config.case_owner_id = self.cleaned_data.get('call_center_case_owner', None)
                domain.call_center_config.case_type = self.cleaned_data.get('call_center_case_type', None)
            domain.restrict_superusers = self.cleaned_data.get('restrict_superusers', False)
            domain.ota_restore_caching = self.cleaned_data.get('ota_restore_caching', False)
            cloudcare_releases = self.cleaned_data.get('cloudcare_releases')
            if cloudcare_releases and domain.cloudcare_releases != 'default':
                # you're never allowed to change from default
                domain.cloudcare_releases = cloudcare_releases
            secure_submissions = self.cleaned_data.get('secure_submissions', False)
            apps_to_save = []
            if secure_submissions != domain.secure_submissions:
                for app in ApplicationBase.by_domain(domain.name):
                    if app.secure_submissions != secure_submissions:
                        app.secure_submissions = secure_submissions
                        apps_to_save.append(app)
            domain.secure_submissions = secure_submissions
            domain.save()
            if apps_to_save:
                ApplicationBase.bulk_save(apps_to_save)
            return True
        except Exception, e:
            logging.exception("couldn't save project settings - error is %s" % e)
            return False
Exemplo n.º 26
0
    def obj_get_list(self, bundle, domain, **kwargs):
        # There should be few enough apps per domain that doing an explicit refresh for each is OK.
        # This is the easiest way to filter remote apps
        # Later we could serialize them to their URL or whatevs but it is not that useful yet
        application_bases = ApplicationBase.by_domain(domain)

        # This wraps in the appropriate class so that is_remote_app() returns the correct answer
        applications = [get_app(domain, application_base.id) for application_base in application_bases]

        return [app for app in applications if not app.is_remote_app()]
Exemplo n.º 27
0
def all_apps_by_domain(domain):
    from corehq.apps.app_manager.models import ApplicationBase
    rows = ApplicationBase.get_db().view(
        'app_manager/applications',
        startkey=[domain, None],
        endkey=[domain, None, {}],
        include_docs=True,
    ).all()
    for row in rows:
        doc = row['doc']
        yield get_correct_app_class(doc).wrap(doc)
Exemplo n.º 28
0
def _get_version_from_build_id(domain, build_id):
    try:
        build = ApplicationBase.get(build_id)
    except ResourceNotFound:
        return None
    if not build.copy_of:
        return None
    elif build.domain != domain:
        return None
    else:
        return build.version
Exemplo n.º 29
0
def _get_app_and_build_ids(domain, build_or_app_id):
    try:
        app_json = ApplicationBase.get_db().get(build_or_app_id)
    except ResourceNotFound:
        pass
    else:
        if domain == app_json.get('domain'):
            copy_of = app_json.get('copy_of')
            if copy_of:
                return copy_of, build_or_app_id
    return build_or_app_id, None
Exemplo n.º 30
0
def all_apps_by_domain(domain):
    from corehq.apps.app_manager.models import ApplicationBase
    rows = ApplicationBase.get_db().view(
        'app_manager/applications',
        startkey=[domain, None],
        endkey=[domain, None, {}],
        include_docs=True,
    ).all()
    for row in rows:
        doc = row['doc']
        yield get_correct_app_class(doc).wrap(doc)
Exemplo n.º 31
0
def _get_version_from_build_id(domain, build_id):
    try:
        build = ApplicationBase.get(build_id)
    except ResourceNotFound:
        return None
    if not build.copy_of:
        return None
    elif build.domain != domain:
        return None
    else:
        return build.version
Exemplo n.º 32
0
def _get_app_and_build_ids(domain, build_or_app_id):
    try:
        app_json = ApplicationBase.get_db().get(build_or_app_id)
    except ResourceNotFound:
        pass
    else:
        if domain == app_json.get('domain'):
            copy_of = app_json.get('copy_of')
            if copy_of:
                return copy_of, build_or_app_id
    return build_or_app_id, None
Exemplo n.º 33
0
def get_cloudcare_apps(domain):
    result = ApplicationBase.get_db().view(
        'app_manager/applications_brief',
        startkey=[domain],
        endkey=[domain, {}]
    )
    app_docs = [row['value'] for row in result]
    # Note: even though cloudcare_enabled is in the value emitted by
    # the view, couch will not include it in the emitted value if
    # it's undefined.
    return [
        app for app in app_docs
        if app['doc_type'] == 'Application' and app.get('cloudcare_enabled', False)
    ]
Exemplo n.º 34
0
def all_commcare_settings(request):
    apps = ApplicationBase.view("app_manager/applications_brief", include_docs=True)
    filters = set()
    for param in request.GET:
        s_type, name = param.split(".")
        value = request.GET.get(param)
        filters.add((s_type, name, value))

    def app_filter(settings):
        for s_type, name, value in filters:
            if settings[s_type].get(name) != value:
                return False
        return True

    settings_list = [s for s in (get_settings_values(app) for app in apps) if app_filter(s)]
    return json_response(settings_list)
Exemplo n.º 35
0
def all_commcare_settings(request):
    apps = ApplicationBase.view('app_manager/applications_brief',
                                include_docs=True)
    filters = set()
    for param in request.GET:
        s_type, name = param.split('.')
        value = request.GET.get(param)
        filters.add((s_type, name, value))

    def app_filter(settings):
        for s_type, name, value in filters:
            if settings[s_type].get(name) != value:
                return False
        return True

    settings_list = [s for s in (get_settings_values(app) for app in apps)
                     if app_filter(s)]
    return json_response(settings_list)
Exemplo n.º 36
0
def get_form_list(domain):
    form_list = []
    for app in ApplicationBase.view("app_manager/applications_brief", startkey=[domain], endkey=[domain, {}]):
        latest_app = get_app(domain, app._id, latest=True)
        if latest_app.doc_type == "Application":
            lang = latest_app.langs[0]
            for m in latest_app.get_modules():
                for f in m.get_forms():
                    try:
                        module_name = m.name[lang]
                    except Exception:
                        module_name = m.name.items()[0][1]
                    try:
                        form_name = f.name[lang]
                    except Exception:
                        form_name = f.name.items()[0][1]
                    form_list.append({"code" :  f.unique_id, "name" : app.name + "/" + module_name + "/" + form_name})
    return form_list
Exemplo n.º 37
0
def get_version_from_build_id(domain, build_id):
    """
    fast lookup of app version number given build_id

    implemented as simple caching around _get_version_from_build_id

    """
    if not build_id:
        return None

    try:
        build = ApplicationBase.get(build_id)
    except ResourceNotFound:
        return None
    if not build.copy_of:
        return None
    elif build.domain != domain:
        return None
    else:
        return build.version
Exemplo n.º 38
0
def get_cloudcare_app():
    """
    Total hack function to get direct links to the cloud care application pages
    """

    from corehq.apps.cloudcare import api

    app = api.get_cloudcare_app(PACT_DOMAIN, PACT_CLOUD_APPNAME)
    app_id = app["_id"]

    pact_cloudcare = filter(lambda x: x["name"]["en"] == PACT_CLOUDCARE_MODULE, app["modules"])
    forms = pact_cloudcare[0]["forms"]
    ret = dict((f["name"]["en"], ix) for (ix, f) in enumerate(forms))

    url_root = "/a/%(domain)s/cloudcare/apps/view/%(build_id)s/%(module_id)s/%(form_id)s/case/%(case_id)s/enter/"
    ret["url_root"] = url_root
    ret["domain"] = PACT_DOMAIN
    ret["app_id"] = app_id
    latest_build = ApplicationBase.get_latest_build(PACT_DOMAIN, app_id)
    if latest_build is not None:
        latest_build_id = latest_build["_id"]
        ret["build_id"] = latest_build_id
    ret["module_id"] = 0
    return ret
Exemplo n.º 39
0
    def __init__(self, report, case_dict):

        next_visit = VISIT_SCHEDULE[0]
        last_inter = None
        for action in case_dict['actions']:
            if action['xform_xmlns'] in LAST_INTERACTION_LIST:
                last_inter = action

        for visit_key, visit in enumerate(VISIT_SCHEDULE):
            for key, action in enumerate(case_dict['actions']):
                if visit['xmlns'] == action['xform_xmlns']:
                    try:
                        next_visit = VISIT_SCHEDULE[visit_key + 1]
                        del case_dict['actions'][key]
                        break
                    except IndexError:
                        next_visit = 'last'
        self.next_visit = next_visit
        if last_inter:
            self.last_interaction = last_inter['date']
        self.app_dict = get_cloudcare_app(report.domain, SUCCEED_CM_APPNAME)
        self.latest_build = ApplicationBase.get_latest_build(report.domain, self.app_dict['_id'])['_id']
        super(PatientListReportDisplay, self).__init__(report, case_dict)
        self.update_target_date_case_properties()
Exemplo n.º 40
0
def get_cloudcare_app():
    """
    Total hack function to get direct links to the cloud care application pages
    """

    from corehq.apps.cloudcare import api

    app = api.get_cloudcare_app(PACT_DOMAIN, PACT_CLOUD_APPNAME)
    app_id = app['_id']

    pact_cloudcare = filter(lambda x: x['name']['en'] == PACT_CLOUDCARE_MODULE, app['modules'])
    forms = pact_cloudcare[0]['forms']
    ret = dict((f['name']['en'], ix) for (ix, f) in enumerate(forms))

    url_root = '/a/%(domain)s/cloudcare/apps/view/%(build_id)s/%(module_id)s/%(form_id)s/case/%(case_id)s/enter/'
    ret['url_root'] = url_root
    ret['domain'] = PACT_DOMAIN
    ret['app_id'] = app_id
    latest_build = ApplicationBase.get_latest_build(PACT_DOMAIN, app_id)
    if latest_build is not None:
        latest_build_id = latest_build['_id']
        ret['build_id'] = latest_build_id
    ret['module_id'] = 0
    return ret
Exemplo n.º 41
0
    def get(self, request, domain, urlPath):
        try:
            preview = string_to_boolean(request.GET.get("preview", "false"))
        except ValueError:
            # this is typically only set at all if it's intended to be true so this
            # is a reasonable default for "something went wrong"
            preview = True

        app_access = ApplicationAccess.get_by_domain(domain)
        accessor = CaseAccessors(domain)

        if not preview:
            apps = get_cloudcare_apps(domain)
            if request.project.use_cloudcare_releases:

                if (toggles.CLOUDCARE_LATEST_BUILD.enabled(domain) or
                        toggles.CLOUDCARE_LATEST_BUILD.enabled(request.couch_user.username)):
                    get_cloudcare_app = get_latest_build_doc
                else:
                    get_cloudcare_app = get_latest_released_app_doc

                apps = map(
                    lambda app: get_cloudcare_app(domain, app['_id']),
                    apps,
                )
                apps = filter(None, apps)
                apps = map(wrap_app, apps)

                # convert to json
                apps = [get_app_json(app) for app in apps]
            else:
                # legacy functionality - use the latest build regardless of stars
                apps = [get_latest_build_doc(domain, app['_id']) for app in apps]
                apps = [get_app_json(ApplicationBase.wrap(app)) for app in apps if app]

        else:
            # big TODO: write a new apps view for Formplayer, can likely cut most out now
            if toggles.USE_FORMPLAYER_FRONTEND.enabled(domain):
                apps = get_cloudcare_apps(domain)
            else:
                apps = get_brief_apps_in_domain(domain)
            apps = [get_app_json(app) for app in apps if app and (
                isinstance(app, RemoteApp) or app.application_version == V2)]
            meta = get_meta(request)
            track_clicked_preview_on_hubspot(request.couch_user, request.COOKIES, meta)

        # trim out empty apps
        apps = filter(lambda app: app, apps)
        apps = filter(lambda app: app_access.user_can_access_app(request.couch_user, app), apps)

        def _default_lang():
            if apps:
                # unfortunately we have to go back to the DB to find this
                return Application.get(apps[0]["_id"]).default_language
            else:
                return "en"

        # default language to user's preference, followed by
        # first app's default, followed by english
        language = request.couch_user.language or _default_lang()

        def _url_context():
            # given a url path, returns potentially the app, parent, and case, if
            # they're selected. the front end optimizes with these to avoid excess
            # server calls

            # there's an annoying dependency between this logic and backbone's
            # url routing that seems hard to solve well. this needs to be synced
            # with apps.js if anything changes

            # for apps anything with "view/app/" works

            # for cases it will be:
            # "view/:app/:module/:form/case/:case/"

            # if there are parent cases, it will be:
            # "view/:app/:module/:form/parent/:parent/case/:case/

            # could use regex here but this is actually simpler with the potential
            # absence of a trailing slash
            split = urlPath.split('/')
            app_id = split[1] if len(split) >= 2 else None

            if len(split) >= 5 and split[4] == "parent":
                parent_id = split[5]
                case_id = split[7] if len(split) >= 7 else None
            else:
                parent_id = None
                case_id = split[5] if len(split) >= 6 else None

            app = None
            if app_id:
                if app_id in [a['_id'] for a in apps]:
                    app = look_up_app_json(domain, app_id)
                else:
                    messages.info(request, _("That app is no longer valid. Try using the "
                                             "navigation links to select an app."))
            if app is None and len(apps) == 1:
                app = look_up_app_json(domain, apps[0]['_id'])

            def _get_case(domain, case_id):
                case = accessor.get_case(case_id)
                assert case.domain == domain, "case %s not in %s" % (case_id, domain)
                return case.to_api_json()

            case = _get_case(domain, case_id) if case_id else None
            if parent_id is None and case is not None:
                parent_id = case.get('indices', {}).get('parent', {}).get('case_id', None)
            parent = _get_case(domain, parent_id) if parent_id else None

            return {
                "app": app,
                "case": case,
                "parent": parent
            }

        context = {
            "domain": domain,
            "language": language,
            "apps": apps,
            "apps_raw": apps,
            "preview": preview,
            "maps_api_key": settings.GMAPS_API_KEY,
            "sessions_enabled": request.couch_user.is_commcare_user(),
            "use_cloudcare_releases": request.project.use_cloudcare_releases,
            "username": request.user.username,
            "formplayer_url": settings.FORMPLAYER_URL,
            'use_sqlite_backend': use_sqlite_backend(domain),
        }
        context.update(_url_context())
        if toggles.USE_FORMPLAYER_FRONTEND.enabled(domain):
            return render(request, "cloudcare/formplayer_home.html", context)
        else:
            return render(request, "cloudcare/cloudcare_home.html", context)
Exemplo n.º 42
0
def cloudcare_main(request, domain, urlPath):
    try:
        preview = string_to_boolean(request.REQUEST.get("preview", "false"))
    except ValueError:
        # this is typically only set at all if it's intended to be true so this
        # is a reasonable default for "something went wrong"
        preview = True

    app_access = ApplicationAccess.get_by_domain(domain)
    
    def _app_latest_build_json(app_id):
        build = ApplicationBase.view('app_manager/saved_app',
                                     startkey=[domain, app_id, {}],
                                     endkey=[domain, app_id],
                                     descending=True,
                                     limit=1).one()
        return get_app_json(build) if build else None

    if not preview:
        apps = get_cloudcare_apps(domain)
        # replace the apps with the last build of each app
        apps = [_app_latest_build_json(app["_id"]) for app in apps]
    else:
        apps = ApplicationBase.view('app_manager/applications_brief', startkey=[domain], endkey=[domain, {}])
        apps = [get_app_json(app) for app in apps if app and app.application_version == V2]

    # trim out empty apps
    apps = filter(lambda app: app, apps)
    apps = filter(lambda app: app_access.user_can_access_app(request.couch_user, app), apps)
    
    def _default_lang():
        if apps:
            # unfortunately we have to go back to the DB to find this
            return Application.get(apps[0]["_id"]).build_langs[0]
        else:
            return "en"

    # default language to user's preference, followed by 
    # first app's default, followed by english
    language = request.couch_user.language or _default_lang()
    
    def _url_context():
        # given a url path, returns potentially the app and case, if they're
        # selected. the front end optimizes with these to avoid excess server
        # calls

        # there's an annoying dependency between this logic and backbone's
        # url routing that seems hard to solve well. this needs to be synced
        # with apps.js if anything changes

        # for apps anything with "view/app/" works

        # for cases it will be:
        # "view/:app/:module/:form/case/:case/"
        
        # could use regex here but this is actually simpler with the potential
        # absence of a trailing slash
        split = urlPath.split('/')
        app_id = split[1] if len(split) >= 2 else None
        case_id = split[5] if len(split) >= 6 else None
        
        app = None
        if app_id:
            if app_id in [a['_id'] for a in apps]:
                app = look_up_app_json(domain, app_id)
            else:
                messages.info(request, _("That app is no longer valid. Try using the "
                                         "navigation links to select an app."))
        if app is None and len(apps) == 1:
            app = look_up_app_json(domain, apps[0]['_id'])

        def _get_case(domain, case_id):
            case = CommCareCase.get(case_id)
            assert case.domain == domain, "case %s not in %s" % (case_id, domain)
            return case.get_json()
        
        case = _get_case(domain, case_id) if case_id else None
        return {
            "app": app,
            "case": case
        }

    context = {
       "domain": domain,
       "language": language,
       "apps": apps,
       "apps_raw": apps,
       "preview": preview,
       "maps_api_key": settings.GMAPS_API_KEY
    }
    context.update(_url_context())
    return render(request, "cloudcare/cloudcare_home.html", context)
Exemplo n.º 43
0
    def get(self, request, domain, urlPath):
        try:
            preview = string_to_boolean(request.GET.get("preview", "false"))
        except ValueError:
            # this is typically only set at all if it's intended to be true so this
            # is a reasonable default for "something went wrong"
            preview = True

        app_access = ApplicationAccess.get_by_domain(domain)
        accessor = CaseAccessors(domain)

        if not preview:
            apps = get_cloudcare_apps(domain)
            if request.project.use_cloudcare_releases:

                if (toggles.CLOUDCARE_LATEST_BUILD.enabled(domain)
                        or toggles.CLOUDCARE_LATEST_BUILD.enabled(
                            request.couch_user.username)):
                    get_cloudcare_app = get_latest_build_doc
                else:
                    get_cloudcare_app = get_latest_released_app_doc

                apps = map(
                    lambda app: get_cloudcare_app(domain, app['_id']),
                    apps,
                )
                apps = filter(None, apps)
                apps = map(wrap_app, apps)

                # convert to json
                apps = [get_app_json(app) for app in apps]
            else:
                # legacy functionality - use the latest build regardless of stars
                apps = [
                    get_latest_build_doc(domain, app['_id']) for app in apps
                ]
                apps = [
                    get_app_json(ApplicationBase.wrap(app)) for app in apps
                    if app
                ]

        else:
            # big TODO: write a new apps view for Formplayer, can likely cut most out now
            if toggles.USE_FORMPLAYER_FRONTEND.enabled(domain):
                apps = get_cloudcare_apps(domain)
            else:
                apps = get_brief_apps_in_domain(domain)
            apps = [
                get_app_json(app) for app in apps if app and
                (isinstance(app, RemoteApp) or app.application_version == V2)
            ]
            meta = get_meta(request)
            track_clicked_preview_on_hubspot(request.couch_user,
                                             request.COOKIES, meta)

        # trim out empty apps
        apps = filter(lambda app: app, apps)
        apps = filter(
            lambda app: app_access.user_can_access_app(request.couch_user, app
                                                       ), apps)

        def _default_lang():
            if apps:
                # unfortunately we have to go back to the DB to find this
                return Application.get(apps[0]["_id"]).default_language
            else:
                return "en"

        # default language to user's preference, followed by
        # first app's default, followed by english
        language = request.couch_user.language or _default_lang()

        def _url_context():
            # given a url path, returns potentially the app, parent, and case, if
            # they're selected. the front end optimizes with these to avoid excess
            # server calls

            # there's an annoying dependency between this logic and backbone's
            # url routing that seems hard to solve well. this needs to be synced
            # with apps.js if anything changes

            # for apps anything with "view/app/" works

            # for cases it will be:
            # "view/:app/:module/:form/case/:case/"

            # if there are parent cases, it will be:
            # "view/:app/:module/:form/parent/:parent/case/:case/

            # could use regex here but this is actually simpler with the potential
            # absence of a trailing slash
            split = urlPath.split('/')
            app_id = split[1] if len(split) >= 2 else None

            if len(split) >= 5 and split[4] == "parent":
                parent_id = split[5]
                case_id = split[7] if len(split) >= 7 else None
            else:
                parent_id = None
                case_id = split[5] if len(split) >= 6 else None

            app = None
            if app_id:
                if app_id in [a['_id'] for a in apps]:
                    app = look_up_app_json(domain, app_id)
                else:
                    messages.info(
                        request,
                        _("That app is no longer valid. Try using the "
                          "navigation links to select an app."))
            if app is None and len(apps) == 1:
                app = look_up_app_json(domain, apps[0]['_id'])

            def _get_case(domain, case_id):
                case = accessor.get_case(case_id)
                assert case.domain == domain, "case %s not in %s" % (case_id,
                                                                     domain)
                return case.to_api_json()

            case = _get_case(domain, case_id) if case_id else None
            if parent_id is None and case is not None:
                parent_id = case.get('indices',
                                     {}).get('parent',
                                             {}).get('case_id', None)
Exemplo n.º 44
0
 def applications(self):
     from corehq.apps.app_manager.models import ApplicationBase
     return ApplicationBase.view('app_manager/applications_brief',
                                 startkey=[self.name],
                                 endkey=[self.name, {}]).all()
Exemplo n.º 45
0
def get_cloudcare_apps(domain):
    return map(
        lambda app: app._doc,
        ApplicationBase.view('cloudcare/cloudcare_apps',
                             startkey=[domain],
                             endkey=[domain, {}]))
Exemplo n.º 46
0
def cloudcare_main(request, domain, urlPath):
    try:
        preview = string_to_boolean(request.REQUEST.get("preview", "false"))
    except ValueError:
        # this is typically only set at all if it's intended to be true so this
        # is a reasonable default for "something went wrong"
        preview = True

    app_access = ApplicationAccess.get_by_domain(domain)

    if not preview:
        apps = get_cloudcare_apps(domain)
        if request.project.use_cloudcare_releases:
            # replace the apps with the last starred build of each app, removing the ones that aren't starred
            apps = filter(
                lambda app: app.is_released,
                [get_app(domain, app['_id'], latest=True) for app in apps])
            # convert to json
            apps = [get_app_json(app) for app in apps]
        else:
            # legacy functionality - use the latest build regardless of stars
            apps = [
                get_app_json(
                    ApplicationBase.get_latest_build(domain, app['_id']))
                for app in apps
            ]

    else:
        apps = ApplicationBase.view('app_manager/applications_brief',
                                    startkey=[domain],
                                    endkey=[domain, {}])
        apps = [
            get_app_json(app) for app in apps
            if app and app.application_version == V2
        ]

    # trim out empty apps
    apps = filter(lambda app: app, apps)
    apps = filter(
        lambda app: app_access.user_can_access_app(request.couch_user, app),
        apps)

    def _default_lang():
        if apps:
            # unfortunately we have to go back to the DB to find this
            return Application.get(apps[0]["_id"]).build_langs[0]
        else:
            return "en"

    # default language to user's preference, followed by
    # first app's default, followed by english
    language = request.couch_user.language or _default_lang()

    def _url_context():
        # given a url path, returns potentially the app, parent, and case, if
        # they're selected. the front end optimizes with these to avoid excess
        # server calls

        # there's an annoying dependency between this logic and backbone's
        # url routing that seems hard to solve well. this needs to be synced
        # with apps.js if anything changes

        # for apps anything with "view/app/" works

        # for cases it will be:
        # "view/:app/:module/:form/case/:case/"

        # if there are parent cases, it will be:
        # "view/:app/:module/:form/parent/:parent/case/:case/

        # could use regex here but this is actually simpler with the potential
        # absence of a trailing slash
        split = urlPath.split('/')
        app_id = split[1] if len(split) >= 2 else None

        if len(split) >= 5 and split[4] == "parent":
            parent_id = split[5]
            case_id = split[7] if len(split) >= 7 else None
        else:
            parent_id = None
            case_id = split[5] if len(split) >= 6 else None

        app = None
        if app_id:
            if app_id in [a['_id'] for a in apps]:
                app = look_up_app_json(domain, app_id)
            else:
                messages.info(
                    request,
                    _("That app is no longer valid. Try using the "
                      "navigation links to select an app."))
        if app is None and len(apps) == 1:
            app = look_up_app_json(domain, apps[0]['_id'])

        def _get_case(domain, case_id):
            case = CommCareCase.get(case_id)
            assert case.domain == domain, "case %s not in %s" % (case_id,
                                                                 domain)
            return case.get_json()

        case = _get_case(domain, case_id) if case_id else None
        if parent_id is None and case is not None:
            parent_id = case.get('indices', {}).get('parent',
                                                    {}).get('case_id', None)
Exemplo n.º 47
0
def clear_app_cache(request, domain):
    ApplicationBase.get_db().view("app_manager/applications_brief", startkey=[domain], limit=1).all()
    ApplicationsTab.clear_dropdown_cache(domain, request.couch_user.get_id)
Exemplo n.º 48
0
def get_cloudcare_apps(domain):
    return map(lambda app: app._doc,
               ApplicationBase.view('cloudcare/cloudcare_apps', 
                                    startkey=[domain], endkey=[domain, {}]))
Exemplo n.º 49
0
 def test_app_base(self):
     apps = ApplicationBase.by_domain(self.domain)
     self.assertEqual(len(apps), 2)
Exemplo n.º 50
0
def excel_config(request, domain):
    if request.method != 'POST':
        return HttpResponseRedirect(base.ImportCases.get_url(domain=domain))

    if not request.FILES:
        return render_error(request, domain,
                            'Please choose an Excel file to import.')

    named_columns = request.POST.get('named_columns') == "on"
    uploaded_file_handle = request.FILES['file']

    extension = os.path.splitext(
        uploaded_file_handle.name)[1][1:].strip().lower()

    # NOTE: We may not always be able to reference files from subsequent
    # views if your worker changes, so we have to store it elsewhere
    # using the soil framework.

    if extension not in importer_util.ExcelFile.ALLOWED_EXTENSIONS:
        return render_error(
            request, domain,
            'The Excel file you chose could not be processed. '
            'Please check that it is saved as a Microsoft '
            'Excel 97/2000 .xls file.')

    # stash content in the default storage for subsequent views
    file_ref = expose_download(uploaded_file_handle.read(), expiry=1 * 60 * 60)
    request.session[EXCEL_SESSION_ID] = file_ref.download_id
    spreadsheet = importer_util.get_spreadsheet(file_ref, named_columns)

    if not spreadsheet:
        return _spreadsheet_expired(request, domain)

    columns = spreadsheet.get_header_columns()
    row_count = spreadsheet.get_num_rows()

    if row_count == 0:
        return render_error(
            request, domain, 'Your spreadsheet is empty. '
            'Please try again with a different spreadsheet.')

    case_types_from_apps = []
    # load types from all modules
    for row in ApplicationBase.view('app_manager/types_by_module',
                                    reduce=True,
                                    group=True,
                                    startkey=[domain],
                                    endkey=[domain, {}]).all():
        if not row['key'][1] in case_types_from_apps:
            case_types_from_apps.append(row['key'][1])

    case_types_from_cases = []
    # load types from all case records
    for row in CommCareCase.view('hqcase/types_by_domain',
                                 reduce=True,
                                 group=True,
                                 startkey=[domain],
                                 endkey=[domain, {}]).all():
        if row['key'][1] and not row['key'][1] in case_types_from_cases:
            case_types_from_cases.append(row['key'][1])

    # for this we just want cases that have data but aren't being used anymore
    case_types_from_cases = filter(lambda x: x not in case_types_from_apps,
                                   case_types_from_cases)

    if len(case_types_from_apps) == 0 and len(case_types_from_cases) == 0:
        return render_error(
            request, domain,
            'No cases have been submitted to this domain and there are no '
            'applications yet. You cannot import case details from an Excel '
            'file until you have existing cases or applications.')

    return render(
        request, "importer/excel_config.html", {
            'named_columns': named_columns,
            'columns': columns,
            'case_types_from_cases': case_types_from_cases,
            'case_types_from_apps': case_types_from_apps,
            'domain': domain,
            'report': {
                'name': 'Import: Configuration'
            },
            'slug': base.ImportCases.slug
        })
Exemplo n.º 51
0
def has_app(domain, *args):
    return bool(ApplicationBase.get_db().view('app_manager/applications_brief',
                                              startkey=[domain],
                                              endkey=[domain, {}],
                                              limit=1).first())
Exemplo n.º 52
0
def cloudcare_main(request, domain, urlPath):
    try:
        preview = string_to_boolean(request.REQUEST.get("preview", "false"))
    except ValueError:
        # this is typically only set at all if it's intended to be true so this
        # is a reasonable default for "something went wrong"
        preview = True

    app_access = ApplicationAccess.get_by_domain(domain)

    if not preview:
        apps = get_cloudcare_apps(domain)
        if request.project.use_cloudcare_releases:
            # replace the apps with the last starred build of each app, removing the ones that aren't starred
            apps = filter(lambda app: app.is_released, [get_app(domain, app['_id'], latest=True) for app in apps])
            # convert to json
            apps = [get_app_json(app) for app in apps]
        else:
            # legacy functionality - use the latest build regardless of stars
            apps = [get_app_json(ApplicationBase.get_latest_build(domain, app['_id'])) for app in apps]

    else:
        apps = ApplicationBase.view('app_manager/applications_brief', startkey=[domain], endkey=[domain, {}])
        apps = [get_app_json(app) for app in apps if app and app.application_version == V2]

    # trim out empty apps
    apps = filter(lambda app: app, apps)
    apps = filter(lambda app: app_access.user_can_access_app(request.couch_user, app), apps)
    
    def _default_lang():
        if apps:
            # unfortunately we have to go back to the DB to find this
            return Application.get(apps[0]["_id"]).build_langs[0]
        else:
            return "en"

    # default language to user's preference, followed by 
    # first app's default, followed by english
    language = request.couch_user.language or _default_lang()
    
    def _url_context():
        # given a url path, returns potentially the app, parent, and case, if
        # they're selected. the front end optimizes with these to avoid excess
        # server calls

        # there's an annoying dependency between this logic and backbone's
        # url routing that seems hard to solve well. this needs to be synced
        # with apps.js if anything changes

        # for apps anything with "view/app/" works

        # for cases it will be:
        # "view/:app/:module/:form/case/:case/"

        # if there are parent cases, it will be:
        # "view/:app/:module/:form/parent/:parent/case/:case/
        
        # could use regex here but this is actually simpler with the potential
        # absence of a trailing slash
        split = urlPath.split('/')
        app_id = split[1] if len(split) >= 2 else None

        if len(split) >= 5 and split[4] == "parent":
            parent_id = split[5]
            case_id = split[7] if len(split) >= 7 else None
        else:
            parent_id = None
            case_id = split[5] if len(split) >= 6 else None

        app = None
        if app_id:
            if app_id in [a['_id'] for a in apps]:
                app = look_up_app_json(domain, app_id)
            else:
                messages.info(request, _("That app is no longer valid. Try using the "
                                         "navigation links to select an app."))
        if app is None and len(apps) == 1:
            app = look_up_app_json(domain, apps[0]['_id'])

        def _get_case(domain, case_id):
            case = CommCareCase.get(case_id)
            assert case.domain == domain, "case %s not in %s" % (case_id, domain)
            return case.get_json()

        case = _get_case(domain, case_id) if case_id else None
        if parent_id is None and case is not None:
            parent_id = case.get('indices',{}).get('parent', {}).get('case_id', None)
        parent = _get_case(domain, parent_id) if parent_id else None

        return {
            "app": app,
            "case": case,
            "parent": parent
        }

    context = {
       "domain": domain,
       "language": language,
       "apps": apps,
       "apps_raw": apps,
       "preview": preview,
       "maps_api_key": settings.GMAPS_API_KEY,
       'offline_enabled': toggles.OFFLINE_CLOUDCARE.enabled(request.user.username),
       'sessions_enabled': request.couch_user.is_commcare_user(),
       'use_cloudcare_releases': request.project.use_cloudcare_releases,
    }
    context.update(_url_context())
    return render(request, "cloudcare/cloudcare_home.html", context)
Exemplo n.º 53
0
def cloudcare_main(request, domain, urlPath):
    preview = string_to_boolean(request.REQUEST.get("preview", "false"))
    app_access = ApplicationAccess.get_by_domain(domain)

    def _app_latest_build_json(app_id):
        build = ApplicationBase.view('app_manager/saved_app',
                                     startkey=[domain, app_id, {}],
                                     endkey=[domain, app_id],
                                     descending=True,
                                     limit=1).one()
        return build._doc if build else None

    if not preview:
        apps = get_cloudcare_apps(domain)
        # replace the apps with the last build of each app
        apps = [_app_latest_build_json(app["_id"]) for app in apps]

    else:
        apps = ApplicationBase.view('app_manager/applications_brief',
                                    startkey=[domain],
                                    endkey=[domain, {}])
        apps = [
            app._doc for app in apps
            if app and app.application_version == "2.0"
        ]

    # trim out empty apps
    apps = filter(lambda app: app, apps)
    apps = filter(
        lambda app: app_access.user_can_access_app(request.couch_user, app),
        apps)

    def _default_lang():
        if apps:
            # unfortunately we have to go back to the DB to find this
            return Application.get(apps[0]["_id"]).build_langs[0]
        else:
            return "en"

    # default language to user's preference, followed by
    # first app's default, followed by english
    language = request.couch_user.language or _default_lang()

    def _url_context():
        # given a url path, returns potentially the app and case, if they're
        # selected. the front end optimizes with these to avoid excess server
        # calls

        # there's an annoying dependency between this logic and backbone's
        # url routing that seems hard to solve well. this needs to be synced
        # with apps.js if anything changes

        # for apps anything with "view/app/" works

        # for cases it will be:
        # "view/:app/:module/:form/case/:case/"

        # could use regex here but this is actually simpler with the potential
        # absence of a trailing slash
        split = urlPath.split('/')
        app_id = split[1] if len(split) >= 2 else None
        case_id = split[5] if len(split) >= 6 else None

        app = None
        if app_id:
            if app_id in [a['_id'] for a in apps]:
                app = get_app(domain, app_id)
            else:
                messages.info(
                    request,
                    _("That app is no longer valid. Try using the "
                      "navigation links to select an app."))
        if app == None and len(apps) == 1:
            app = get_app(domain, apps[0]['_id'])

        def _get_case(domain, case_id):
            case = CommCareCase.get(case_id)
            assert case.domain == domain, "case %s not in %s" % (case_id,
                                                                 domain)
            return case.get_json()

        case = _get_case(domain, case_id) if case_id else None
        return {"app": app, "case": case}