Passed
Push — master ( 70be41...e1228c )
by Ramon
11:12
created

bika.lims.browser.clientfolder.ajaxGetClients.__call__()   B

Complexity

Conditions 6

Size

Total Lines 52
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 39
dl 0
loc 52
rs 8.0106
c 0
b 0
f 0
cc 6
nop 1

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
# SENAITE.CORE is free software: you can redistribute it and/or modify it under
6
# the terms of the GNU General Public License as published by the Free Software
7
# Foundation, version 2.
8
#
9
# This program is distributed in the hope that it will be useful, but WITHOUT
10
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
12
# details.
13
#
14
# You should have received a copy of the GNU General Public License along with
15
# this program; if not, write to the Free Software Foundation, Inc., 51
16
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
#
18
# Copyright 2018-2019 by it's authors.
19
# Some rights reserved, see README and LICENSE.
20
21
import collections
22
23
from Products.CMFCore.permissions import ModifyPortalContent
24
from plone.app.content.browser.interfaces import IFolderContentsView
25
from zope.interface import implements
26
27
from bika.lims import bikaMessageFactory as _
28
from bika.lims.browser.bika_listing import BikaListingView
29
from bika.lims.permissions import AddClient
30
from bika.lims.permissions import ManageAnalysisRequests
31
from bika.lims.utils import check_permission
32
from bika.lims.utils import get_email_link
33
from bika.lims.utils import get_link
34
from bika.lims.utils import get_registry_value
35
36
37
class ClientFolderContentsView(BikaListingView):
38
    """Listing view for all Clients
39
    """
40
    implements(IFolderContentsView)
41
42
    _LANDING_PAGE_REGISTRY_KEY = "bika.lims.client.default_landing_page"
43
    _DEFAULT_LANDING_PAGE = "analysisrequests"
44
45
    def __init__(self, context, request):
46
        super(ClientFolderContentsView, self).__init__(context, request)
47
48
        self.title = self.context.translate(_("Clients"))
49
        self.description = ""
50
        self.form_id = "list_clientsfolder"
51
        self.sort_on = "sortable_title"
52
        # Landing page to be added to the link of each client from the list
53
        self.landing_page = get_registry_value(
54
            self._LANDING_PAGE_REGISTRY_KEY, self._DEFAULT_LANDING_PAGE)
55
56
        self.contentFilter = {
57
            "portal_type": "Client",
58
            "sort_on": "sortable_title",
59
            "sort_order": "ascending"
60
        }
61
62
63
        self.show_select_row = False
64
        self.show_select_all_checkbox = False
65
        self.show_select_column = False
66
        self.pagesize = 25
67
        self.icon = "{}/{}".format(
68
            self.portal_url, "++resource++bika.lims.images/client_big.png")
69
        request.set("disable_border", 1)
70
71
        self.columns = collections.OrderedDict((
72
            ("title", {
73
                "title": _("Name"),
74
                "index": "sortable_title"},),
75
            ("getClientID", {
76
                "title": _("Client ID")}),
77
            ("EmailAddress", {
78
                "title": _("Email Address"),
79
                "sortable": False}),
80
            ("getCountry", {
81
                "toggle": False,
82
                "sortable": False,
83
                "title": _("Country")}),
84
            ("getProvince", {
85
                "toggle": False,
86
                "sortable": False,
87
                "title": _("Province")}),
88
            ("getDistrict", {
89
                "toggle": False,
90
                "sortable": False,
91
                "title": _("District")}),
92
            ("Phone", {
93
                "title": _("Phone"),
94
                "sortable": False}),
95
            ("Fax", {
96
                "toggle": False,
97
                "sortable": False,
98
                "title": _("Fax")}),
99
            ("BulkDiscount", {
100
                "toggle": False,
101
                "sortable": False,
102
                "title": _("Bulk Discount")}),
103
            ("MemberDiscountApplies", {
104
                "toggle": False,
105
                "sortable": False,
106
                "title": _("Member Discount")}),
107
        ))
108
109
        self.review_states = [
110
            {
111
                "id": "default",
112
                "contentFilter": {"review_state": "active"},
113
                "title": _("Active"),
114
                "transitions": [{"id": "deactivate"}, ],
115
                "columns": self.columns.keys(),
116
            }, {
117
                "id": "inactive",
118
                "title": _("Inactive"),
119
                "contentFilter": {"review_state": "inactive"},
120
                "transitions": [{"id": "activate"}, ],
121
                "columns": self.columns.keys(),
122
            }, {
123
                "id": "all",
124
                "title": _("All"),
125
                "contentFilter": {},
126
                "transitions": [],
127
                "columns": self.columns.keys(),
128
            },
129
        ]
130
131
    def before_render(self):
132
        """Before template render hook
133
        """
134
        # Call `before_render` from the base class
135
        super(ClientFolderContentsView, self).before_render()
136
137
        # Render the Add button if the user has the AddClient permission
138
        if check_permission(AddClient, self.context):
139
            self.context_actions[_("Add")] = {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable _ does not seem to be defined.
Loading history...
140
                "url": "createObject?type_name=Client",
141
                "icon": "++resource++bika.lims.images/add.png"
142
            }
143
144
        # Display a checkbox next to each client in the list if the user has
145
        # rights for ModifyPortalContent
146
        self.show_select_column = check_permission(ModifyPortalContent,
147
                                                   self.context)
148
149
    def isItemAllowed(self, obj):
150
        """Returns true if the current user has Manage AR rights for the
151
        current Client (item) to be rendered.
152
153
        :param obj: client to be rendered as a row in the list
154
        :type obj: ATContentType/DexterityContentType
155
        :return: True if the current user can see this Client. Otherwise, False.
156
        :rtype: bool
157
        """
158
        return check_permission(ManageAnalysisRequests, obj)
159
160
    def folderitem(self, obj, item, index):
161
        """Applies new properties to the item (Client) that is currently being
162
        rendered as a row in the list
163
164
        :param obj: client to be rendered as a row in the list
165
        :param item: dict representation of the client, suitable for the list
166
        :param index: current position of the item within the list
167
        :type obj: ATContentType/DexterityContentType
168
        :type item: dict
169
        :type index: int
170
        :return: the dict representation of the item
171
        :rtype: dict
172
        """
173
        # render a link to the defined start page
174
        link_url = "{}/{}".format(item["url"], self.landing_page)
175
        item["replace"]["title"] = get_link(link_url, item["title"])
176
        item["replace"]["getClientID"] = get_link(link_url, item["getClientID"])
177
        # render an email link
178
        item["replace"]["EmailAddress"] = get_email_link(item["EmailAddress"])
179
        # translate True/FALSE values
180
        item["replace"]["BulkDiscount"] = obj.getBulkDiscount() and _("Yes") or _("No")
181
        item["replace"]["MemberDiscountApplies"] = obj.getMemberDiscountApplies() and _("Yes") or _("No")
182
        # render a phone link
183
        phone = obj.getPhone()
184
        if phone:
185
            item["replace"]["Phone"] = get_link("tel:{}".format(phone), phone)
186
187
        return item
188
189
190
def client_match(client, search_term):
191
    # Check if the search_term matches some common fields
192
    if search_term in client.getClientID().lower():
193
        return True
194
    if search_term in client.Title().lower():
195
        return True
196
    if search_term in client.getName().lower():
197
        return True
198
    if search_term in client.Description().lower():
199
        return True
200
    return False
201