Passed
Push — master ( feb3de...56c573 )
by Jordi
04:25
created

build.bika.lims.setuphandlers.hide_navbar_items()   A

Complexity

Conditions 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 12
rs 10
c 0
b 0
f 0
cc 3
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
from Products.CMFCore.utils import getToolByName
9
from bika.lims import logger
10
from bika.lims.catalog import getCatalogDefinitions
11
from bika.lims.catalog import setup_catalogs
12
from bika.lims.config import *
13
14
GROUPS = {
15
    # Dictionary {group_name: [roles]}
16
    "Analysts": ["Analyst", ],
17
    "Clients": ["Client", ],
18
    "LabClerks": ["LabClerk",],
19
    # TODO Unbound LabManagers from Manager role
20
    "LabManagers": ["LabManager", "Manager", ],
21
    "Preservers": ["Perserver", ],
22
    "Publishers": ["Publisher", ],
23
    "Verifiers": ["Verifier", ],
24
    "Samplers": ["Sampler", ],
25
    "RegulatoryInspectors": ["RegulatoryInspector", ],
26
    "SamplingCoordinators": ["SamplingCoordinator", ],
27
}
28
29
NAV_BAR_ITEMS_TO_HIDE = (
30
    # List of items to hide from navigation bar
31
    "arimports",
32
    "pricelists",
33
    "supplyorders",
34
)
35
36
# noinspection PyClassHasNoInit
37
class Empty:
38
    pass
39
40
41
class BikaGenerator(object):
42
    def __init__(self):
43
        pass
44
45
    def setupPortalContent(self, portal):
46
        """ Setup Bika site structure """
47
        self.remove_default_content(portal)
48
        self.reindex_structure(portal)
49
50
        portal.bika_setup.laboratory.unmarkCreationFlag()
51
        portal.bika_setup.laboratory.reindexObject()
52
53
    def reindex_structure(self, portal):
54
        # index objects - importing through GenericSetup doesn't
55
        for obj_id in ('clients',
56
                       'batches',
57
                       'pricelists',
58
                       'bika_setup',
59
                       'methods',
60
                       'analysisrequests',
61
                       'referencesamples',
62
                       'supplyorders',
63
                       'worksheets',
64
                       'reports',
65
                       ):
66
            try:
67
                obj = portal[obj_id]
68
                obj.unmarkCreationFlag()
69
                obj.reindexObject()
70
            except AttributeError:
71
                pass
72
73
        for obj_id in ('bika_analysiscategories',
74
                       'bika_analysisservices',
75
                       'bika_attachmenttypes',
76
                       'bika_batchlabels',
77
                       'bika_calculations',
78
                       'bika_departments',
79
                       'bika_containers',
80
                       'bika_containertypes',
81
                       'bika_preservations',
82
                       'bika_identifiertypes',
83
                       'bika_instruments',
84
                       'bika_instrumenttypes',
85
                       'bika_instrumentlocations',
86
                       'bika_analysisspecs',
87
                       'bika_analysisprofiles',
88
                       'bika_artemplates',
89
                       'bika_labcontacts',
90
                       'bika_labproducts',
91
                       'bika_manufacturers',
92
                       'bika_sampleconditions',
93
                       'bika_samplematrices',
94
                       'bika_samplingdeviations',
95
                       'bika_samplepoints',
96
                       'bika_sampletypes',
97
                       'bika_srtemplates',
98
                       'bika_reflexrulefolder',
99
                       'bika_storagelocations',
100
                       'bika_subgroups',
101
                       'bika_suppliers',
102
                       'bika_referencedefinitions',
103
                       'bika_worksheettemplates'):
104
            try:
105
                obj = portal.bika_setup[obj_id]
106
                obj.unmarkCreationFlag()
107
                obj.reindexObject()
108
            except AttributeError:
109
                pass
110
111
    def remove_default_content(self, portal):
112
        # remove undesired content objects
113
        del_ids = []
114
        for obj_id in ['Members', 'news', 'events']:
