Completed
Branch master (9edffc)
by Jordi
04:36
created

AnalysisRequestAnalysesView.folderitem()   B

Complexity

Conditions 7

Size

Total Lines 72
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 45
dl 0
loc 72
rs 7.4
c 0
b 0
f 0
cc 7
nop 4

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of SENAITE.CORE
4
#
5
# Copyright 2018 by it's authors.
6
# Some rights reserved. See LICENSE.rst, CONTRIBUTORS.rst.
7
8
import collections
9
10
from bika.lims import api
11
from bika.lims import bikaMessageFactory as _
12
from bika.lims.browser.bika_listing import BikaListingView
13
from bika.lims.content.analysisspec import ResultsRangeDict
14
from bika.lims.utils import dicts_to_dict
15
from bika.lims.utils import get_image
16
from bika.lims.utils import get_link
17
from bika.lims.utils import logged_in_client
18
from bika.lims.utils import t
19
from bika.lims.workflow import wasTransitionPerformed
20
from plone.memoize import view
21
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
22
from zope.i18n.locales import locales
23
24
25
class AnalysisRequestAnalysesView(BikaListingView):
26
    """AR Manage Analyses View
27
    """
28
    template = ViewPageTemplateFile("templates/analysisrequest_analyses.pt")
29
30
    def __init__(self, context, request):
31
        super(AnalysisRequestAnalysesView, self).__init__(context, request)
32
33
        self.catalog = "bika_setup_catalog"
34
        self.contentFilter = {
35
            "portal_type": "AnalysisService",
36
            "sort_on": "sortable_title",
37
            "sort_order": "ascending",
38
            "inactive_state": "active"
39
        }
40
        self.context_actions = {}
41
        self.icon = "{}/{}".format(
42
            self.portal_url,
43
            "++resource++bika.lims.images/analysisservice_big.png"
44
        )
45
        self.show_column_toggles = False
46
        self.show_select_column = True
47
        self.show_select_all_checkbox = False
48
        self.pagesize = 999999
49
        self.show_search = True
50
        self.fetch_transitions_on_select = False
51
52
        self.categories = []
53
        self.selected = []
54
        self.do_cats = self.context.bika_setup.getCategoriseAnalysisServices()
55
        if self.do_cats:
56
            self.show_categories = True
57
            self.expand_all_categories = False
58
59
        self.columns = collections.OrderedDict((
60
            ("Title", {
61
                "title": _("Service"),
62
                "index": "sortable_title",
63
                "sortable": False}),
64
            ("Unit", {
65
                "title": _("Unit"),
66
                "sortable": False}),
67
            ("Hidden", {
68
                "title": _("Hidden"),
69
                "sortable": False,
70
                "type": "boolean"}),
71
            ("Price", {
72
                "title": _("Price"),
73
                "sortable": False}),
74
            ("warn_min", {
75
                "title": _("Min warn")}),
76
            ("min", {
77
                "title": _("Min")}),
78
            ("warn_max", {
79
                "title": _("Max warn")}),
80
            ("max", {
81
                "title": _("Max")}),
82
        ))
83
84
        columns = ["Title", "Unit", "Hidden", ]
85
        if self.show_prices():
86
            columns.append("Price")
87
        if self.show_ar_specs():
88
            columns.append("warn_min")
89
            columns.append("min")
90
            columns.append("warn_max")
91
            columns.append("max")
92
93
        self.review_states = [
94
            {
95
                "id": "default",
96
                "title": _("All"),
97
                "contentFilter": {"inactive_state": "active"},
98
                "columns": columns,
99
                "transitions": [{"id": "disallow-all-possible-transitions"}],
100
                "custom_transitions": [
101
                    {
102
                        "id": "save_analyses_button",
103
                        "title": _("Save")
104
                    }
105
                ],
106
            },
107
        ]
108
109
    def update(self):
110
        """Update hook
111
        """
112
        super(AnalysisRequestAnalysesView, self).update()
113
        analyses = self.context.getAnalyses(full_objects=True)
114
        self.analyses = dict([(a.getServiceUID(), a) for a in analyses])
115
        self.selected = self.analyses.keys()
116
117
    @view.memoize
118
    def show_prices(self):
119
        """Checks if prices should be shown or not
120
        """
121
        setup = api.get_setup()
122
        return setup.getShowPrices()
123
124
    @view.memoize
125
    def show_ar_specs(self):
