def get_context_data(self, **kwargs): context = super(SuppliersView, self).get_context_data(**kwargs) root, trail = self.breadcrumbs update_context_urls(context, { 'api_suppliers': reverse('api_suppliers', args=(self.account, root)), 'api_accessibles': site_prefixed( "/api/profile/%(account)s/plans/%(account)s-report/"\ "subscriptions/" % {'account': self.account}), 'api_organizations': site_prefixed("/api/profile/"), 'api_organization_profile': site_prefixed( "/api/profile/%(account)s/" % {'account': self.account}), 'download': reverse('reporting_organization_download', args=(self.account, root)), 'improvements_download': reverse( 'reporting_organization_improvements_download', args=(self.account, root)) }) try: extra = json.loads(self.account.extra) except (IndexError, TypeError, ValueError) as err: extra = {} start_at = extra.get('start_at', None) context.update({ 'score_toggle': True, 'account_extra': self.account.extra, 'date_range': { 'start_at': start_at, 'ends_at': (datetime_or_now() + relativedelta(days=1) ).isoformat(), } }) return context
def get_context_data(self, **kwargs): context = super(ShareView, self).get_context_data(**kwargs) from_root, trail = self.breadcrumbs # Find supplier managers subscribed to this profile # to share scorecard with. is_account_manager = self.manages(self.account) if is_account_manager: context.update({'is_account_manager': is_account_manager}) context.update({ 'supplier_managers': json.dumps(get_supplier_managers(self.account)) }) update_context_urls( context, { 'api_scorecard_share': reverse('api_scorecard_share', args=(context['organization'], from_root[1:])), 'api_organizations': site_prefixed("/api/profile/"), 'api_viewers': site_prefixed("/api/profile/%s/roles/viewers/" % self.account), }) breadcrumbs = context.get('breadcrumbs', []) if breadcrumbs: context.update({'segment_title': breadcrumbs[0][0].title}) context.update({'sample': self.sample}) return context
def get_context_data(self, **kwargs): #pylint:disable=too-many-locals context = super(BenchmarkView, self).get_context_data(**kwargs) segment_url, segment_prefix, segment_element = self.segment root = None if segment_element: root = self._build_tree(segment_element, segment_prefix, cut=TransparentCut()) # Flatten icons and practices (i.e. Energy Efficiency) to produce # the list of charts. self.decorate_with_breadcrumbs(root) charts = self.get_charts(root, excludes=[segment_element.slug]) organization = kwargs.get('organization') if self.assessment_sample: last_updated_at = self.assessment_sample.created_at.strftime( "%b %Y") update_context_urls( context, { 'scorecard_organization_download': reverse('scorecard_organization_download', args=(organization, self.assessment_sample, segment_url)), 'api_account_benchmark': reverse('api_benchmark', args=(organization, self.assessment_sample, segment_prefix[1:])), 'api_historical_scores': reverse('api_historical_scores', args=(organization, segment_prefix[1:])), }) context.update({'sample': self.assessment_sample}) else: # There are no assessment yet. last_updated_at = "N/A" if organization in self.accessibles( roles=['manager', 'contributor']): if organization != settings.APP_NAME: # /app/:organization/scorecard/:path # Only when accessing an actual scorecard and # if the request user is a manager/contributor # for the organization will we prompt to start # the assessment. context.update({'no_assessment_warning': "You need to complete an <em>Assessment</em> before"\ " moving on to the <em>Scorecard</em>."}) else: context.update({'no_assessment_warning': "This organization has not yet started"\ " their <em>Assessment</em>."}) context.update({ 'charts': charts, 'root': root, 'entries': json.dumps(root, cls=JSONEncoder), 'last_updated_at': last_updated_at, }) return context
def get_context_data(self, **kwargs): context = super(AssessmentView, self).get_context_data(**kwargs) self.get_or_create_assessment_sample() segment_url, segment_prefix, segment_element = self.segment root = self.get_report_tree( load_text=(self.campaign.slug == 'framework')) if root: self.decorate_visible_column_headers(root) context.update({ 'root': root, 'entries': json.dumps(root, cls=JSONEncoder) }) nb_answers = Answer.objects.filter( sample=self.sample, question__default_metric=F('metric_id'), # question__default_metric_id=self.default_metric_id, question__path__startswith=segment_prefix).count() context.update({ 'nb_answers': nb_answers, 'nb_required_answers': self.nb_required_answers, 'nb_questions': self.nb_questions, 'nb_required_questions': self.nb_required_questions, 'page_icon': self.icon, 'sample': self.sample, 'campaign': self.sample.campaign, 'role': "tab", 'score_toggle': self.request.GET.get('toggle', False) }) # Find supplier managers subscribed to this profile # to share scorecard with. if self.manages(self.account): context.update({ 'supplier_managers': json.dumps(get_supplier_managers(self.account)) }) organization = context['organization'] update_context_urls( context, { 'download': reverse('assess_organization_sample_download', args=(organization, self.sample, segment_url)), 'api_assessment_sample': reverse('survey_api_sample', args=(organization, self.sample)), 'api_assessment_freeze': reverse('survey_api_sample_freeze', args=(organization, self.sample, segment_prefix[1:])), 'api_assessment_sample_new': reverse('survey_api_sample_new', args=(organization, )), 'api_scorecard_share': reverse('api_scorecard_share', args=(organization, segment_prefix[1:])), }) return context
def get_context_data(self, **kwargs): context = super(AppView, self).get_context_data(**kwargs) context.update({ 'FEATURES_DEBUG': self.account.pk in get_testing_accounts() }) update_context_urls(context, { 'api_historical_scores': reverse('api_historical_scores', args=(self.account, '')), }) return context
def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context.update({ 'segments': self.get_segments(search_query='public') }) update_context_urls(context, { 'api_enable': reverse('api_enable', args=("",)), 'api_disable': reverse('api_disable', args=("",)), }) return context
def get_context_data(self, **kwargs): context = super(ImprovementView, self).get_context_data(**kwargs) segment_url, segment_prefix, segment_element = self.segment organization = context['organization'] update_context_urls( context, { 'api_improvements': reverse('api_improvement_base', args=(organization, )), 'api_organizations': site_prefixed("/api/profile/"), 'api_viewers': site_prefixed("/api/profile/%s/roles/viewers/" % self.account), }) if self.improvement_sample: update_context_urls( context, { 'print': reverse('improve_organization_sample_print', args=(organization, self.improvement_sample, '/%s' % segment_prefix.split('/')[-1])), 'download': reverse('improve_organization_sample_download', args=(organization, self.improvement_sample, '/%s' % segment_prefix.split('/')[-1])) }) if self.assessment_sample: update_context_urls( context, { 'api_account_benchmark': reverse('api_benchmark', args=(organization, self.assessment_sample, segment_prefix)) }) return context
def get_context_data(self, **kwargs): #pylint:disable=too-many-locals context = super(DetailView, self).get_context_data(**kwargs) from_root, trail = self.breadcrumbs # It is OK here to index by -1 since we would have generated a redirect # in the `get` method when the path is "/". root = self._build_tree(trail[-1][0], from_root) self._report_queries("content tree built.") # Removes framework additional questions and other assessments # questions which are irrelevant when making an improvement plan. to_remove = [] for key, node in six.iteritems(root[1]): tags = node[0].get('tag', "") if tags and 'metrics' in tags: to_remove += [key] for key in to_remove: del root[1][key] # attach visible column headers hidden_columns = {} is_content_manager = context.get('is_content_manager', False) for icon_path, icon_tuple in six.iteritems(root[1]): hidden_columns[icon_path] = {} hidden = set([ row['slug'] for row in ColumnHeader.objects.filter( hidden=True, path=icon_path).values('slug') ]) profitability_headers = [] for col_header in [ {"slug": "avg_energy_saving", "title": "Savings", "tooltip": "The average estimated percentage saved"\ " relative to spend in the area of focus (e.g. site energy, waste) resulting"\ " from the implementation of a best practice.\n***** > 5%\n**** 3-5%\n***"\ " 2-3%\n** 1-2%\n* < 1%\n Click individual best practice"\ " headings and navigate to the \"References\" section for more detail on data"\ " provenance."}, {"slug": "capital_cost", "title": "Cost", "tooltip": "The average estimated percentage of cost"\ " relative to spend in the area of focus (e.g. site energy, waste) to"\ " implement a best practice.\n$$$$$ < 10%\n$$$$ 5-10%\n$$$ 2-5%\n$$"\ " 1-2%\n$ < 1%\nClick individual best practice headings and"\ " navigate to the \"References\" section for more detail on data provenance."}, {"slug": "payback_period", "title": "Payback years", "tooltip": "Range: The range of payback values are"\ " calculated for a best practice implemented at a facility by the following"\ " formula: Simple Year-of-Payback = (Implementation Cost) / (Total Energy"\ " Cost Savings)\n\nAverage (in parentheses): The average represents an"\ " average of the totals represented by the range.\n\nClick individual best"\ " practice headings and navigate to the \"References\" section for more"\ " detail on data provenance."}]: if is_content_manager: profitability_headers += [col_header] hidden_columns[icon_path][col_header['slug']] = ( col_header['slug'] in hidden) elif not col_header['slug'] in hidden: profitability_headers += [col_header] icon_tuple[0]['profitability_headers'] = profitability_headers icon_tuple[0]['profitability_headers_len'] = len( profitability_headers) + 1 value_headers = [] for col_header in [{ "slug": "environmental_value", "title": "/static/img/green-leaf.png", "tooltip": "Environmental value" }, { "slug": "business_value", "title": "/static/img/cogs.png", "tooltip": "Ops/Maintenance value" }, { "slug": "profitability", "title": "/static/img/dollar-sign.png", "tooltip": "Financial value" }, { "slug": "implementation_ease", "title": "/static/img/shovel.png", "tooltip": "Implementation ease" }, { "slug": "avg_value", "title": "Average Value" }]: if is_content_manager: value_headers += [col_header] hidden_columns[icon_path][col_header['slug']] = ( col_header['slug'] in hidden) elif not col_header['slug'] in hidden: value_headers += [col_header] icon_tuple[0]['value_headers'] = value_headers icon_tuple[0]['value_headers_len'] = len(value_headers) + 2 icon_tuple[0]['colspan'] = max( icon_tuple[0]['profitability_headers_len'], icon_tuple[0]['value_headers_len']) self._report_queries("attached visiblity of columns.") if not is_content_manager: context.update({'sort_by': "{'agv_value': 'desc'}"}) context.update({ 'role': "tab", 'root': root, 'entries': json.dumps(root), 'hidden': json.dumps(hidden_columns) }) segment_url, segment_prefix, segment_element = self.segment update_context_urls( context, { 'summary_download': reverse('summary_download', args=(segment_url, )), }) return context
def get_context_data(self, **kwargs): context = super(BreadcrumbMixin, self).get_context_data(**kwargs) from_root, trail = self.breadcrumbs parts = from_root.split('/') root_prefix = '/'.join(parts[:-1]) if len(parts) > 1 else "" path = kwargs.get('path', "") context.update({ 'path': path, 'root_prefix': root_prefix, 'breadcrumbs': trail, 'active': self.request.GET.get('active', "")}) urls = { 'api_scorecard_disable': reverse( 'api_scorecard_disable', args=("/",)), 'api_scorecard_enable': reverse( 'api_scorecard_enable', args=("/",)), 'api_best_practices': reverse('api_detail', args=("",)), 'api_mirror_node': reverse('api_mirror_node', args=("",)), 'api_move_node': reverse('api_move_node', args=("",)), 'api_columns': reverse('api_column', args=("",)), 'api_consumptions': reverse('api_consumption_base'), 'api_weights': reverse('api_score', kwargs={'path': ''}), 'api_page_element_base': reverse('api_page_element', kwargs={'path':""}), 'api_page_element_search': reverse('api_page_element_search'), 'best_practice_base': self.get_breadcrumb_url( path) } active_section = "" if self.request.GET.get('active', ""): active_section += "?active=%s" % self.request.GET.get('active') hide_summary = True hide_improve = False hide_scorecard = False hide_targets = True if trail and trail[0]: #hide_summary = bool(trail[0][0].tag and # 'hide-summary' in trail[0][0].tag) hide_improve = bool(trail[0][0].tag and 'hide-improve' in trail[0][0].tag) hide_scorecard = bool(trail[0][0].tag and 'hide-scorecard' in trail[0][0].tag) if RelationShip.objects.filter( orig_element__slug=trail[0][0].slug, dest_element__slug='targets').exists(): hide_targets = False organization = kwargs.get('organization') url_path, prefix, element = self.segment if element: # XXX Because this code is called on the app page url_path = '/%s' % url_path.split('/')[-2] else: url_path = '' if organization: sample = kwargs.get('sample') summary_url = reverse('summary_organization_redirect', args=(organization, path)) improve_url = reverse('improve_organization_redirect', args=(organization, path)) if not hide_summary: urls.update({ 'summary': summary_url, }) if sample: urls.update({ 'assess': reverse('assess_organization', args=(organization, sample, url_path)), 'complete': reverse('complete_organization', args=(organization, sample, url_path)), 'share': reverse('share_organization', args=(organization, sample, url_path)), }) if not hide_improve: urls.update({ 'improve': reverse('improve_organization', args=(organization, sample, url_path)), }) if not hide_targets: urls.update({ 'targets': reverse('assess_organization', args=(organization, sample, '%s/targets' % url_path)), }) if not hide_scorecard: urls.update({ 'scorecard': reverse('scorecard_organization', args=(organization, sample, url_path)), }) else: urls.update({ 'assess': reverse('assess_organization_redirect', args=(organization, path)), 'complete': reverse('complete_organization_redirect', args=(organization, url_path)), 'share': reverse('share_organization_redirect', args=(organization, url_path)), }) if not hide_improve: urls.update({ 'improve': improve_url, 'api_improvements': reverse('api_improvement_base', args=(organization,)), }) if not hide_targets: urls.update({ 'targets': reverse('assess_organization_redirect', args=(organization, '%s/targets' % url_path)), }) if not hide_scorecard: urls.update({ 'scorecard': reverse('scorecard_organization_redirect', args=(organization, url_path)), }) else: summary_url = reverse('summary', args=(path,)) improve_url = reverse('improve_redirect', args=(path,)) urls.update({ 'assess': reverse('assess_redirect', args=(url_path,)), 'complete': reverse('complete_redirect', args=(url_path,)), 'share': reverse('share_redirect', args=(url_path,)), }) if not hide_summary: urls.update({ 'summary': summary_url, }) if not hide_improve: urls.update({ 'improve': improve_url, }) if not hide_scorecard: urls.update({ 'scorecard': reverse( 'scorecard_redirect', args=(url_path,)), }) if self.__class__.__name__ == 'DetailView': urls.update({'context_base': summary_url}) elif self.__class__.__name__ == 'ImprovementView': urls.update({'context_base': improve_url}) elif self.__class__.__name__ == 'AssessmentView': urls.update({'context_base': urls['assess']}) elif self.__class__.__name__ == 'ShareView': urls.update({'context_base': urls['share']}) update_context_urls(context, urls) return context
def get_context_data(self, **kwargs): context = super( BestPracticeMixin, self).get_context_data(**kwargs) breadcrumbs = context.get('breadcrumbs', []) if breadcrumbs: context.update({ 'is_content_manager': self.manages( breadcrumbs[-1][0].account.slug)}) if not self.best_practice: return context context.update({ 'icon': self.icon, 'best_practice': self.best_practice}) aliases = self.best_practice.get_parent_paths() if len(aliases) > 1: alias_breadcrumbs = [] for alias in aliases: if alias and len(alias) > 4: alias_breadcrumbs += [[alias[0], "..."] + alias[-3:-1]] elif alias and len(alias) > 1: alias_breadcrumbs += [alias[:-1]] else: # XXX This is probably an error in `get_parent_paths` alias_breadcrumbs += [[alias]] context.update({'aliases': alias_breadcrumbs}) organization = self.kwargs.get('organization', None) if organization: context.update({'organization': organization}) votes_score = self.best_practice.votes.all().aggregate( sum_votes=Sum('vote')).get('sum_votes', 0) if votes_score is None: votes_score = 0 context.update({ 'nb_followers': self.best_practice.followers.all().count(), 'votes_score': votes_score }) if self.request.user.is_authenticated: context.update({ 'is_following': self.best_practice.followers.filter( user=self.request.user).exists(), 'is_voted': self.best_practice.votes.filter( user=self.request.user).exists() }) # Change defaults contextual URL to move back up one level. _, trail = self.breadcrumbs contextual_path = ( trail[-2][1] if len(trail) > 1 else self.kwargs.get('path', "")) parts = contextual_path.split('#') contextual_path = parts[0] if len(parts) > 1: active_section = "?active=%s" % parts[1] else: active_section = "" if organization: urls = { 'assess': reverse('assess_organization_redirect', args=(organization, contextual_path)) + active_section, 'improve': reverse('improve_organization_redirect', args=(organization, contextual_path)) + active_section } else: urls = { 'assess': reverse('assess_redirect', args=(contextual_path,)) + active_section, 'improve': reverse('improve_redirect', args=(contextual_path,)) + active_section } # XXX should `api_detail` be replaced by `api_page_element`? urls.update({'api_page_element_base': reverse('api_detail', args=( context['root_prefix'],)), }) update_context_urls(context, urls) return context
def get_context_data(self, **kwargs): context = super(AssessmentView, self).get_context_data(**kwargs) self.get_or_create_assessment_sample() segment_url, segment_prefix, segment_element = self.segment root = self.get_report_tree( load_text=(self.survey.slug == 'framework')) if root: self.decorate_visible_column_headers(root) context.update({ 'root': root, 'entries': json.dumps(root, cls=JSONEncoder) }) prev_samples = [(reverse('assess_organization', args=(self.account, prev_sample, self.kwargs.get('path'))), prev_sample.created_at) for prev_sample in Sample.objects.filter( is_frozen=True, extra__isnull=True, survey=self.survey, account=self.account).order_by('-created_at')] if prev_samples: context.update({'prev_samples': prev_samples}) if self.sample.is_frozen: selected_sample = reverse('assess_organization', args=(self.account, self.sample, self.kwargs.get('path'))) context.update({'selected_sample': selected_sample}) nb_questions = Consumption.objects.filter( path__startswith=segment_prefix).count() nb_required_questions = Consumption.objects.filter( path__startswith=segment_prefix, default_metric_id=self.default_metric_id).count() nb_answers = Answer.objects.filter( sample=self.sample, question__default_metric=F('metric_id'), # question__default_metric_id=self.default_metric_id, question__path__startswith=segment_prefix).count() nb_required_answers = Answer.objects.filter( sample=self.sample, question__default_metric=F('metric_id'), question__default_metric_id=self.default_metric_id, question__path__startswith=segment_prefix).count() context.update({ 'nb_answers': nb_answers, 'nb_required_answers': nb_required_answers, 'nb_questions': nb_questions, 'nb_required_questions': nb_required_questions, 'page_icon': self.icon, 'sample': self.sample, 'survey': self.sample.survey, 'role': "tab", 'score_toggle': self.request.GET.get('toggle', False) }) # Find supplier managers subscribed to this profile # to share scorecard with. if self.manages(self.account): context.update({ 'supplier_managers': json.dumps(get_supplier_managers(self.account)) }) organization = context['organization'] update_context_urls( context, { 'download': reverse('assess_organization_sample_download', args=(organization, self.sample, segment_prefix)), 'api_assessment_sample': reverse('survey_api_sample', args=(organization, self.sample)), 'api_assessment_freeze': reverse('survey_api_sample_freeze', args=(organization, self.sample, segment_prefix)), 'api_assessment_sample_new': reverse('survey_api_sample_new', args=(organization, )), 'api_scorecard_share': reverse('api_scorecard_share', args=(organization, segment_prefix)), }) return context