115
            if obj_id in portal:
116
                del_ids.append(obj_id)
117
        if del_ids:
118
            portal.manage_delObjects(ids=del_ids)
119
120
    def setupGroupsAndRoles(self, portal):
121
        # Create groups
122
        groups_ids = portal.portal_groups.listGroupIds()
123
        groups_ids = filter(lambda gr: gr not in groups_ids, GROUPS.keys())
124
        for group_id in groups_ids:
125
            portal.portal_groups.addGroup(group_id, title=group_id,
126
                                          roles=GROUPS[group_id])
127
128
    def setupCatalogs(self, portal):
129
        # an item should belong to only one catalog.
130
        # that way looking it up means first looking up *the* catalog
131
        # in which it is indexed, as well as making it cheaper to index.
132
133
        def addIndex(cat, *args):
134
            # noinspection PyBroadException
135
            try:
136
                cat.addIndex(*args)
137
            except:
138
                pass
139
140
        def addColumn(cat, col):
141
            # noinspection PyBroadException
142
            try:
143
                cat.addColumn(col)
144
            except:
145
                pass
146
147
        # create lexicon
148
        wordSplitter = Empty()
149
        wordSplitter.group = 'Word Splitter'
150
        wordSplitter.name = 'Unicode Whitespace splitter'
151
        caseNormalizer = Empty()
152
        caseNormalizer.group = 'Case Normalizer'
153
        caseNormalizer.name = 'Unicode Case Normalizer'
154
        stopWords = Empty()
155
        stopWords.group = 'Stop Words'
156
        stopWords.name = 'Remove listed and single char words'
157
        elem = [wordSplitter, caseNormalizer, stopWords]
158
        zc_extras = Empty()
159
        zc_extras.index_type = 'Okapi BM25 Rank'
160
        zc_extras.lexicon_id = 'Lexicon'
161
162
        # bika_catalog
163
164
        bc = getToolByName(portal, 'bika_catalog', None)
165
        if bc is None:
166
            logger.warning('Could not find the bika_catalog tool.')
167
            return
168
169
        # noinspection PyBroadException
170
        try:
171
            bc.manage_addProduct['ZCTextIndex'].manage_addLexicon(
172
                'Lexicon', 'Lexicon', elem)
173
        except:
174
            logger.warning('Could not add ZCTextIndex to bika_catalog')
175
            pass
176
177
        at = getToolByName(portal, 'archetype_tool')
178
        at.setCatalogsByType('Batch', ['bika_catalog', 'portal_catalog'])
179
        # TODO Remove in >v1.3.0
180
        at.setCatalogsByType('Sample', ['bika_catalog', 'portal_catalog'])
181
        # TODO Remove in >v1.3.0
182
        at.setCatalogsByType('SamplePartition',
183
                             ['bika_catalog', 'portal_catalog'])
184
        at.setCatalogsByType('ReferenceSample',
185
                             ['bika_catalog', 'portal_catalog'])
186
187
        addIndex(bc, 'path', 'ExtendedPathIndex', 'getPhysicalPath')
188
        addIndex(bc, 'allowedRolesAndUsers', 'KeywordIndex')
189
        addIndex(bc, 'UID', 'FieldIndex')
190
        addIndex(bc, 'SearchableText', 'ZCTextIndex', zc_extras)
191
        addIndex(bc, 'Title', 'ZCTextIndex', zc_extras)
192
        addIndex(bc, 'Description', 'ZCTextIndex', zc_extras)
193
        addIndex(bc, 'id', 'FieldIndex')
194
        addIndex(bc, 'getId', 'FieldIndex')
195
        addIndex(bc, 'Type', 'FieldIndex')
196
        addIndex(bc, 'portal_type', 'FieldIndex')
197
        addIndex(bc, 'created', 'DateIndex')
198
        addIndex(bc, 'Creator', 'FieldIndex')
199
        addIndex(bc, 'getObjPositionInParent', 'GopipIndex')