126
        """Checks if AR specs should be shown or not
127
        """
128
        setup = api.get_setup()
129
        return setup.getEnableARSpecs()
130
131
    @view.memoize
132
    def get_results_range(self):
133
        """Get the results Range from the AR
134
        """
135
        spec = self.context.getResultsRange()
136
        if spec:
137
            return dicts_to_dict(spec, "keyword")
138
        return ResultsRangeDict()
139
140
    @view.memoize
141
    def get_currency_symbol(self):
142
        """Get the currency Symbol
143
        """
144
        locale = locales.getLocale('en')
145
        setup = api.get_setup()
146
        currency = setup.getCurrency()
147
        return locale.numbers.currencies[currency].symbol
148
149
    def is_submitted(self, obj):
150
        """Check if the "submit" transition was performed
151
        """
152
        return wasTransitionPerformed(obj, "submit")
153
154
    @view.memoize
155
    def get_logged_in_client(self):
156
        """Return the logged in client
157
        """
158
        return logged_in_client(self.context)
159
160
    def get_editable_columns(self, obj):
161
        """Return editable fields
162
        """
163
        columns = ["min", "max", "warn_min", "warn_max", "Hidden"]
164
        if not self.get_logged_in_client():
165
            columns.append("Price")
166
        return columns
167
168
    def folderitems(self):
169
        """XXX refactor if possible to non-classic mode
170
        """
171
        items = super(AnalysisRequestAnalysesView, self).folderitems()
172
        self.categories.sort()
173
        return items
174
175
    def folderitem(self, obj, item, index):
176
        """Service triggered each time an item is iterated in folderitems.
177
178
        The use of this service prevents the extra-loops in child objects.
179
180
        :obj: the instance of the class to be foldered
181
        :item: dict containing the properties of the object to be used by
182
            the template
183
        :index: current index of the item
184
        """
185
        # ensure we have an object and not a brain
186
        obj = api.get_object(obj)
187
        uid = api.get_uid(obj)
188
189
        # settings for this analysis
190
        service_settings = self.context.getAnalysisServiceSettings(uid)
191
        hidden = service_settings.get("hidden", obj.getHidden())
192
193
        # get the category
194
        category = obj.getCategoryTitle()
195
        item["category"] = category
196
        if category not in self.categories:
197
            self.categories.append(category)
198
199
        keyword = obj.getKeyword()
200
        if uid in self.analyses:
201
            analysis = self.analyses[uid]
202
            # Might differ from the service keyword
203
            keyword = analysis.getKeyword()
204
            # Mark the row as disabled if the analysis is not in an open state
205
            item["disabled"] = not analysis.isOpen()
206
            # get the hidden status of the analysis
207
            hidden = analysis.getHidden()
208
209
        # get the specification of this object
210
        rr = self.get_results_range()
211
        spec = rr.get(keyword, ResultsRangeDict())
212
213
        item["Title"] = obj.Title()
214
        item["Unit"] = obj.getUnit()
215
        item["Price"] = obj.getPrice()
216
        item["before"]["Price"] = self.get_currency_symbol()
217
        item["allow_edit"] = self.get_editable_columns(obj)
218
        item["selected"] = uid in self.selected
219
        item["min"] = str(spec.get("min", ""))
220
        item["max"] = str(spec.get("max", ""))
221
        item["warn_min"] = str(spec.get("warn_min", ""))
222
        item["warn_max"] = str(spec.get("warn_max", ""))
223
        item["Hidden"] = hidden
224
225
        # Append info link before the service
226
        # see: bika.lims.site.coffee for the attached event handler
227
        item["before"]["Title"] = get_link(
228
            "analysisservice_info?service_uid={}".format(uid),
229
            value="<span class='glyphicon glyphicon-info-sign'></span>",
230
            css_class="service_info")
231
232
        # Icons
233
        after_icons = ""
234
        if obj.getAccredited():
235
            after_icons += get_image(
236
                "accredited.png", title=t(_("Accredited")))
237
        if obj.getAttachmentOption() == "r":
238
            after_icons += get_image(
239
                "attach_reqd.png", title=t(_("Attachment required")))
240
        if obj.getAttachmentOption() == "n":
241
            after_icons += get_image(
242
                "attach_no.png", title=t(_('Attachment not permitted')))
243
        if after_icons:
244
            item["after"]["Title"] = after_icons
245
246
        return item
247