-
-
Notifications
You must be signed in to change notification settings - Fork 152
/
Copy path__init__.py
562 lines (433 loc) · 19.6 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
# -*- coding:utf-8 -*-
# This file is part of Bika LIMS
#
# Copyright 2011-2016 by it's authors.
# Some rights reserved. See LICENSE.txt, AUTHORS.txt.
from Acquisition import aq_get
from bika.lims import bikaMessageFactory as _
from bika.lims.utils import t
from bika.lims.interfaces import IDisplayListVocabulary, ICustomPubPref
from bika.lims.utils import to_utf8
from Products.Archetypes.public import DisplayList
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from pkg_resources import resource_filename
from plone.resource.utils import iterDirectoriesOfType
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import SimpleTerm
from zope.schema.vocabulary import SimpleVocabulary
from zope.component import getAdapters
from zope.site.hooks import getSite
import os
import glob
class CatalogVocabulary(object):
"""Make vocabulary from catalog query.
"""
implements(IDisplayListVocabulary)
catalog = 'portal_catalog'
contentFilter = {}
key = 'UID'
value = 'Title'
def __init__(self, context, key=None, value=None, contentFilter=None):
self.context = context
self.key = key if key else self.key
self.value = value if value else self.value
self.contentFilter = \
contentFilter if contentFilter else self.contentFilter
def __call__(self, **kwargs):
site = getSite()
request = aq_get(site, 'REQUEST', None)
catalog = getToolByName(site, self.catalog)
allow_blank = False
if 'allow_blank' in kwargs:
allow_blank = kwargs.get('allow_blank')
del (kwargs['allow_blank'])
self.contentFilter.update(**kwargs)
# If a secondary deactivation/cancellation workflow is anbled,
# Be sure and select only active objects, unless other instructions
# are explicitly specified:
wf = getToolByName(site, 'portal_workflow')
if 'portal_type' in self.contentFilter:
portal_type = self.contentFilter['portal_type']
wf_ids = [x.id for x in wf.getWorkflowsFor(portal_type)]
if 'bika_inactive_workflow' in wf_ids \
and 'bika_inactive_workflow' not in self.contentFilter:
self.contentFilter['inactive_state'] = 'active'
elif 'bika_cancellation_workflow' in wf_ids \
and 'bika_inactive_workflow' not in self.contentFilter:
self.contentFilter['cancellation_state'] = 'active'
brains = catalog(self.contentFilter)
items = [('', '')] if allow_blank else []
for brain in brains:
if self.key in brain and self.value in brain:
key = getattr(brain, self.key)
value = getattr(brain, self.value)
else:
obj = brain.getObjec()
key = obj[self.key]
key = callable(key) and key() or key
value = obj[self.value]
value = callable(value) and value() or value
items.append((key, t(value)))
return DisplayList(items)
class BikaContentVocabulary(object):
"""Vocabulary factory for Bika Setup objects. We find them by listing
folder contents directly.
"""
implements(IVocabularyFactory)
def __init__(self, folders, portal_types):
self.folders = isinstance(folders, (tuple, list)) and \
folders or [folders, ]
self.portal_types = isinstance(portal_types, (tuple, list)) and \
portal_types or [portal_types, ]
def __call__(self, context):
site = getSite()
request = aq_get(site, 'REQUEST', None)
items = []
wf = site.portal_workflow
for folder in self.folders:
folder = site.restrictedTraverse(folder)
for portal_type in self.portal_types:
objects = list(folder.objectValues(portal_type))
objects = [o for o in objects if
wf.getInfoFor(o, 'inactive_state') == 'active']
if not objects:
continue
objects.sort(lambda x, y: cmp(x.Title().lower(),
y.Title().lower()))
xitems = [(t(item.Title()), item.Title()) for item in objects]
xitems = [SimpleTerm(i[1], i[1], i[0]) for i in xitems]
items += xitems
return SimpleVocabulary(items)
class BikaCatalogTypesVocabulary(object):
"""Vocabulary factory for really user friendly portal types,
filtered to return only types listed as indexed by bika_catalog
"""
implements(IVocabularyFactory)
def __call__(self, context):
translate = context.translate
types = (
('AnalysisRequest', translate(to_utf8(_('Analysis Request')))),
('Batch', translate(to_utf8(_('Batch')))),
('Sample', translate(to_utf8(_('Sample')))),
('ReferenceSample', translate(to_utf8(_('Reference Sample')))),
('Worksheet', translate(to_utf8(_('Worksheet'))))
)
items = [SimpleTerm(i[0], i[0], i[1]) for i in types]
return SimpleVocabulary(items)
BikaCatalogTypesVocabularyFactory = BikaCatalogTypesVocabulary()
class AnalysisCategoryVocabulary(BikaContentVocabulary):
"""" AnalysisCategories
>>> portal = layer['portal']
>>> from plone.app.testing import TEST_USER_NAME
>>> from plone.app.testing import TEST_USER_ID
>>> from plone.app.testing import setRoles
>>> from plone.app.testing import login
>>> login(portal, TEST_USER_NAME)
>>> setRoles(portal, TEST_USER_ID, ['Manager',])
>>> from zope.component import queryUtility
>>> name = 'bika.lims.vocabularies.AnalysisCategories'
>>> util = queryUtility(IVocabularyFactory, name)
>>> folder = portal.bika_setup.bika_analysiscategories
>>> objects = folder.objectValues()
>>> len(objects)
3
>>> source = util(portal)
>>> source
<zope.schema.vocabulary.SimpleVocabulary object at ...>
>>> 'Water Chemistry' in source.by_token
True
"""
def __init__(self):
BikaContentVocabulary.__init__(self,
['bika_setup/bika_analysiscategories', ],
['AnalysisCategory', ])
AnalysisCategoryVocabularyFactory = AnalysisCategoryVocabulary()
class AnalysisProfileVocabulary(BikaContentVocabulary):
def __init__(self):
BikaContentVocabulary.__init__(self,
['bika_setup/bika_analysisprofiles', ],
['AnalysisProfile', ])
AnalysisProfileVocabularyFactory = AnalysisProfileVocabulary()
class StorageLocationVocabulary(BikaContentVocabulary):
def __init__(self):
BikaContentVocabulary.__init__(self,
['bika_setup/bika_storagelocations', ],
['StorageLocation', ])
StorageLocationVocabularyFactory = StorageLocationVocabulary()
class SamplePointVocabulary(BikaContentVocabulary):
def __init__(self):
BikaContentVocabulary.__init__(self,
['bika_setup/bika_samplepoints', ],
['SamplePoint', ])
SamplePointVocabularyFactory = SamplePointVocabulary()
class SampleTypeVocabulary(BikaContentVocabulary):
def __init__(self):
BikaContentVocabulary.__init__(self,
['bika_setup/bika_sampletypes', ],
['SampleType', ])
SampleTypeVocabularyFactory = SampleTypeVocabulary()
class AnalysisServiceVocabulary(BikaContentVocabulary):
def __init__(self):
BikaContentVocabulary.__init__(self,
['bika_setup/bika_analysisservices', ],
['AnalysisService', ])
AnalysisServiceVocabularyFactory = AnalysisServiceVocabulary()
class ClientVocabulary(BikaContentVocabulary):
def __init__(self):
BikaContentVocabulary.__init__(self,
['clients', ],
['Client', ])
ClientVocabularyFactory = ClientVocabulary()
class UserVocabulary(object):
""" Present a vocabulary containing users in the specified
list of roles
>>> from zope.component import queryUtility
>>> portal = layer['portal']
>>> name = 'bika.lims.vocabularies.Users'
>>> util = queryUtility(IVocabularyFactory, name)
>>> tool = portal.portal_registration
>>> tool.addMember('user1', 'user1',
... properties = {
... 'username': 'user1',
... 'email': '[email protected]',
... 'fullname': 'user1'}
... )
<MemberData at /plone/portal_memberdata/user1 used for /plone/acl_users>
>>> source = util(portal)
>>> source
<zope.schema.vocabulary.SimpleVocabulary object at ...>
>>> 'test_user_1_' in source.by_value
True
>>> 'user1' in source.by_value
True
"""
implements(IVocabularyFactory)
def __init__(self, roles=[]):
self.roles = roles if isinstance(roles, (tuple, list)) else [roles, ]
def __call__(self, context):
site = getSite()
mtool = getToolByName(site, 'portal_membership')
users = mtool.searchForMembers(roles=self.roles)
items = [(item.getProperty('fullname'), item.getId())
for item in users]
items.sort(lambda x, y: cmp(x[0].lower(), y[0].lower()))
items = [SimpleTerm(i[1], i[1], i[0]) for i in items]
return SimpleVocabulary(items)
UserVocabularyFactory = UserVocabulary()
ClientVocabularyFactory = ClientVocabulary()
class ClientContactVocabulary(object):
""" Present Client Contacts
>>> from zope.component import queryUtility
>>> portal = layer['portal']
>>> name = 'bika.lims.vocabularies.ClientContacts'
>>> util = queryUtility(IVocabularyFactory, name)
>>> from plone.app.testing import TEST_USER_NAME
>>> from plone.app.testing import TEST_USER_ID
>>> from plone.app.testing import setRoles
>>> from plone.app.testing import login
>>> login(portal, TEST_USER_NAME)
>>> setRoles(portal, TEST_USER_ID, ['Manager',])
>>> portal.clients.invokeFactory('Client', id='client1')
'client1'
>>> client1 = portal.clients.client1
>>> client1.processForm()
>>> client1.invokeFactory('Contact', id='contact1')
'contact1'
>>> contact1 = client1.contact1
>>> contact1.processForm()
>>> contact1.edit(Firstname='Contact', Surname='One')
>>> contact1.reindexObject()
>>> source = util(portal)
>>> source
<zope.schema.vocabulary.SimpleVocabulary object at ...>
>>> 'Contact One' in source.by_value
True
"""
implements(IVocabularyFactory)
def __call__(self, context):
site = getSite()
request = aq_get(site, 'REQUEST', None)
items = []
for client in site.clients.objectValues('Client'):
objects = list(client.objectValues('Contact'))
objects.sort(lambda x, y: cmp(x.getFullname().lower(),
y.getFullname().lower()))
xitems = [(to_utf8(item.getFullname()), item.getFullname())
for item in objects]
xitems = [SimpleTerm(i[1], i[1], i[0]) for i in xitems]
items += xitems
return SimpleVocabulary(items)
ClientContactVocabularyFactory = ClientContactVocabulary()
class AnalystVocabulary(UserVocabulary):
def __init__(self):
UserVocabulary.__init__(self, roles=['Analyst', ])
AnalystVocabularyFactory = AnalystVocabulary()
class AnalysisRequestWorkflowStateVocabulary(object):
"""Vocabulary factory for workflow states.
>>> from zope.component import queryUtility
>>> portal = layer['portal']
>>> name = 'bika.lims.vocabularies.AnalysisRequestWorkflowStates'
>>> util = queryUtility(IVocabularyFactory, name)
>>> tool = getToolByName(portal, "portal_workflow")
>>> states = util(portal)
>>> states
<zope.schema.vocabulary.SimpleVocabulary object at ...>
>>> pub = states.by_token['published']
>>> pub.title, pub.token, pub.value
(u'Published', 'published', 'published')
"""
implements(IVocabularyFactory)
def __call__(self, context):
portal = getSite()
wftool = getToolByName(portal, 'portal_workflow', None)
if wftool is None:
return SimpleVocabulary([])
# XXX This is evil. A vocabulary shouldn't be request specific.
# The sorting should go into a separate widget.
# we get REQUEST from wftool because context may be an adapter
request = aq_get(wftool, 'REQUEST', None)
wf = wftool.getWorkflowById('bika_ar_workflow')
items = wftool.listWFStatesByTitle(filter_similar=True)
items_dict = dict([(i[1], t(i[0])) for i in items])
items_list = [(k, v) for k, v in items_dict.items()]
items_list.sort(lambda x, y: cmp(x[1], y[1]))
terms = [SimpleTerm(k, title=u'%s' % v) for k, v in items_list]
return SimpleVocabulary(terms)
AnalysisRequestWorkflowStateVocabularyFactory = \
AnalysisRequestWorkflowStateVocabulary()
def getTemplates(bikalims_path, restype, filter_by_type=False):
""" Returns an array with the Templates available in the Bika LIMS path
specified plus the templates from the resources directory specified and
available on each additional product (restype).
Each array item is a dictionary with the following structure:
{'id': <template_id>,
'title': <template_title>}
If the template lives outside the bika.lims add-on, both the template_id
and template_title include a prefix that matches with the add-on
identifier. template_title is the same name as the id, but with
whitespaces and without extension.
As an example, for a template from the my.product add-on located in
<restype> resource dir, and with a filename "My_cool_report.pt", the
dictionary will look like:
{'id': 'my.product:My_cool_report.pt',
'title': 'my.product: My cool report'}
:param bikalims_path: the path inside bika lims to find the stickers.
:type bikalims_path: an string as a path
:param restype: the resource directory type to search for inside
an addon.
:type restype: string
:param filter_by_type: the folder name to look for inside the
templates path
:type filter_by_type: string/boolean
"""
# Retrieve the templates from bika.lims add-on
templates_dir = resource_filename("bika.lims", bikalims_path)
tempath = os.path.join(templates_dir, '*.pt')
templates = [os.path.split(x)[-1] for x in glob.glob(tempath)]
# Retrieve the templates from other add-ons
for templates_resource in iterDirectoriesOfType(restype):
prefix = templates_resource.__name__
if prefix == 'bika.lims':
continue
directory = templates_resource.directory
# Only use the directory asked in 'filter_by_type'
if filter_by_type:
directory = directory + '/' + filter_by_type
if os.path.isdir(directory):
dirlist = os.listdir(directory)
exts = ['{0}:{1}'.format(prefix, tpl) for tpl in dirlist if
tpl.endswith('.pt')]
templates.extend(exts)
out = []
templates.sort()
for template in templates:
title = template[:-3]
title = title.replace('_', ' ')
title = title.replace(':', ': ')
out.append({'id': template,
'title': title})
return out
def getARReportTemplates():
""" Returns an array with the AR Templates available in Bika LIMS plus the
templates from the 'reports' resources directory type from each
additional product.
Each array item is a dictionary with the following structure:
{'id': <template_id>,
'title': <template_title>}
If the template lives outside the bika.lims add-on, both the template_id
and template_title include a prefix that matches with the add-on
identifier. template_title is the same name as the id, but with
whitespaces and without extension.
As an example, for a template from the my.product add-on located in
templates/reports dir, and with a filename "My_cool_report.pt", the
dictionary will look like:
{'id': 'my.product:My_cool_report.pt',
'title': 'my.product: My cool report'}
"""
resdirname = 'reports'
p = os.path.join("browser", "analysisrequest", "templates", resdirname)
return getTemplates(p, resdirname)
class ARReportTemplatesVocabulary(object):
"""Locate all ARReport templates to allow user to set the default
"""
implements(IVocabularyFactory)
def __call__(self, context):
out = [SimpleTerm(x['id'], x['id'], x['title']) for x in
getARReportTemplates()]
return SimpleVocabulary(out)
def getStickerTemplates(filter_by_type=False):
""" Returns an array with the sticker templates available. Retrieves the
TAL templates saved in templates/stickers folder.
Each array item is a dictionary with the following structure:
{'id': <template_id>,
'title': <template_title>}
If the template lives outside the bika.lims add-on, both the template_id
and template_title include a prefix that matches with the add-on
identifier. template_title is the same name as the id, but with
whitespaces and without extension.
As an example, for a template from the my.product add-on located in
templates/stickers, and with a filename "EAN128_default_small.pt", the
dictionary will look like:
{'id': 'my.product:EAN128_default_small.pt',
'title': 'my.product: EAN128 default small'}
If filter by type is given in the request, only the templates under
the path with the type name will be rendered given as vocabulary.
Example: If filter_by_type=='worksheet', only *.tp files under a
folder with this name will be displayed.
:param filter_by_type:
:type filter_by_type: string/bool.
:returns: an array with the sticker templates available
"""
# Retrieve the templates from bika.lims add-on
# resdirname
resdirname = 'stickers'
if filter_by_type:
bikalims_path = os.path.join(
"browser", "templates", resdirname, filter_by_type)
else:
bikalims_path = os.path.join("browser", "templates", resdirname)
# getTemplates needs two parameters, the first one is the bikalims path
# where the stickers will be found. The second one is the resource
# directory type. This allows us to filter stickers by the type we want.
return getTemplates(bikalims_path, resdirname, filter_by_type)
class StickerTemplatesVocabulary(object):
""" Locate all sticker templates
"""
implements(IVocabularyFactory)
def __call__(self, context):
out = [SimpleTerm(x['id'], x['id'], x['title']) for x in
getStickerTemplates()]
return SimpleVocabulary(out)
ARReportTemplatesVocabularyFactory = ARReportTemplatesVocabulary()
class CustomPubPrefVocabulary(object):
implements(IVocabularyFactory)
def __call__(self, context):
items = [
(_('Email'),'email'),
(_('PDF'), 'pdf')
]
for name, item in getAdapters((context, ), ICustomPubPref):
items.append(item)
return SimpleVocabulary.fromItems(items)
CustomPubPrefVocabularyFactory = CustomPubPrefVocabulary()