200
        addIndex(bc, 'title', 'FieldIndex', 'Title')
201
        addIndex(bc, 'sortable_title', 'FieldIndex')
202
        addIndex(bc, 'description', 'FieldIndex', 'Description')
203
        addIndex(bc, 'review_state', 'FieldIndex')
204
        addIndex(bc, 'Identifiers', 'KeywordIndex')
205
        addIndex(bc, 'is_active', 'BooleanIndex')
206
        addIndex(bc, 'BatchDate', 'DateIndex')
207
        addIndex(bc, 'getClientTitle', 'FieldIndex')
208
        addIndex(bc, 'getClientUID', 'FieldIndex')
209
        addIndex(bc, 'getClientID', 'FieldIndex')
210
        addIndex(bc, 'getClientBatchID', 'FieldIndex')
211
        addIndex(bc, 'getDateReceived', 'DateIndex')
212
        addIndex(bc, 'getDateSampled', 'DateIndex')
213
        addIndex(bc, 'getDueDate', 'DateIndex')
214
        addIndex(bc, 'getExpiryDate', 'DateIndex')
215
        addIndex(bc, 'getReferenceDefinitionUID', 'FieldIndex')
216
        addIndex(bc, 'getSampleTypeTitle', 'FieldIndex')
217
        addIndex(bc, 'getSampleTypeUID', 'FieldIndex')
218
219
        # https://github.com/senaite/senaite.core/pull/1091
220
        addIndex(bc, 'getSupportedServices', 'KeywordIndex')
221
        addIndex(bc, 'getBlank', 'BooleanIndex')
222
        addIndex(bc, 'isValid', 'BooleanIndex')
223
224
        addColumn(bc, 'path')
225
        addColumn(bc, 'UID')
226
        addColumn(bc, 'id')
227
        addColumn(bc, 'getId')
228
        addColumn(bc, 'Type')
229
        addColumn(bc, 'portal_type')
230
        addColumn(bc, 'creator')
231
        addColumn(bc, 'Created')
232
        addColumn(bc, 'Title')
233
        addColumn(bc, 'Description')
234
        addColumn(bc, 'sortable_title')
235
        addColumn(bc, 'getClientTitle')
236
        addColumn(bc, 'getClientID')
237
        addColumn(bc, 'getClientBatchID')
238
        addColumn(bc, 'getSampleTypeTitle')
239
        addColumn(bc, 'getDateReceived')
240
        addColumn(bc, 'getDateSampled')
241
        addColumn(bc, 'review_state')
242
243
        # bika_setup_catalog
244
245
        bsc = getToolByName(portal, 'bika_setup_catalog', None)
246
        if bsc is None:
247
            logger.warning('Could not find the setup catalog tool.')
248
            return
249
250
        # noinspection PyBroadException
251
        try:
252
            bsc.manage_addProduct['ZCTextIndex'].manage_addLexicon(
253
                'Lexicon', 'Lexicon', elem)
254
        except:
255
            logger.warning('Could not add ZCTextIndex to bika_setup_catalog')
256
            pass
257
258
        at = getToolByName(portal, 'archetype_tool')
259
        at.setCatalogsByType('Department',
260
                             ['bika_setup_catalog', "portal_catalog", ])
261
        at.setCatalogsByType('Container', ['bika_setup_catalog', ])
262
        at.setCatalogsByType('ContainerType', ['bika_setup_catalog', ])
263
        at.setCatalogsByType('AnalysisCategory', ['bika_setup_catalog', ])
264
        at.setCatalogsByType('AnalysisService',
265
                             ['bika_setup_catalog', 'portal_catalog'])
266
        at.setCatalogsByType('AnalysisSpec', ['bika_setup_catalog', ])
267
        at.setCatalogsByType('SampleCondition', ['bika_setup_catalog'])
268
        at.setCatalogsByType('SampleMatrix', ['bika_setup_catalog', ])
269
        at.setCatalogsByType('SampleType',
270
                             ['bika_setup_catalog', 'portal_catalog'])
