Passed
Push — master ( 6d6a8c...6374c8 )
by Ramon
05:17
created

BatchFolderContentsView.__call__()   A

Complexity

Conditions 4

Size

Total Lines 10
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 10
rs 9.95
c 0
b 0
f 0
cc 4
nop 1
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 json
9
from operator import itemgetter
10
11
import plone
12
from bika.lims import api
13
from bika.lims import bikaMessageFactory as _
14
from bika.lims.browser import BrowserView
15
from bika.lims.browser.bika_listing import BikaListingView
16
from bika.lims.permissions import AddBatch
17
18
19
class BatchFolderContentsView(BikaListingView):
20
21
    def __init__(self, context, request):
22
        super(BatchFolderContentsView, self).__init__(context, request)
23
        self.catalog = 'bika_catalog'
24
        self.contentFilter = {
25
            'portal_type': 'Batch',
26
            'sort_on': 'created',
27
            'sort_order': 'reverse',
28
            'cancellation_state': 'active'
29
        }
30
        self.context_actions = {}
31
        self.icon = self.portal_url + "/++resource++bika.lims.images/batch_big.png"
32
        self.title = self.context.translate(_("Batches"))
33
        self.description = ""
34
35
        self.show_select_row = False
36
        self.show_select_all_checkbox = False
37
        self.show_select_column = True
38
        self.pagesize = 25
39
40
        self.columns = {
41
            'Title': {'title': _('Title'),
42
                      'index': 'title'},
43
            'BatchID': {'title': _('Batch ID'),
44
                        'index': 'getId'},
45
            'Description': {'title': _('Description'), 'sortable': False},
46
            'BatchDate': {'title': _('Date')},
47
            'Client': {'title': _('Client'),
48
                       'index': 'getClientTitle'},
49
            'state_title': {'title': _('State'), 'sortable': False},
50
            'created': {'title': _('Created'), },
51
        }
52
53
        self.review_states = [  # leave these titles and ids alone
54
            {'id': 'default',
55
             'contentFilter': {'review_state': 'open'},
56
             'title': _('Open'),
57
             'transitions': [{'id': 'close'}, {'id': 'cancel'}],
58
             'columns': ['Title',
59
                         'BatchID',
60
                         'BatchDate',
61
                         'Client',
62
                         'Description',
63
                         'state_title', ]
64
             },
65
            {'id': 'closed',
66
             'contentFilter': {'review_state': 'closed'},
67
             'title': _('Closed'),
68
             'transitions': [{'id': 'open'}],
69
             'columns': ['Title',
70
                         'BatchID',
71
                         'BatchDate',
72
                         'Client',
73
                         'Description',
74
                         'state_title', ]
75
             },
76
            {'id': 'cancelled',
77
             'title': _('Cancelled'),
78
             'transitions': [{'id': 'reinstate'}],
79
             'contentFilter': {'cancellation_state': 'cancelled'},
80
             'columns': ['Title',
81
                         'BatchID',
82
                         'BatchDate',
83
                         'Client',
84
                         'Description',
85
                         'state_title', ]
86
             },
87
            {'id': 'all',
88
             'title': _('All'),
89
             'transitions': [],
90
             'columns': ['Title',
91
                         'BatchID',
92
                         'BatchDate',
93
                         'Client',
94
                         'Description',
95
                         'state_title', ]
96
             },
97
        ]
98
99
    def __call__(self):
100
        if self.context.absolute_url() == self.portal.batches.absolute_url():
101
            # in contexts other than /batches, we do want to show the edit border
102
            self.request.set('disable_border', 1)
103
        if self.context.absolute_url() == self.portal.batches.absolute_url() \
104
        and self.portal_membership.checkPermission(AddBatch, self.portal.batches):
105
            self.context_actions[_('Add')] = \
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable _ does not seem to be defined.
Loading history...
106
                {'url': 'createObject?type_name=Batch',
107
                 'icon': self.portal.absolute_url() + '/++resource++bika.lims.images/add.png'}
108
        return super(BatchFolderContentsView, self).__call__()
109
110
111
    def folderitem(self, obj, item, index):
112
        """Applies new properties to the item (Batch) that is currently being
113
        rendered as a row in the list
114
        :param obj: client to be rendered as a row in the list
115
        :param item: dict representation of the batch, suitable for the list
116
        :param index: current position of the item within the list
117
        :type obj: ATContentType/DexterityContentType
118
        :type item: dict
119
        :type index: int
120
        :return: the dict representation of the item
121
        :rtype: dict
122
        """
123
        # TODO This can be done entirely by using brains
124
        full_obj = api.get_object(obj)
125
        bid = full_obj.getId()
126
        item['BatchID'] = bid
127
        item['replace']['BatchID'] = "<a href='%s/%s'>%s</a>" % (
128
            item['url'], 'analysisrequests', bid)
129
130
        title = full_obj.Title()
131
        item['Title'] = title
132
        item['replace']['Title'] = "<a href='%s/%s'>%s</a>" % (
133
            item['url'], 'analysisrequests', title)
134
        item['Client'] = ''
135
        client = full_obj.getClient()
136
        if client:
137
            item['Client'] = client.Title()
138
            item['replace']['Client'] = "<a href='%s'>%s</a>" % (
139
                client.absolute_url(), client.Title())
140
141
        # TODO This workaround is necessary?
142
        date = full_obj.Schema().getField('BatchDate').get(obj)
143
        if callable(date):
144
            date = date()
145
        item['BatchDate'] = date
146
        item['replace']['BatchDate'] = self.ulocalized_time(date)
147
        return item
148
149
150
class ajaxGetBatches(BrowserView):
151
152
    """ Vocabulary source for jquery combo dropdown box
153
    """
154
155
    def __call__(self):
156
        plone.protect.CheckAuthenticator(self.request)
157
        searchTerm = self.request['searchTerm'].lower()
158
        page = self.request['page']
159
        nr_rows = self.request['rows']
160
        sord = self.request['sord']
161
        sidx = self.request['sidx']
162
163
        rows = []
164
165
        batches = self.bika_catalog(portal_type='Batch')
166
167
        for batch in batches:
168
            batch = batch.getObject()
169
            if self.portal_workflow.getInfoFor(batch, 'review_state', 'open') != 'open' \
170
               or self.portal_workflow.getInfoFor(batch, 'cancellation_state') == 'cancelled':
171
                continue
172
            if batch.Title().lower().find(searchTerm) > -1 \
173
            or batch.Description().lower().find(searchTerm) > -1:
174
                rows.append({'BatchID': batch.getBatchID(),
175
                             'Description': batch.Description(),
176
                             'BatchUID': batch.UID()})
177
178
        rows = sorted(rows, cmp=lambda x, y: cmp(x.lower(), y.lower()), key=itemgetter(sidx and sidx or 'BatchID'))
179
        if sord == 'desc':
180
            rows.reverse()
181
        pages = len(rows) / int(nr_rows)
182
        pages += divmod(len(rows), int(nr_rows))[1] and 1 or 0
183
        ret = {'page': page,
184
               'total': pages,
185
               'records': len(rows),
186
               'rows': rows[(int(page) - 1) * int(nr_rows): int(page) * int(nr_rows)]}
187
188
        return json.dumps(ret)
189