def get(self, request, domain, app_id, **kwargs): app_access = ApplicationAccess.get_by_domain(domain) app = get_current_app(domain, app_id) if not app_access.user_can_access_app(request.couch_user, app): raise Http404() def _default_lang(): try: return app['langs'][0] except Exception: 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() context = { "domain": domain, "language": language, "apps": [app], "maps_api_key": settings.GMAPS_API_KEY, "username": request.user.username, "formplayer_url": settings.FORMPLAYER_URL, "single_app_mode": True, "home_url": reverse(self.urlname, args=[domain, app_id]), "environment": WEB_APPS_ENVIRONMENT, } return render(request, "cloudcare/formplayer_home.html", context)
def handle(self, from_domain, from_app_id, to_domain, to_app_id, *args, **options): self.from_domain = from_domain self.to_domain = to_domain app = get_current_app(self.to_domain, to_app_id) latest_master_build = get_app(None, from_app_id, latest=True) overwrite_app(app, latest_master_build, self.report_map)
def get(self, request, domain, app_id, **kwargs): app_access = ApplicationAccess.get_by_domain(domain) app = get_current_app(domain, app_id) if not app_access.user_can_access_app(request.couch_user, app): raise Http404() role = request.couch_user.get_role(domain) if role and not role.permissions.view_web_app(app): raise Http404() def _default_lang(): try: return app['langs'][0] except Exception: 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() context = { "domain": domain, "language": language, "apps": [app], "maps_api_key": settings.GMAPS_API_KEY, "username": request.user.username, "formplayer_url": settings.FORMPLAYER_URL, "single_app_mode": True, "home_url": reverse(self.urlname, args=[domain, app_id]), "environment": WEB_APPS_ENVIRONMENT, 'use_live_query': toggles.FORMPLAYER_USE_LIVEQUERY.enabled(domain), } return render(request, "cloudcare/formplayer_home.html", context)
def pull_master_app(request, domain, app_id): master_app_id = request.POST.get('master_app_id') if not master_app_id: messages.error(request, _("Please select a master app.")) return HttpResponseRedirect( reverse_util('app_settings', params={}, args=[domain, app_id])) async_update = request.POST.get('notify') == 'on' if async_update: update_linked_app_and_notify_task.delay(domain, app_id, master_app_id, request.couch_user.get_id, request.couch_user.email) messages.success( request, _('Your request has been submitted. We will notify you via email once completed.' )) else: app = get_current_app(domain, app_id) try: update_linked_app(app, master_app_id, 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, _('Your linked application was successfully updated to the latest version.' )) track_workflow(request.couch_user.username, "Linked domain: master app pulled") return HttpResponseRedirect( reverse_util('app_settings', params={}, args=[domain, app_id]))
def get_apps(domain): for app_id in get_app_ids_in_domain(domain): try: app = get_current_app(domain, app_id) except Exception: pass # It's not gonna load in app manager anyways if not app.is_remote_app(): yield app
def _get_app_and_item(self, app_id, domain, request): try: app = get_current_app(domain, app_id) except ResourceNotFound: raise Http404 item = request.GET.get('whitelist_item') if not item: item = QueryDict(request.body).get('whitelist_item') return app, item
def pull_master_app(request, domain, app_id): app = get_current_app(domain, app_id) try: update_linked_app(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, _('Your linked application was successfully updated to the latest version.')) return HttpResponseRedirect(reverse_util('app_settings', params={}, args=[domain, app_id]))
def get(self, request, domain, app_id, **kwargs): app_access = get_application_access_for_domain(domain) app = get_current_app(domain, app_id) if not app_access.user_can_access_app(request.couch_user, app): raise Http404() role = request.couch_user.get_role(domain) if role and not role.permissions.view_web_app(app.master_id): raise Http404() def _default_lang(): try: return app['langs'][0] except Exception: 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() domain_obj = Domain.get_by_name(domain) context = { "domain": domain, "default_geocoder_location": domain_obj.default_geocoder_location, "language": language, "apps": [_format_app(app)], "mapbox_access_token": settings.MAPBOX_ACCESS_TOKEN, "username": request.user.username, "formplayer_url": settings.FORMPLAYER_URL, "single_app_mode": True, "home_url": reverse(self.urlname, args=[domain, app_id]), "environment": WEB_APPS_ENVIRONMENT, 'use_live_query': toggles.FORMPLAYER_USE_LIVEQUERY.enabled(domain), "integrations": integration_contexts(domain), "has_geocoder_privs": domain_has_privilege(domain, privileges.GEOCODER), } return render(request, "cloudcare/formplayer_home.html", context)
def pull_master_app(request, domain, app_id): async_update = request.POST.get('notify') == 'on' if async_update: update_linked_app_and_notify_task.delay(domain, app_id, request.couch_user.get_id, request.couch_user.email) messages.success(request, _('Your request has been submitted. We will notify you via email once completed.')) else: app = get_current_app(domain, app_id) try: update_linked_app(app, request.couch_user.get_id) except AppLinkError as e: messages.error(request, six.text_type(e)) return HttpResponseRedirect(reverse_util('app_settings', params={}, args=[domain, app_id])) messages.success(request, _('Your linked application was successfully updated to the latest version.')) track_workflow(request.couch_user.username, "Linked domain: master app pulled") return HttpResponseRedirect(reverse_util('app_settings', params={}, args=[domain, app_id]))
def __init__(self, domain, app_id, version, key_lang, source_lang, lang_prefix, exclude_if_default=False, use_version_postfix=True): """ Generates translations for source/default lang files and also for translated files :param domain: domain name :param app_id: app UUID :param version: version of the app to use, usually the built version. If none, the current app state is used. :param key_lang: the lang used to create msgid in PO files. Usually en. :param source_lang: the lang to create the msgstr in PO files. Should be same as key lang for source files and the target lang for translated files :param lang_prefix: usually default_ :param exclude_if_default: set this to skip adding msgstr in case its same as the default language. For details: https://github.com/dimagi/commcare-hq/pull/20706 :param use_version_postfix: use version number at the end of resource slugs """ if key_lang == source_lang and exclude_if_default: raise Exception( "Looks like you are setting up the file for default language " "and doing that with exclude_if_default is not expected since " "that would result in empty msgstr and no display for other lang" ) self.domain = domain self.app_id = app_id self.app = get_current_app(domain, app_id) self.key_lang = key_lang self.source_lang = source_lang self.lang_prefix = lang_prefix self.exclude_if_default = exclude_if_default self.version = self.app.version if version is None else version self.use_version_postfix = use_version_postfix self.checker = EligibleForTransifexChecker(self.app) self.headers = dict() # headers for each sheet name self.sheet_name_to_module_or_form_type_and_id = dict() self.slug_to_name = defaultdict(dict) self.slug_to_name[MODULES_AND_FORMS_SHEET_NAME] = { 'en': MODULES_AND_FORMS_SHEET_NAME } self.translations = self._build_translations()
def update_linked_app_and_notify(domain, app_id, user_id, email): app = get_current_app(domain, app_id) subject = _("Update Status for linked app %s") % app.name try: update_linked_app(app, user_id) except (AppLinkError, MultimediaMissingError) as e: message = six.text_type(e) except Exception: # Send an email but then crash the process # so we know what the error was send_html_email_async.delay(subject, email, _( "Something went wrong updating your linked app. " "Our team has been notified and will monitor the situation. " "Please try again, and if the problem persists report it as an issue.")) raise else: message = _("Your linked application was successfully updated to the latest version.") send_html_email_async.delay(subject, email, message)
def update_linked_app_and_notify(domain, app_id, master_app_id, user_id, email): app = get_current_app(domain, app_id) subject = _("Update Status for linked app %s") % app.name try: update_linked_app(app, master_app_id, user_id) except (AppLinkError, MultimediaMissingError) as e: message = str(e) except Exception: # Send an email but then crash the process # so we know what the error was send_html_email_async.delay(subject, email, _( "Something went wrong updating your linked app. " "Our team has been notified and will monitor the situation. " "Please try again, and if the problem persists report it as an issue.")) raise else: message = _("Your linked application was successfully updated to the latest version.") send_html_email_async.delay(subject, email, message)
def _build_translations(self): """ :return: { sheet_name_with_build_id: { key: Translation(key, translation, occurrences) } } """ from corehq.apps.app_manager.dbaccessors import get_current_app app = get_current_app(self.domain, self.app_id_to_build) if self.version is None: self.version = app.version rows = self._translation_data(app) for sheet_name in rows: file_name = self._get_filename(sheet_name) self.translations[file_name] = self._get_translation_for_sheet( app, sheet_name, rows[sheet_name])
def handle(self, from_domain, from_app_id, to_domain, *args, **options): self.from_domain = from_domain self.to_domain = to_domain to_app_id = options.get('to-app-id') version = options.get('version') if to_app_id: app = get_current_app(self.to_domain, to_app_id) print('Overwriting application: {}'.format(app.name)) else: print('Creating new application') app = Application() if version: from_app_doc = get_build_doc_by_version(self.from_domain, from_app_id, version) else: from_app_doc = get_latest_released_app_doc(self.from_domain, from_app_id) if not from_app_doc: raise CommandError("From app not found") from_app = wrap_app(from_app_doc) print('Overwring app with "{}" (version {})'.format(from_app.name, from_app.version)) overwrite_app(app, from_app, self.report_map)
def fetch_app(self, domain, app_id): return get_current_app(domain, app_id)
def handle(self, domain, app_id, module_id, *args, **options): app = get_current_app(domain, app_id) module = app.get_module_by_unique_id(module_id) assert module.doc_type == 'Module', "Only support modules" assert module.display_style == 'list', "Doesn't support grid case lists" assert module.referral_list.show is False, "Doesn't support referral lists" assert module.ref_details.short.columns == [], "Doesn't support ref details" assert module.ref_details.long.columns == [], "Doesn't support ref details" assert module.task_list.show is False, "Doesn't support task lists" latest_build = get_latest_build_version(domain, app_id) if latest_build != app.version: app.validate_app() copy = app.make_build( comment="Build before moving {} to an advanced module".format( module.name), ) copy.save(increment_version=False) module.module_type = 'advanced' module.doc_type = 'AdvancedModule' forms = [] for form in module.forms: # https://github.com/dimagi/commcare-hq/blob/271ab9346745e7a8a4d647db66dc959fbb9f8159/corehq/apps/app_manager/models.py#L3182 assert isinstance(form, Form) new_form = AdvancedForm( name=form.name, form_filter=form.form_filter, media_image=form.media_image, media_audio=form.media_audio, comment=form.comment, ) new_form._parent = module form._parent = module new_form.source = form.source actions = form.active_actions() open = actions.get('open_case', None) update = actions.get('update_case', None) close = actions.get('close_case', None) preload = actions.get('case_preload', None) subcases = actions.get('subcases', None) case_type = module.case_type base_action = None if open: base_action = AdvancedOpenCaseAction( case_type=case_type, case_tag='open_{0}_0'.format(case_type), name_path=open.name_path, open_condition=open.condition, case_properties=update.update if update else {}, ) new_form.actions.open_cases.append(base_action) elif update or preload or close: base_action = LoadUpdateAction( case_type=case_type, case_tag='load_{0}_0'.format(case_type), case_properties=update.update if update else {}, preload=preload.preload if preload else {}, ) if module.parent_select.active: select_chain = get_select_chain(app, module, include_self=False) for n, link in enumerate( reversed(list(enumerate(select_chain)))): i, module = link new_form.actions.load_update_cases.append( LoadUpdateAction( case_type=module.case_type, case_tag='_'.join(['parent'] * (i + 1)), details_module=module.unique_id, case_index=CaseIndex( tag='_'.join(['parent'] * (i + 2)) if n > 0 else ''), )) base_action.case_indices = [CaseIndex(tag='parent')] if close: base_action.close_condition = close.condition new_form.actions.load_update_cases.append(base_action) if subcases: for i, subcase in enumerate(subcases): open_subcase_action = AdvancedOpenCaseAction( case_type=subcase.case_type, case_tag='open_{0}_{1}'.format(subcase.case_type, i + 1), name_path=subcase.case_name, open_condition=subcase.condition, case_properties=subcase.case_properties, repeat_context=subcase.repeat_context, case_indices=[ CaseIndex( tag=base_action.case_tag if base_action else '', reference_id=subcase.reference_id, ) ], ) new_form.actions.open_cases.append(open_subcase_action) new_form.unique_id = form.unique_id forms.append(new_form.to_json()) new_module = module.to_json() new_module['forms'] = forms del new_module['display_style'] del new_module['referral_list'] del new_module['ref_details'] del new_module['task_list'] del new_module[ 'parent_select'] # This is handled in forms for advanced modules new_module = AdvancedModule.wrap(new_module) modules = app.modules mod_index = [ i for i, mod in enumerate(modules) if mod.unique_id == module_id ][0] modules[mod_index] = new_module app.modules = modules app.save() # update xml app = get_current_app(domain, app_id) module = app.get_module_by_unique_id(module_id) for form in module.forms: real_form = app.get_form(form.unique_id) if form.xmlns in (DUE_LIST_XMLNS, IMMUNIZATION_XMLNS): new_form_source = form.source.replace( "instance('commcaresession')/session/data/case_id", "instance('commcaresession')/session/data/case_id_load_tasks_0" ) real_form.source = new_form_source elif form.xmlns == ELIGIBLE_COUPLE_XMLNS: new_form_source = form.source.replace( "instance('commcaresession')/session/data/case_id", "instance('commcaresession')/session/data/case_id_load_person_0" ) real_form.source = new_form_source app.save() copy = app.make_build(comment="{} moved to an advanced module".format( module.name), ) copy.save(increment_version=False)
def handle(self, domain, app_id, module_id, *args, **options): app = get_current_app(domain, app_id) module = app.get_module_by_unique_id(module_id) assert module.doc_type == 'Module', "Only support modules" assert module.display_style == 'list', "Doesn't support grid case lists" assert module.referral_list.show is False, "Doesn't support referral lists" assert module.ref_details.short.columns == [], "Doesn't support ref details" assert module.ref_details.long.columns == [], "Doesn't support ref details" assert module.task_list.show is False, "Doesn't support task lists" latest_build = get_latest_build_version(domain, app_id) if latest_build != app.version: app.validate_app() copy = app.make_build( comment="Build before moving {} to an advanced module".format(module.name), ) copy.save(increment_version=False) module.module_type = 'advanced' module.doc_type = 'AdvancedModule' forms = [] for form in module.forms: # https://github.com/dimagi/commcare-hq/blob/271ab9346745e7a8a4d647db66dc959fbb9f8159/corehq/apps/app_manager/models.py#L3182 assert isinstance(form, Form) new_form = AdvancedForm( name=form.name, form_filter=form.form_filter, media_image=form.media_image, media_audio=form.media_audio, comment=form.comment, ) new_form._parent = module form._parent = module new_form.source = form.source actions = form.active_actions() open = actions.get('open_case', None) update = actions.get('update_case', None) close = actions.get('close_case', None) preload = actions.get('case_preload', None) subcases = actions.get('subcases', None) case_type = module.case_type base_action = None if open: base_action = AdvancedOpenCaseAction( case_type=case_type, case_tag='open_{0}_0'.format(case_type), name_path=open.name_path, open_condition=open.condition, case_properties=update.update if update else {}, ) new_form.actions.open_cases.append(base_action) elif update or preload or close: base_action = LoadUpdateAction( case_type=case_type, case_tag='load_{0}_0'.format(case_type), case_properties=update.update if update else {}, preload=preload.preload if preload else {}, ) if module.parent_select.active: select_chain = get_select_chain(app, module, include_self=False) for n, link in enumerate(reversed(list(enumerate(select_chain)))): i, module = link new_form.actions.load_update_cases.append(LoadUpdateAction( case_type=module.case_type, case_tag='_'.join(['parent'] * (i + 1)), details_module=module.unique_id, case_index=CaseIndex(tag='_'.join(['parent'] * (i + 2)) if n > 0 else ''), )) base_action.case_indices = [CaseIndex(tag='parent')] if close: base_action.close_condition = close.condition new_form.actions.load_update_cases.append(base_action) if subcases: for i, subcase in enumerate(subcases): open_subcase_action = AdvancedOpenCaseAction( case_type=subcase.case_type, case_tag='open_{0}_{1}'.format(subcase.case_type, i + 1), name_path=subcase.case_name, open_condition=subcase.condition, case_properties=subcase.case_properties, repeat_context=subcase.repeat_context, case_indices=[CaseIndex( tag=base_action.case_tag if base_action else '', reference_id=subcase.reference_id, )], ) new_form.actions.open_cases.append(open_subcase_action) new_form.unique_id = form.unique_id forms.append(new_form.to_json()) new_module = module.to_json() new_module['forms'] = forms del new_module['display_style'] del new_module['referral_list'] del new_module['ref_details'] del new_module['task_list'] del new_module['parent_select'] # This is handled in forms for advanced modules new_module = AdvancedModule.wrap(new_module) modules = app.modules mod_index = [i for i, mod in enumerate(modules) if mod.unique_id == module_id][0] modules[mod_index] = new_module app.modules = modules app.save() # update xml app = get_current_app(domain, app_id) module = app.get_module_by_unique_id(module_id) for form in module.forms: real_form = app.get_form(form.unique_id) if form.xmlns in (DUE_LIST_XMLNS, IMMUNIZATION_XMLNS): new_form_source = form.source.replace( "instance('commcaresession')/session/data/case_id", "instance('commcaresession')/session/data/case_id_load_tasks_0") real_form.source = new_form_source elif form.xmlns == ELIGIBLE_COUPLE_XMLNS: new_form_source = form.source.replace( "instance('commcaresession')/session/data/case_id", "instance('commcaresession')/session/data/case_id_load_person_0") real_form.source = new_form_source app.save() copy = app.make_build( comment="{} moved to an advanced module".format(module.name), ) copy.save(increment_version=False)
def get_xmlns_by_app(domain, app_id): app = get_current_app(domain, app_id) return [form.xmlns.split('/')[-1] for form in app.get_forms()]
def pull_master_app(request, domain, app_id): app = get_current_app(domain, app_id) try: master_version = app.get_master_version() except RemoteRequestError: messages.error( request, _('Unable to pull latest master from remote CommCare HQ. Please try again later.' )) return HttpResponseRedirect( reverse_util('app_settings', params={}, args=[domain, app_id])) if master_version > app.version: exception_message = None try: latest_master_build = app.get_latest_master_release() except ActionNotPermitted: exception_message = _( 'This project is not authorized to update from the master application. ' 'Please contact the maintainer of the master app if you believe this is a mistake. ' ) except RemoteAuthError: exception_message = _( 'Authentication failure attempting to pull latest master from remote CommCare HQ.' 'Please verify your authentication details for the remote link are correct.' ) except RemoteRequestError: exception_message = _( 'Unable to pull latest master from remote CommCare HQ. Please try again later.' ) if exception_message: messages.error(request, exception_message) return HttpResponseRedirect( reverse_util('app_settings', params={}, args=[domain, app_id])) report_map = get_static_report_mapping(latest_master_build.domain, app['domain'], {}) try: overwrite_app(app, latest_master_build, report_map) except AppEditingError: messages.error( request, _('This linked application uses dynamic mobile UCRs ' 'which are currently not supported. For this application ' 'to function correctly, you will need to remove those modules ' 'or revert to a previous version that did not include them.') ) return HttpResponseRedirect( reverse_util('app_settings', params={}, args=[domain, app_id])) if app.master_is_remote: try: pull_missing_multimedia_from_remote(app) except RemoteRequestError: messages.error( request, _('Error fetching multimedia from remote server. Please try again later.' )) return HttpResponseRedirect( reverse_util('app_settings', params={}, args=[domain, app_id])) messages.success( request, _('Your linked application was successfully updated to the latest version.' )) return HttpResponseRedirect( reverse_util('app_settings', params={}, args=[domain, app_id]))
def app(self): from corehq.apps.app_manager.dbaccessors import get_current_app return get_current_app(self.domain, self.app_id)
def get_app(self): from corehq.apps.app_manager.dbaccessors import get_current_app app_build_id = self.transifex.app_id_to_build return get_current_app(self.transifex.domain, app_build_id)
def get_app(self): from corehq.apps.app_manager.dbaccessors import get_current_app app_build_id = self.transifex.build_id return get_current_app(self.transifex.domain, app_build_id)
def update_linked_whitelist(request, domain, app_id): app = get_current_app(domain, app_id) new_whitelist = json.loads(request.POST.get('whitelist')) app.linked_whitelist = new_whitelist app.save() return HttpResponse()
def test_get_current_app(self): app_doc = get_current_app(self.domain, self.app_id) self.assertEqual(app_doc["version"], 4)
def test_get_current_app(self): app_doc = get_current_app(self.domain, self.app_id) self.assertEqual(app_doc['version'], 4)