271
        at.setCatalogsByType('SamplePoint',
272
                             ['bika_setup_catalog', 'portal_catalog'])
273
        at.setCatalogsByType('StorageLocation',
274
                             ['bika_setup_catalog', 'portal_catalog'])
275
        at.setCatalogsByType('SamplingDeviation', ['bika_setup_catalog', ])
276
        at.setCatalogsByType('IdentifierType', ['bika_setup_catalog', ])
277
        at.setCatalogsByType('Instrument',
278
                             ['bika_setup_catalog', 'portal_catalog'])
279
        at.setCatalogsByType('InstrumentType',
280
                             ['bika_setup_catalog', 'portal_catalog'])
281
        at.setCatalogsByType('InstrumentLocation',
282
                             ['bika_setup_catalog', 'portal_catalog'])
283
        at.setCatalogsByType('Method', ['bika_setup_catalog', 'portal_catalog'])
284
        at.setCatalogsByType('Multifile', ['bika_setup_catalog'])
285
        at.setCatalogsByType('AttachmentType', ['bika_setup_catalog', ])
286
        at.setCatalogsByType('Attachment', ['portal_catalog'])
287
        at.setCatalogsByType('Calculation',
288
                             ['bika_setup_catalog', 'portal_catalog'])
289
        at.setCatalogsByType('AnalysisProfile',
290
                             ['bika_setup_catalog', 'portal_catalog'])
291
        at.setCatalogsByType('ARTemplate',
292
                             ['bika_setup_catalog', 'portal_catalog'])
293
        at.setCatalogsByType('LabProduct',
294
                             ['bika_setup_catalog', 'portal_catalog'])
295
        at.setCatalogsByType('LabContact',
296
                             ['bika_setup_catalog', 'portal_catalog'])
297
        at.setCatalogsByType('Manufacturer',
298
                             ['bika_setup_catalog', 'portal_catalog'])
299
        at.setCatalogsByType('Preservation', ['bika_setup_catalog', ])
300
        at.setCatalogsByType('ReferenceDefinition',
301
                             ['bika_setup_catalog', 'portal_catalog'])
302
        at.setCatalogsByType('SRTemplate',
303
                             ['bika_setup_catalog', 'portal_catalog'])
304
        at.setCatalogsByType('SubGroup', ['bika_setup_catalog', ])
305
        at.setCatalogsByType('Supplier',
306
                             ['bika_setup_catalog', 'portal_catalog'])
307
        at.setCatalogsByType('Unit', ['bika_setup_catalog', ])
308
        at.setCatalogsByType('WorksheetTemplate',
309
                             ['bika_setup_catalog', 'portal_catalog'])
310
        at.setCatalogsByType('BatchLabel', ['bika_setup_catalog', ])
311
312
        addIndex(bsc, 'path', 'ExtendedPathIndex', 'getPhysicalPath')
313
        addIndex(bsc, 'allowedRolesAndUsers', 'KeywordIndex')
314
        addIndex(bsc, 'UID', 'FieldIndex')
315
        addIndex(bsc, 'SearchableText', 'ZCTextIndex', zc_extras)
316
        addIndex(bsc, 'Title', 'ZCTextIndex', zc_extras)
317
        addIndex(bsc, 'Description', 'ZCTextIndex', zc_extras)
318
        addIndex(bsc, 'id', 'FieldIndex')
319
        addIndex(bsc, 'getId', 'FieldIndex')
320
        addIndex(bsc, 'Type', 'FieldIndex')
321
        addIndex(bsc, 'portal_type', 'FieldIndex')
322
        addIndex(bsc, 'created', 'DateIndex')
323
        addIndex(bsc, 'Creator', 'FieldIndex')
324
        addIndex(bsc, 'getObjPositionInParent', 'GopipIndex')
325
        addIndex(bc, 'Identifiers', 'KeywordIndex')
326
327
        addIndex(bsc, 'title', 'FieldIndex', 'Title')
