Passed
Push — 2.x ( 6f26c4...6cbbfb )
by Jordi
05:32
created

bika.lims.browser   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 210
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 36
eloc 125
dl 0
loc 210
rs 9.52
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A ulocalized_time() 0 38 5

19 Methods

Rating   Name   Duplication   Size   Complexity  
A BrowserView.portal_url() 0 3 1
A BrowserView.portal() 0 3 1
A BrowserView.__init__() 0 4 1
A BrowserView.reference_catalog() 0 3 1
A BrowserView.senaite_catalog_setup() 0 3 1
A BrowserView.checkPermission() 0 3 1
A BrowserView.senaite_catalog_analysis() 0 3 1
A BrowserView.user_email() 0 9 3
A BrowserView.senaite_catalog() 0 3 1
A BrowserView.portal_catalog() 0 3 1
B BrowserView.python_date_format() 0 27 6
A BrowserView.user_fullname() 0 9 3
A BrowserView.date_format_short() 0 6 2
A BrowserView.date_format_long() 0 6 2
A BrowserView.portal_workflow() 0 3 1
A BrowserView.ulocalized_time() 0 3 1
A BrowserView.time_format() 0 6 2
A BrowserView.portal_groups() 0 3 1
A BrowserView.portal_membership() 0 3 1
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-2021 by it's authors.
19
# Some rights reserved, see README and LICENSE.
20
21
import traceback
22
23
from AccessControl import ClassSecurityInfo
24
from bika.lims import api
25
from bika.lims import logger
26
from DateTime.DateTime import DateTime
27
from Products.CMFCore.utils import getToolByName
28
from Products.CMFPlone.i18nl10n import ulocalized_time as _ut
29
from Products.Five.browser import BrowserView as BaseBrowserView
30
from zope.cachedescriptors.property import Lazy as lazy_property
31
from zope.i18n import translate
32
33
34
def ulocalized_time(time, long_format=None, time_only=None, context=None,
35
                    request=None):
36
    """
37
    This function gets ans string as time or a DateTime objects and returns a
38
    string with the time formatted
39
40
    :param time: The time to process
41
    :type time: str/DateTime
42
    :param long_format:  If True, return time in ling format
43
    :type portal_type: boolean/null
44
    :param time_only: If True, only returns time.
45
    :type title: boolean/null
46
    :param context: The current context
47
    :type context: ATContentType
48
    :param request: The current request
49
    :type request: HTTPRequest object
50
    :returns: The formatted date as string
51
    :rtype: string
52
    """
53
    # if time is a string, we'll try pass it through strptime with the various
54
    # formats defined.
55
    time = api.to_date(time)
56
    if not time or not isinstance(time, DateTime):
57
        return ''
58
59
    # no printing times if they were not specified in inputs
60
    if time.second() + time.minute() + time.hour() == 0:
61
        long_format = False
62
    try:
63
        time_str = _ut(time, long_format, time_only, context, 'senaite.core', request)
64
    except ValueError:
65
        err_msg = traceback.format_exc() + '\n'
66
        logger.warn(
67
            err_msg + '\n' +
68
            "Error converting '{}' time to string in {}."
69
            .format(time, context))
70
        time_str = ''
71
    return time_str
72
73
74
class BrowserView(BaseBrowserView):
75
    security = ClassSecurityInfo()
76
77
    logger = logger
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable logger does not seem to be defined.
Loading history...
78
79
    def __init__(self, context, request):
80
        self.context = context
81
        self.request = request
82
        super(BrowserView, self).__init__(context, request)
83
84
    security.declarePublic('ulocalized_time')
85
86
    def ulocalized_time(self, time, long_format=None, time_only=None):
87
        return ulocalized_time(time, long_format, time_only,
88
                               context=self.context, request=self.request)
89
90
    @lazy_property
91
    def portal(self):
92
        return getToolByName(self.context, 'portal_url').getPortalObject()
93
94
    @lazy_property
95
    def portal_url(self):
96
        return self.portal.absolute_url().split("?")[0]
97
98
    @lazy_property
99
    def portal_catalog(self):
100
        return getToolByName(self.context, 'portal_catalog')
101
102
    @lazy_property
103
    def reference_catalog(self):
104
        return getToolByName(self.context, 'reference_catalog')