328
        addIndex(bsc, 'sortable_title', 'FieldIndex')
329
        addIndex(bsc, 'description', 'FieldIndex', 'Description')
330
331
        addIndex(bsc, 'review_state', 'FieldIndex')
332
333
        addIndex(bsc, 'getAccredited', 'FieldIndex')
334
        addIndex(bsc, 'getAnalyst', 'FieldIndex')
335
        addIndex(bsc, 'getBlank', 'FieldIndex')
336
        addIndex(bsc, 'getCalculationTitle', 'FieldIndex')
337
        addIndex(bsc, 'getCalculationUID', 'FieldIndex')
338
        addIndex(bsc, 'getCalibrationExpiryDate', 'FieldIndex')
339
        addIndex(bsc, 'getCategoryTitle', 'FieldIndex')
340
        addIndex(bsc, 'getCategoryUID', 'FieldIndex')
341
        addIndex(bsc, 'getClientUID', 'FieldIndex')
342
        addIndex(bsc, 'getDepartmentTitle', 'FieldIndex')
343
        addIndex(bsc, 'getDocumentID', 'FieldIndex')
344
        addIndex(bsc, 'getDuplicateVariation', 'FieldIndex')
345
        addIndex(bsc, 'getFormula', 'FieldIndex')
346
        addIndex(bsc, 'getFullname', 'FieldIndex')
347
        addIndex(bsc, 'getHazardous', 'FieldIndex')
348
        addIndex(bsc, 'getInstrumentLocationName', 'FieldIndex')
349
        addIndex(bsc, 'getInstrumentTitle', 'FieldIndex')
350
        addIndex(bsc, 'getInstrumentType', 'FieldIndex')
351
        addIndex(bsc, 'getInstrumentTypeName', 'FieldIndex')
352
        addIndex(bsc, 'getKeyword', 'FieldIndex')
353
        addIndex(bsc, 'getManagerEmail', 'FieldIndex')
354
        addIndex(bsc, 'getManagerName', 'FieldIndex')
355
        addIndex(bsc, 'getManagerPhone', 'FieldIndex')
356
        addIndex(bsc, 'getMaxTimeAllowed', 'FieldIndex')
357
        addIndex(bsc, 'getMethodID', 'FieldIndex')
358
        addIndex(bsc, 'getAvailableMethodUIDs', 'KeywordIndex')
359
        addIndex(bsc, 'getModel', 'FieldIndex')
360
        addIndex(bsc, 'getName', 'FieldIndex')
361
        addIndex(bsc, 'getPointOfCapture', 'FieldIndex')
362
        addIndex(bsc, 'getPrice', 'FieldIndex')
363
        addIndex(bsc, 'getSamplePointTitle', 'KeywordIndex')
364
        addIndex(bsc, 'getSamplePointUID', 'FieldIndex')
365
        addIndex(bsc, 'getSampleTypeTitle', 'FieldIndex')
366
        addIndex(bsc, 'getSampleTypeTitles', 'KeywordIndex')
367
        addIndex(bsc, 'getSampleTypeUID', 'FieldIndex')
368
        addIndex(bsc, 'getServiceUID', 'FieldIndex')
369
        addIndex(bsc, 'getServiceUIDs', 'KeywordIndex')
370
        addIndex(bsc, 'getTotalPrice', 'FieldIndex')
371
        addIndex(bsc, 'getUnit', 'FieldIndex')
372
        addIndex(bsc, 'getVATAmount', 'FieldIndex')
373
        addIndex(bsc, 'getVolume', 'FieldIndex')
374
        addIndex(bsc, 'is_active', 'BooleanIndex')
375
376
        addColumn(bsc, 'path')
377
        addColumn(bsc, 'UID')
378
        addColumn(bsc, 'id')
379
        addColumn(bsc, 'getId')
380
        addColumn(bsc, 'Type')
381
        addColumn(bsc, 'portal_type')
382
        addColumn(bsc, 'getObjPositionInParent')