105
106
    @lazy_property
107
    def senaite_catalog_analysis(self):
108
        return getToolByName(self.context, 'senaite_catalog_analysis')
109
110
    @lazy_property
111
    def senaite_catalog_setup(self):
112
        return getToolByName(self.context, 'senaite_catalog_setup')
113
114
    @lazy_property
115
    def senaite_catalog(self):
116
        return getToolByName(self.context, 'senaite_catalog')
117
118
    @lazy_property
119
    def portal_membership(self):
120
        return getToolByName(self.context, 'portal_membership')
121
122
    @lazy_property
123
    def portal_groups(self):
124
        return getToolByName(self.context, 'portal_groups')
125
126
    @lazy_property
127
    def portal_workflow(self):
128
        return getToolByName(self.context, 'portal_workflow')
129
130
    @lazy_property
131
    def checkPermission(self, perm, obj):
132
        return self.portal_membership.checkPermission(perm, obj)
133
134
    # TODO: user_fullname is deprecated and will be removed in Bika LIMS 3.3.
135
    # Use bika.utils.user_fullnameinstead
136
    # I was having a problem trying to import the function from bika.lims.utils
137
    # so i copied the code here.
138
    def user_fullname(self, userid):
139
        member = self.portal_membership.getMemberById(userid)
140
        if member is None:
141
            return userid
142
        member_fullname = member.getProperty('fullname')
143
        portal_catalog = getToolByName(self, 'portal_catalog')
144
        c = portal_catalog(portal_type='Contact', getUsername=userid)
145
        contact_fullname = c[0].getObject().getFullname() if c else None
146
        return contact_fullname or member_fullname or userid
147
148
    # TODO: user_fullname is deprecated and will be removed in Bika LIMS 3.3.
149
    # Use bika.utils.user_fullnameinstead.
150
    # I was having a problem trying to import the function from bika.lims.utils
151
    # so i copied the code here.
152
    def user_email(self, userid):
153
        member = self.portal_membership.getMemberById(userid)
154
        if member is None:
155
            return userid
156
        member_email = member.getProperty('email')
157
        portal_catalog = getToolByName(self, 'portal_catalog')
158
        c = portal_catalog(portal_type='Contact', getUsername=userid)
159
        contact_email = c[0].getObject().getEmailAddress() if c else None
160
        return contact_email or member_email or ''
161
162
    def python_date_format(self, long_format=None, time_only=False):
163
        """This convert bika domain date format msgstrs to Python
164
        strftime format strings, by the same rules as ulocalized_time.
165
        XXX i18nl10n.py may change, and that is where this code is taken from.
166
        """
167
        # get msgid
168
        msgid = long_format and 'date_format_long' or 'date_format_short'
169
        if time_only:
170
            msgid = 'time_format'
171
        # get the formatstring
172
        formatstring = translate(msgid, domain="senaite.core",
173
                                 context=self.request)
174
175
        if formatstring is None or formatstring.startswith(
176
                'date_') or formatstring.startswith('time_'):
177
            self.logger.error("bika/%s/%s could not be translated" %
178
                              (self.request.get('LANGUAGE'), msgid))
179
            # msg catalog was not able to translate this msgids
180
            # use default setting
181
            if long_format:
182
                key = "Products.CMFPlone.i18nl10n.override_dateformat.date_format_long"
183
                format = api.get_registry_record(key)
184
            else:
185
                key = "Products.CMFPlone.i18nl10n.override_dateformat.time_format"
186
                format = api.get_registry_record(key)
187
            return format
188
        return formatstring.replace(r"${", '%').replace('}', '')
189
190
    @lazy_property
191
    def date_format_long(self):
192
        fmt = self.python_date_format(long_format=1)
193
        if fmt == "date_format_long":
194
            fmt = "%Y-%m-%d %I:%M %p"
195
        return fmt
196
197
    @lazy_property
198
    def date_format_short(self):
199
        fmt = self.python_date_format()
200
        if fmt == "date_format_short":
201
            fmt = "%Y-%m-%d"
202
        return fmt
203
204
    @lazy_property
205
    def time_format(self):
206
        fmt = self.python_date_format(time_only=True)
207
        if fmt == "time_format":
208
            fmt = "%I:%M %p"
209
        return fmt
210