383
384
        addColumn(bsc, 'Title')
385
        addColumn(bsc, 'Description')
386
        addColumn(bsc, 'title')
387
        addColumn(bsc, 'sortable_title')
388
        addColumn(bsc, 'description')
389
        addColumn(bsc, 'review_state')
390
        addColumn(bsc, 'getAccredited')
391
        addColumn(bsc, 'getInstrumentType')
392
        addColumn(bsc, 'getInstrumentTypeName')
393
        addColumn(bsc, 'getInstrumentLocationName')
394
        addColumn(bsc, 'getBlank')
395
        addColumn(bsc, 'getCalculationTitle')
396
        addColumn(bsc, 'getCalculationUID')
397
        addColumn(bsc, 'getCalibrationExpiryDate')
398
        addColumn(bsc, 'getCategoryTitle')
399
        addColumn(bsc, 'getCategoryUID')
400
        addColumn(bsc, 'getClientUID')
401
        addColumn(bsc, 'getDepartmentTitle')
402
        addColumn(bsc, 'getDuplicateVariation')
403
        addColumn(bsc, 'getFormula')
404
        addColumn(bsc, 'getFullname')
405
        addColumn(bsc, 'getHazardous')
406
        addColumn(bsc, 'getInstrumentTitle')
407
        addColumn(bsc, 'getKeyword')
408
        addColumn(bsc, 'getManagerName')
409
        addColumn(bsc, 'getManagerPhone')
410
        addColumn(bsc, 'getManagerEmail')
411
        addColumn(bsc, 'getMaxTimeAllowed')
412
        addColumn(bsc, 'getModel')
413
        addColumn(bsc, 'getName')
414
        addColumn(bsc, 'getPointOfCapture')
415
        addColumn(bsc, 'getPrice')
416
        addColumn(bsc, 'getSamplePointTitle')
417
        addColumn(bsc, 'getSamplePointUID')
418
        addColumn(bsc, 'getSampleTypeTitle')
419
        addColumn(bsc, 'getSampleTypeUID')
420
        addColumn(bsc, 'getServiceUID')
421
        addColumn(bsc, 'getTotalPrice')
422
        addColumn(bsc, 'getUnit')
423
        addColumn(bsc, 'getVATAmount')
424
        addColumn(bsc, 'getVolume')
425
426
        # portal_catalog
427
        pc = getToolByName(portal, 'portal_catalog', None)
428
        if pc is None:
429
            logger.warning('Could not find the portal_catalog tool.')
430
            return
431
        addIndex(pc, 'Analyst', 'FieldIndex')
432
        addColumn(pc, 'Analyst')
433
        # TODO: Nmrl
434
        addColumn(pc, 'getProvince')
435
        addColumn(pc, 'getDistrict')
436
437
        # Setting up all LIMS catalogs defined in catalog folder
438
        setup_catalogs(portal, getCatalogDefinitions())
439
440
441
def setupVarious(context):
442
    """
443
    Final Bika import steps.
444
    """
445
    if context.readDataFile('bika.lims_various.txt') is None:
446
        return
447
448
    site = context.getSite()
449
    gen = BikaGenerator()
450
    gen.setupGroupsAndRoles(site)
451
    gen.setupPortalContent(site)
452
    gen.setupCatalogs(site)
453
454
    # Hide navbar items no longer used
455
    # https://github.com/senaite/senaite.core/pull/1304
456
    hide_navbar_items(site)
457
458
459
def hide_navbar_items(portal):
460
    """Remove navbar items that are no longer used
461
    """
462
    logger.info("Removing items from navigation bar ...")
463
464
    # Get the list of object ids for portal
465
    object_ids = portal.objectIds()
466
    object_ids = filter(lambda id: id in object_ids, NAV_BAR_ITEMS_TO_HIDE)
467
    for object_id in object_ids:
468
        item = portal[object_id]
469
        item.setExcludeFromNav(True)
470
        item.reindexObject()